import { cU as fe, cV as Qe, cW as oe, cX as qe, cY as Ue, cZ as xe, c_ as ze, c$ as Ee, d0 as Oe } from "./index-BJZQSU1O.mjs";
class Be extends Error {
  constructor({ message: t, name: n, statusCode: r, data: o }) {
    super(t), this.name = n, this.statusCode = r, this.data = o;
  }
}
class Je extends Be {
  constructor(t = "Something went wrong.", n = {}) {
    super({
      message: t,
      name: "UnexpectedServerError",
      statusCode: 500,
      data: n
    });
  }
}
class te extends Be {
  constructor(t = "Invalid index in array.", n = {}) {
    super({
      message: t,
      name: "UnexpectedIndexError",
      statusCode: 500,
      data: n
    });
  }
}
var Z = /* @__PURE__ */ ((e) => (e.DEFAULT = "default", e.COMMA_PERIOD = "commaPeriod", e.SPACE_PERIOD = "spacePeriod", e.PERIOD_COMMA = "periodComma", e.NO_SEPARATOR_PERIOD = "noSeparatorPeriod", e))(Z || {});
const Ae = {
  thousands: {
    compact: "thousands",
    alias: ["K", "thousand"],
    orderOfMagnitude: 3,
    convertFn: (e) => e / 1e3,
    label: "thousands (K)",
    suffix: "K"
  },
  millions: {
    compact: "millions",
    alias: ["M", "million"],
    orderOfMagnitude: 6,
    convertFn: (e) => e / 1e6,
    label: "millions (M)",
    suffix: "M"
  },
  billions: {
    compact: "billions",
    alias: ["B", "billion"],
    orderOfMagnitude: 9,
    convertFn: (e) => e / 1e9,
    label: "billions (B)",
    suffix: "B"
  },
  trillions: {
    compact: "trillions",
    alias: ["T", "trillion"],
    orderOfMagnitude: 12,
    convertFn: (e) => e / 1e12,
    label: "trillions (T)",
    suffix: "T"
  },
  kilobytes: {
    compact: "kilobytes",
    alias: ["KB", "kilobyte"],
    orderOfMagnitude: 3,
    convertFn: (e) => e / 1e3,
    label: "kilobytes (KB)",
    suffix: "KB"
  },
  megabytes: {
    compact: "megabytes",
    alias: ["MB", "megabyte"],
    orderOfMagnitude: 6,
    convertFn: (e) => e / 1e6,
    label: "megabytes (MB)",
    suffix: "MB"
  },
  gigabytes: {
    compact: "gigabytes",
    alias: ["GB", "gigabyte"],
    orderOfMagnitude: 9,
    convertFn: (e) => e / 1e9,
    label: "gigabytes (GB)",
    suffix: "GB"
  },
  terabytes: {
    compact: "terabytes",
    alias: ["TB", "terabyte"],
    orderOfMagnitude: 12,
    convertFn: (e) => e / 1e12,
    label: "terabytes (TB)",
    suffix: "TB"
  },
  petabytes: {
    compact: "petabytes",
    alias: ["PB", "petabyte"],
    orderOfMagnitude: 15,
    convertFn: (e) => e / 1e15,
    label: "petabytes (PB)",
    suffix: "PB"
  },
  kibibytes: {
    compact: "kibibytes",
    alias: ["KiB", "kibibyte"],
    orderOfMagnitude: -1,
    convertFn: (e) => e / 1024,
    label: "kibibytes (KiB)",
    suffix: "KiB"
  },
  mebibytes: {
    compact: "mebibytes",
    alias: ["MiB", "mebibyte"],
    orderOfMagnitude: -1,
    convertFn: (e) => e / 1048576,
    label: "mebibytes (MiB)",
    suffix: "MiB"
  },
  gibibytes: {
    compact: "gibibytes",
    alias: ["GiB", "gibibyte"],
    orderOfMagnitude: -1,
    convertFn: (e) => e / 1073741824,
    label: "gibibytes (GiB)",
    suffix: "GiB"
  },
  tebibytes: {
    compact: "tebibytes",
    alias: ["TiB", "tebibyte"],
    orderOfMagnitude: -1,
    convertFn: (e) => e / 1099511627776,
    label: "tebibytes (TiB)",
    suffix: "TiB"
  },
  pebibytes: {
    compact: "pebibytes",
    alias: ["PiB", "pebibyte"],
    orderOfMagnitude: -1,
    convertFn: (e) => e / 1125899906842624,
    label: "pebibytes (PiB)",
    suffix: "PiB"
  }
};
function Ze(e) {
  return Object.values(Ae).find(
    ({ compact: t, alias: n }) => t === e || n.includes(e)
  );
}
var Ve = /* @__PURE__ */ ((e) => (e.BIN = "bin", e.SQL = "sql", e))(Ve || {});
const de = (e) => e !== void 0 && Object.values(Ve).includes(e.type), et = (e) => e !== void 0 && de(e) && e.type === "bin", Fe = (e) => e !== void 0 && de(e) && e.type === "sql";
var D = /* @__PURE__ */ ((e) => (e.DEFAULT = "default", e.PERCENT = "percent", e.CURRENCY = "currency", e.NUMBER = "number", e.ID = "id", e.DATE = "date", e.TIMESTAMP = "timestamp", e.BYTES_SI = "bytes_si", e.BYTES_IEC = "bytes_iec", e.CUSTOM = "custom", e))(D || {}), ee = /* @__PURE__ */ ((e) => (e.NUMBER = "number", e.STRING = "string", e.DATE = "date", e.TIMESTAMP = "timestamp", e.BOOLEAN = "boolean", e))(ee || {}), Y = /* @__PURE__ */ ((e) => (e.METRIC = "metric", e.DIMENSION = "dimension", e))(Y || {});
const Me = (e) => e ? !de(e) && (!!("sql" in e && e.sql) || !!("template" in e && e.template)) && !("description" in e) && !("tableName" in e) && "displayName" in e : !1, Se = (e) => e ? !!e.fieldType : !1;
var k = /* @__PURE__ */ ((e) => (e.STRING = "string", e.NUMBER = "number", e.TIMESTAMP = "timestamp", e.DATE = "date", e.BOOLEAN = "boolean", e))(k || {});
const H = (e) => Se(e) && e.fieldType === "dimension";
var M = /* @__PURE__ */ ((e) => (e.PERCENTILE = "percentile", e.AVERAGE = "average", e.COUNT = "count", e.COUNT_DISTINCT = "count_distinct", e.SUM = "sum", e.SUM_DISTINCT = "sum_distinct", e.AVERAGE_DISTINCT = "average_distinct", e.MIN = "min", e.MAX = "max", e.PERCENT_OF_PREVIOUS = "percent_of_previous", e.PERCENT_OF_TOTAL = "percent_of_total", e.RUNNING_TOTAL = "running_total", e.NUMBER = "number", e.MEDIAN = "median", e.STRING = "string", e.DATE = "date", e.TIMESTAMP = "timestamp", e.BOOLEAN = "boolean", e))(M || {}), $ = /* @__PURE__ */ ((e) => (e.KM = "km", e.MI = "mi", e.USD = "usd", e.GBP = "gbp", e.EUR = "eur", e.JPY = "jpy", e.DKK = "dkk", e.ID = "id", e.PERCENT = "percent", e))($ || {});
const tt = (e) => !!e && Object.values($).includes(e), nt = (e) => e ? "fieldType" in e && e.fieldType === "metric" : !1, Ce = (e) => {
  if (!e || Me(e) || de(e))
    return !1;
  const t = [
    "count",
    "sum"
    /* SUM */
  ], n = H(e) && e.type === "number", r = t.includes(e.type) || n, o = e.format === "percent", l = H(e) && e.timeInterval;
  return r && !o && !l;
}, ve = [
  "kibibytes",
  "mebibytes",
  "gibibytes",
  "tebibytes",
  "pebibytes"
  /* PEBIBYTES */
], se = (e, t, n) => {
  if (e === void 0)
    throw new te(
      `Cannot get key "${t}" value from empty array`
    );
  const r = e[t];
  if (r === void 0)
    throw console.trace(), new te(
      `Cannot get key "${t}" value from array`
    );
  return r;
}, Te = (e, t, n) => {
  if (e === void 0)
    throw new te(
      `Cannot get key "${t}" value from empty object`
    );
  const r = e[t];
  if (r === void 0)
    throw console.trace(), new te(
      `Cannot get key "${t}" value from object`
    );
  return r;
};
var Re = /* @__PURE__ */ ((e) => (e.PREFIX = "lightdash.parameters", e.PREFIX_SHORT = "ld.parameters", e))(Re || {});
const Pe = (e) => e?.table && e?.name && !e?.fieldType && !de(e), rt = (e) => !!e.formatOptions;
var P = /* @__PURE__ */ ((e) => (e.RAW = "RAW", e.YEAR = "YEAR", e.QUARTER = "QUARTER", e.MONTH = "MONTH", e.WEEK = "WEEK", e.DAY = "DAY", e.HOUR = "HOUR", e.MINUTE = "MINUTE", e.SECOND = "SECOND", e.MILLISECOND = "MILLISECOND", e.DAY_OF_WEEK_INDEX = "DAY_OF_WEEK_INDEX", e.DAY_OF_MONTH_NUM = "DAY_OF_MONTH_NUM", e.DAY_OF_YEAR_NUM = "DAY_OF_YEAR_NUM", e.WEEK_NUM = "WEEK_NUM", e.MONTH_NUM = "MONTH_NUM", e.QUARTER_NUM = "QUARTER_NUM", e.YEAR_NUM = "YEAR_NUM", e.DAY_OF_WEEK_NAME = "DAY_OF_WEEK_NAME", e.MONTH_NAME = "MONTH_NAME", e.QUARTER_NAME = "QUARTER_NAME", e.HOUR_OF_DAY_NUM = "HOUR_OF_DAY_NUM", e.MINUTE_OF_HOUR_NUM = "MINUTE_OF_HOUR_NUM", e))(P || {});
const Le = (e, t) => {
  throw typeof t == "string" ? Error(t) : t;
}, st = (e) => [
  ee.NUMBER,
  k.NUMBER,
  M.NUMBER,
  M.PERCENTILE,
  M.MEDIAN,
  M.AVERAGE,
  M.COUNT,
  M.COUNT_DISTINCT,
  M.SUM,
  M.SUM_DISTINCT,
  M.AVERAGE_DISTINCT,
  M.MIN,
  M.MAX,
  M.PERCENT_OF_PREVIOUS,
  M.PERCENT_OF_TOTAL,
  M.RUNNING_TOTAL
].includes(e);
function $e(e) {
  return H(e) || nt(e) ? e.type : Fe(e) ? e.dimensionType : et(e) ? k.STRING : Me(e) ? e.type ?? ee.NUMBER : Pe(e) ? e.type : k.STRING;
}
function ot(e) {
  return e ? st($e(e)) : !1;
}
Ue.extend(ze);
const at = (e) => ["True", "true", "yes", "Yes", "1", "T"].includes(`${e}`) ? "True" : "False", it = (e = P.DAY) => {
  switch (e) {
    case P.YEAR:
      return "YYYY";
    case P.QUARTER:
      return "YYYY-[Q]Q";
    case P.MONTH:
      return "YYYY-MM";
    default:
      return "YYYY-MM-DD";
  }
}, ct = (e = P.DAY) => {
  let t;
  switch (e) {
    case P.HOUR:
      t = "HH";
      break;
    case P.MINUTE:
      t = "HH:mm";
      break;
    case P.SECOND:
      t = "HH:mm:ss";
      break;
    default:
      t = "HH:mm:ss:SSS";
      break;
  }
  return `YYYY-MM-DD, ${t} (Z)`;
}, ge = (e) => typeof e == "string" || typeof e == "number" || e instanceof Date || e instanceof oe || e instanceof Ue;
function Ye(e, t = P.DAY, n = !1) {
  const r = n ? oe(e).utc() : oe(e);
  return r.isValid() ? r.format(it(t)) : "NaT";
}
function me(e, t = P.MILLISECOND, n = !1) {
  const r = n ? oe(e).utc() : oe(e);
  return r.isValid() ? r.format(ct(t)) : "NaT";
}
function lt(e, t) {
  const n = t?.type === D.CURRENCY && t?.currency, r = n ? { style: "currency", currency: t.currency } : {}, o = t?.round;
  if (o === void 0)
    return n ? r : {};
  if (o < 0)
    return {
      maximumSignificantDigits: Math.max(
        Math.floor(e).toString().length + o,
        1
      ),
      maximumFractionDigits: 0,
      ...r
    };
  const l = Math.min(o, 20);
  return {
    maximumFractionDigits: l,
    minimumFractionDigits: l,
    ...r
  };
}
function pe(e) {
  return typeof e == "boolean" ? !0 : Number.isNaN(Number(e));
}
function ut(e) {
  return !pe(e);
}
function ce(e, t) {
  const n = lt(e, t), r = t?.separator || Z.DEFAULT;
  switch (r) {
    case Z.COMMA_PERIOD:
      return e.toLocaleString("en-US", n);
    case Z.SPACE_PERIOD:
      return e.toLocaleString("en-US", n).replace(/,/g, " ");
    case Z.PERIOD_COMMA:
      return e.toLocaleString("de-DE", n);
    case Z.NO_SEPARATOR_PERIOD:
      return e.toLocaleString("en-US", {
        ...n,
        useGrouping: !1
      });
    case Z.DEFAULT:
      return e.toLocaleString(void 0, n);
    default:
      return Le(r, "Unknown separator");
  }
}
function le(e) {
  return e === null ? "∅" : e === void 0 ? "-" : ut(e) ? ce(e) : `${e}`;
}
function dt({
  format: e,
  compact: t,
  round: n
}) {
  switch (e) {
    case $.EUR:
    case $.GBP:
    case $.USD:
    case $.JPY:
    case $.DKK:
      return {
        type: D.CURRENCY,
        currency: e.toUpperCase(),
        compact: t,
        round: n
      };
    case $.KM:
    case $.MI:
      return {
        type: D.NUMBER,
        suffix: ` ${e}`,
        compact: t,
        round: n
      };
    case $.PERCENT:
      return {
        type: D.PERCENT,
        compact: t,
        round: n
      };
    case $.ID:
      return {
        type: D.ID
      };
    default:
      return {
        type: D.NUMBER,
        round: n,
        compact: t
      };
  }
}
function ft(e) {
  if (!e) return;
  if (rt(e))
    return e.formatOptions;
  if (Me(e))
    return e.format;
  const t = {
    ..."format" in e && { format: e.format },
    ..."compact" in e && { compact: e.compact },
    ..."round" in e && { round: e.round }
  };
  if (Object.keys(t).length > 0 || ot(e))
    return dt(t);
}
function _e(e, t) {
  if (t?.compact === void 0)
    return { compactValue: Number(e), compactSuffix: "" };
  const n = Ze(t.compact);
  if (n) {
    const r = n.convertFn(Number(e)), o = t.compact ? n.suffix : "";
    return { compactValue: r, compactSuffix: o };
  }
  return { compactValue: Number(e), compactSuffix: "" };
}
function Ke(e, t) {
  try {
    let n = t;
    if (typeof t == "bigint")
      if (t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER)
        n = Number(t);
      else
        throw new Error(
          "Can't format value as BigInt is out of safe integer range"
        );
    const o = ve.map(
      (l) => Ae[l].suffix
    ).find(
      (l) => e.includes(`"${l}"`)
    );
    if (o && !pe(Number(n))) {
      const l = Object.values(Ae).find(
        (A) => A.suffix === o && ve.includes(A.compact)
      );
      if (l) {
        const A = l.convertFn(
          Number(n)
        ), _ = e.replace(
          `"${o}"`,
          ""
        );
        return `${fe(
          _,
          A
        )}${o}`;
      }
    }
    return Qe(e) ? ge(n) ? fe(
      e,
      oe(n).toDate(),
      { ignoreTimezone: !0 }
    ) : "NaT" : qe(e) ? fe(e, n) : pe(Number(n)) ? `${t}` : fe(e, Number(n));
  } catch (n) {
    return console.error("Error formatting value with expression", n), `${t}`;
  }
}
function mt(e, t) {
  if (t?.type === void 0) return le(e);
  if (e === "") return "";
  if (e instanceof Date && ![D.DATE, D.TIMESTAMP].includes(
    t.type
  ))
    return me(e, void 0, !1);
  if (pe(e) || e === null)
    return le(e);
  switch (t.type) {
    case D.ID:
      return `${e}`;
    case D.DEFAULT:
      return le(e);
    case D.PERCENT:
      return `${ce(Number(e) * 100, t)}%`;
    case D.CURRENCY:
      const { compactValue: r, compactSuffix: o } = _e(e, t);
      return `${ce(
        r,
        t
      ).replace(/\u00A0/, " ")}${o}`;
    case D.DATE:
      return Ye(e, t?.timeInterval, !1);
    case D.TIMESTAMP:
      return me(e, t?.timeInterval, !1);
    case D.NUMBER:
      const A = t.prefix || "", _ = t.suffix || "", {
        compactValue: f,
        compactSuffix: b
      } = _e(e, t), N = ce(f, t);
      return `${A}${N}${b}${_}`;
    case D.BYTES_SI:
    case D.BYTES_IEC: {
      const {
        compactValue: h,
        compactSuffix: y
      } = _e(e, t);
      return `${ce(
        h,
        t
      )}${y}`;
    }
    case D.CUSTOM:
      return Ke(t.custom || "", e);
    default:
      return Le(
        t.type,
        `Table calculation format type ${t.type} is not valid`
      );
  }
}
function pt(e) {
  if (!e.includes("${"))
    return xe(e);
  const n = e.replace(/\$\{[^}]+\}/g, "");
  return xe(n);
}
function It(e) {
  return !e || !("format" in e) || !e.format ? !1 : (Se(e) || Pe(e)) && typeof e.format == "string" && !tt(e.format) && pt(e.format);
}
function Ie(e, t, n, r) {
  if (t === null) return "∅";
  if (t === void 0) return "-";
  if (e) {
    if (It(e)) {
      if (e.format.includes(
        `\${${Re.PREFIX_SHORT}`
      ) || e.format.includes(`\${${Re.PREFIX}`))
        return le(t);
      try {
        return Ke(e.format, t);
      } catch {
      }
    }
    const o = ft(e);
    if (Fe(e) || "type" in e)
      switch ($e(e)) {
        case ee.STRING:
        case k.STRING:
        case M.STRING:
          return `${t}`;
        case k.BOOLEAN:
        case M.BOOLEAN:
        case ee.BOOLEAN:
          return at(t);
        case k.DATE:
        case M.DATE:
        case ee.DATE:
          return ge(t) ? Ye(
            t,
            H(e) ? e.timeInterval : void 0,
            n
          ) : "NaT";
        case k.TIMESTAMP:
        case M.TIMESTAMP:
        case ee.TIMESTAMP:
          return ge(t) ? me(
            t,
            H(e) ? e.timeInterval : void 0,
            n
          ) : "NaT";
        case M.MAX:
        case M.MIN:
          if (t instanceof Date && o === void 0)
            return me(
              t,
              H(e) ? e.timeInterval : void 0,
              n
            );
          break;
        case k.NUMBER:
          if (H(e) && e.timeInterval && e.timeInterval === P.YEAR_NUM)
            return `${t}`;
          break;
      }
    return mt(t, o);
  }
  return le(t);
}
const be = (e) => typeof e == "object" && e !== null, B = (e, t, n = null) => Array.from(
  { length: e },
  () => Array.from({ length: t }, () => n)
), ae = (e) => {
  if (e === null) return 0;
  const t = Number(e.raw);
  return Number.isNaN(t) ? 0 : t;
}, ue = (e, t, n) => {
  if (t.length === 0)
    return !1;
  const [r, ...o] = t;
  if (r === void 0)
    throw new te(
      `setIndexByKey: Cannot get key from keys ${t.length}`
    );
  if (o.length === 0)
    return e[r] === void 0 ? (e[r] = n, !0) : !1;
  e[r] === void 0 && (e[r] = {});
  const l = e[r];
  if (!be(l))
    throw new Error("Cannot set key on non-object");
  return ue(l, o, n);
}, we = (e, t) => {
  if (t.length === 0)
    throw new Error("Cannot get key from empty keys array");
  const [n, ...r] = t;
  if (n === void 0)
    throw new Je(
      `getIndexByKey: Cannot get key from keys ${t.length}`
    );
  if (r.length === 0) {
    const o = e[n];
    if (typeof o != "number")
      throw new Error("Expected a number");
    return o;
  } else {
    const o = e[n];
    if (be(o))
      return we(o, r);
    throw new Error("Expected a RecursiveRecord object");
  }
}, Ne = (e, t) => Object.entries(e).reduce((r, [o, l]) => o === t && Ee(l) ? [...r, l] : be(l) ? [...r, ...Ne(l, t)] : r, []), ke = (e) => Object.values(e).reduce((t, n) => Ee(n) ? [...t, n] : [...t, ...ke(n)], []), He = (e, t) => {
  const [n, ...r] = t;
  if (n === void 0)
    throw new te("Cannot set key on undefined");
  if (r.length === 0) {
    const l = Te(e, n);
    return Ee(l) ? [l] : ke(l);
  }
  const o = e[n];
  if (be(o))
    return He(o, r);
  throw new Error("Expected a RecursiveRecord object");
}, Et = (e, t, n) => {
  const r = He(t, n).sort((_, f) => _ - f);
  if (r.length === 0)
    throw new Error("Cannot get span from empty indices array");
  const o = r.indexOf(
    e
  ), l = r[o - 1];
  if (o < 0)
    throw new Error(
      "Cannot get span for index that does not exist in indices array"
    );
  return !Ee(l) || l !== e - 1 ? r.slice(o).reduce((_, f, b) => f === e + b ? _ + 1 : _, 0) : 0;
}, Ge = (e, t, n) => {
  const r = e.indexValues.length ? e.indexValues : [[]], o = Oe(e.headerValues);
  if (e.headerValues[0] === void 0)
    throw new te(
      "combinedRetrofit: Cannot get header values"
    );
  const l = Array(
    se(e.headerValues, 0).length
  );
  e.headerValues.forEach((N) => {
    N.forEach((h, y) => {
      l[y] = `${(l[y] ?? "") + h.fieldId}__`;
    });
  });
  const A = (N, h) => {
    const y = Oe(e.indexValues[h]);
    if (!y || !y.fieldId) throw new Error("Invalid pivot data");
    const T = t(y.fieldId);
    if (!Ce(T))
      return null;
    const U = Ie(T, N, !1);
    return {
      raw: N,
      formatted: U
    };
  }, _ = (N, h) => {
    if (!N || !N.fieldId) throw new Error("Invalid pivot data");
    const y = t(N.fieldId), T = Ie(y, h, !1);
    return {
      raw: h,
      formatted: T
    };
  };
  let f = [];
  const b = r.map((N, h) => {
    const y = N.map((d, E) => {
      if (d.type === "label") {
        const R = n(d.fieldId);
        return {
          ...d,
          fieldId: `label-${E}`,
          value: {
            raw: R,
            formatted: R
          },
          columnType: "label"
        };
      }
      return {
        ...d,
        columnType: "indexValue"
      };
    }), T = se(e.dataValues, h).map(
      (d, E) => {
        const x = (o ? o[E] : void 0)?.fieldId, v = se(l, E) + E;
        return {
          baseId: x,
          fieldId: v,
          value: d || {}
        };
      }
    ), U = e.rowTotals?.[h]?.map(
      (d, E) => {
        const R = `row-total-${E}`, x = R, v = Oe(e.rowTotalFields)?.[E], g = e.pivotConfig.metricsAsRows ? A(d, h) : _(v, d), C = e.pivotConfig.metricsAsRows ? void 0 : v?.fieldId;
        return {
          baseId: R,
          fieldId: x,
          underlyingId: C,
          value: g,
          columnType: "rowTotal"
        };
      }
    ), V = [
      ...y,
      ...T,
      ...U || []
    ];
    h === 0 && (f = V.map((d) => ({
      fieldId: d.fieldId,
      baseId: "baseId" in d ? d.baseId : void 0,
      underlyingId: "underlyingId" in d ? d.underlyingId : void 0,
      columnType: "columnType" in d ? d.columnType : void 0
    })));
    const I = {};
    return V.forEach((d) => {
      const E = d.value;
      E && "formatted" in E && E.formatted !== void 0 && (I[d.fieldId] = {
        value: {
          raw: E.raw,
          formatted: E.formatted
        }
      });
    }), I;
  });
  return e.retrofitData = { allCombinedData: b, pivotColumnInfo: f }, e;
}, We = ({
  metricsAsRows: e,
  pivotDimensionNames: t
}) => {
  const n = t.map((o) => ({
    type: Y.DIMENSION,
    fieldId: o
  })), r = e ? [] : [{ type: Y.METRIC }];
  return [...n, ...r];
}, je = ({
  summableMetricFieldIds: e,
  rowIndices: t,
  totalColumns: n,
  dataColumns: r,
  dataValues: o,
  hasIndex: l,
  pivotConfig: A,
  indexValues: _
}) => {
  let f, b;
  const N = r;
  if (A.columnTotals && l)
    if (A.metricsAsRows) {
      const h = e.length, y = n;
      f = B(h, y), b = B(h, N), e.forEach((T, U) => {
        f[U][y - 1] = {
          fieldId: T
        };
      }), b = b.map(
        (T, U) => T.map((V, I) => {
          const d = f[U][y - 1]?.fieldId, E = d ? Ne(t, d) : [];
          return o.filter(
            (R, x) => E.includes(x)
          ).reduce(
            (R, x) => R + ae(x[I]),
            0
          );
        })
      );
    } else {
      const h = _[0].length, y = 1;
      f = B(y, h), b = B(y, N), f[y - 1][h - 1] = {
        fieldId: void 0
      }, b = b.map(
        (T, U) => T.map(
          (V, I) => o.map((d) => d[I]).reduce(
            (d, E) => d + ae(E),
            0
          )
        )
      );
    }
  return { columnTotalFields: f, columnTotals: b };
}, Xe = ({
  hasHeader: e,
  hasIndex: t,
  headerValueTypes: n,
  indexValueTypes: r
}) => {
  const o = B(
    e ? n.length : 1,
    t ? r.length : 1
  );
  return n.forEach((l, A) => {
    l.type === Y.DIMENSION && (o[A][t ? r.length - 1 : 0] = {
      fieldId: l.fieldId,
      direction: "header"
    });
  }), r.forEach((l, A) => {
    l.type === Y.DIMENSION && (o[e ? n.length - 1 : 0][A] = {
      fieldId: l.fieldId,
      direction: "index"
    });
  }), o;
}, bt = ({
  pivotConfig: e,
  metricQuery: t,
  rows: n,
  options: r,
  getField: o,
  getFieldLabel: l,
  groupedSubtotals: A
}) => {
  if (n.length === 0)
    throw new Error("Cannot pivot results with no rows");
  const _ = e.hiddenMetricFieldIds || [], f = t.metrics.filter((a) => {
    const c = o(a);
    return !c || H(c) || _.includes(a) ? !1 : Ce(c);
  }), b = (e.columnOrder || []).filter(
    (a) => !_.includes(a)
  ), N = [...t.dimensions], h = e.pivotDimensions.filter(
    (a) => N.includes(a)
  ), y = We({
    metricsAsRows: e.metricsAsRows,
    pivotDimensionNames: h
  }), T = N.filter((a) => !e.pivotDimensions.includes(a)).slice().sort((a, c) => b.indexOf(a) - b.indexOf(c)), U = T.map((a) => ({
    type: Y.DIMENSION,
    fieldId: a
  })), V = e.metricsAsRows ? [{ type: Y.METRIC }] : [], I = [
    ...U,
    ...V
  ], d = [
    ...t.metrics,
    ...t.tableCalculations.map((a) => a.name)
  ].filter((a) => !_.includes(a)).sort((a, c) => b.indexOf(a) - b.indexOf(c)).map((a) => ({ fieldId: a }));
  if (d.length === 0)
    throw new Error("Cannot pivot results with no metrics");
  const E = n.length, R = [], x = [], v = {}, g = {};
  let C = 0, G = 0;
  for (let a = 0; a < E; a += 1) {
    const c = n[a];
    for (let p = 0; p < d.length; p += 1) {
      const w = T.map((O) => ({
        type: "value",
        fieldId: O,
        value: Te(c, O).value,
        colSpan: 1
      })).concat(
        e.metricsAsRows ? [
          {
            type: "label",
            fieldId: se(d, p).fieldId
          }
        ] : []
      ), S = h.map((O) => ({
        type: "value",
        fieldId: O,
        value: Te(c, O).value,
        colSpan: 1
      })).concat(
        e.metricsAsRows ? [] : [
          {
            type: "label",
            fieldId: se(d, p).fieldId
          }
        ]
      );
      if (ue(
        v,
        w.map(
          (O) => O.type === "value" ? String(O.value?.raw) : O.fieldId
        ),
        C
      ) && (C += 1, R.push(w)), ue(
        g,
        S.map(
          (O) => O.type === "value" ? String(O.value.raw) : O.fieldId
        ),
        G
      )) {
        if (G += 1, G > r.maxColumns)
          throw new Error(
            `Cannot pivot results with more than ${r.maxColumns} columns. Try adding a filter to limit your results.`
          );
        x.push(S);
      }
    }
  }
  const ie = x[0]?.map(
    (a, c) => x.map(
      (p, w) => {
        const S = se(p, c);
        if (S.type === "label")
          return S;
        const O = p.slice(0, c + 1).reduce(
          (q, F) => F.type === "value" ? [...q, String(F.value.raw)] : q,
          []
        );
        return {
          ...S,
          colSpan: Et(
            w,
            g,
            O
          )
        };
      }
    )
  ) ?? [], X = I.length > 0, ne = y.length > 0, W = X ? C : 1, re = ne ? G : 1, K = B(
    W,
    re
  );
  if (W === 0 || re === 0)
    throw new Error("Cannot pivot results with no data");
  for (let a = 0; a < E; a += 1) {
    const c = n[a];
    for (let p = 0; p < d.length; p += 1) {
      const w = d[p], { value: S } = c?.[w.fieldId] ?? {}, O = [
        ...T.map((J) => c[J].value.raw),
        ...e.metricsAsRows ? [w.fieldId] : []
      ], Q = [
        ...h.map((J) => c[J].value.raw),
        ...e.metricsAsRows ? [] : [w.fieldId]
      ], q = O.map(String), F = Q.map(String), z = X ? we(v, q) : 0, he = ne ? we(g, F) : 0;
      K[z][he] = S;
    }
  }
  let j, L;
  if (e.rowTotals && ne)
    if (e.metricsAsRows) {
      const c = ie.length;
      j = B(c, 1), L = B(W, 1), j[c - 1][0] = {
        fieldId: void 0
      }, L = L.map(
        (p, w) => p.map(
          () => K[w].reduce(
            (S, O) => S + ae(O),
            0
          )
        )
      );
    } else {
      const a = f.length, c = ie.length;
      j = B(c, a), L = B(W, a), f.forEach((p, w) => {
        j[c - 1][w] = {
          fieldId: p
        };
      }), L = L.map(
        (p, w) => p.map((S, O) => {
          const Q = j[c - 1][O]?.fieldId, q = Q ? Ne(
            g,
            Q
          ) : [];
          return K[w].filter(
            (F, z) => q.includes(z)
          ).reduce(
            (F, z) => F + ae(z),
            0
          );
        })
      );
    }
  const { columnTotalFields: De, columnTotals: ye } = je({
    summableMetricFieldIds: f,
    totalColumns: I.length,
    dataColumns: re,
    dataValues: K,
    rowIndices: v,
    pivotConfig: e,
    indexValues: R,
    hasIndex: X
  }), s = Xe({
    hasIndex: X,
    hasHeader: ne,
    headerValueTypes: y,
    indexValueTypes: I
  }), i = (I.length === 0 ? s[0].length : 0) + I.length + K[0].length + (e.rowTotals && L ? L[0].length : 0), u = K.length || 0;
  return Ge({
    titleFields: s,
    headerValueTypes: y,
    headerValues: ie,
    indexValueTypes: I,
    indexValues: R,
    dataColumnCount: re,
    dataValues: K,
    rowTotalFields: j,
    columnTotalFields: De,
    rowTotals: L,
    columnTotals: ye,
    cellsCount: i,
    rowsCount: u,
    pivotConfig: e,
    retrofitData: {
      allCombinedData: [],
      pivotColumnInfo: []
    },
    groupedSubtotals: A
  }, o, l);
}, Nt = ({
  rows: e,
  pivotDetails: t,
  pivotConfig: n,
  getField: r,
  getFieldLabel: o,
  groupedSubtotals: l
}) => {
  if (e.length === 0)
    throw new Error("Cannot convert SQL pivoted results with no rows");
  const A = n.hiddenMetricFieldIds || [], _ = n.columnOrder || [];
  let f;
  t.indexColumn ? Array.isArray(t.indexColumn) ? f = t.indexColumn.map((s) => s.reference).sort(
    (s, i) => _.indexOf(s) - _.indexOf(i)
  ) : f = [t.indexColumn.reference] : f = [];
  const b = t.valuesColumns.filter(
    ({ referenceField: s }) => !A.includes(s)
  ), N = b.map((s) => s.referenceField).filter((s, i, u) => u.indexOf(s) === i).sort((s, i) => _.indexOf(s) - _.indexOf(i)), h = We({
    metricsAsRows: n.metricsAsRows,
    pivotDimensionNames: (t.groupByColumns ?? []).map(
      ({ reference: s }) => s
    )
  }), y = n.metricsAsRows ? [
    ...f.map((s) => ({
      type: Y.DIMENSION,
      fieldId: s
    })),
    { type: Y.METRIC }
  ] : f.map((s) => ({
    type: Y.DIMENSION,
    fieldId: s
  })), T = [];
  t.groupByColumns?.forEach(({ reference: s }, i) => {
    T.push([]);
    let u = b;
    n.metricsAsRows && (u = Array.from(
      new Map(
        u.map((m) => [
          m.pivotValues.map(
            ({ referenceField: a, value: c }) => `${a}:${c}`
          ).join("|"),
          m
        ])
      ).values()
    )), u.forEach(({ pivotValues: m, pivotColumnName: a }) => {
      const c = m.find(
        ({ referenceField: p }) => p === s
      );
      if (c) {
        const p = r(c.referenceField), w = c.formatted || (p ? Ie(
          p,
          c.value,
          !0
        ) : String(c.value)), S = u.filter(
          (Q) => (t.groupByColumns || []).map((F) => F.reference).slice(0, i + 1).every((F) => {
            const z = m.find(
              ({ referenceField: J }) => J === F
            ), he = Q.pivotValues.find(
              ({ referenceField: J }) => J === F
            );
            return z?.value === he?.value;
          })
        ), O = S[0].pivotColumnName === a;
        T[i].push({
          type: "value",
          fieldId: s,
          value: {
            raw: c.value,
            formatted: w
          },
          colSpan: O ? S.length : 0
        });
      }
    });
  }), !n.metricsAsRows && N.length > 0 && T.push(
    b.sort((s, i) => {
      const u = Number(s.columnIndex) - Number(i.columnIndex), m = _.indexOf(s.referenceField) - _.indexOf(i.referenceField);
      return u || m;
    }).map(({ referenceField: s }) => ({
      type: "label",
      fieldId: s
    }))
  );
  const U = T.filter((s) => s.length > 0);
  let V;
  n.metricsAsRows ? V = e.reduce((s, i) => (N.forEach((u) => {
    s.push([
      ...f.map((m) => ({
        type: "value",
        fieldId: m,
        value: i[m].value,
        colSpan: 1
      })),
      {
        type: "label",
        fieldId: u
      }
    ]);
  }), s), []) : V = e.map(
    (s) => f.map((i) => ({
      type: "value",
      fieldId: i,
      value: s[i].value,
      colSpan: 1
    }))
  );
  let I;
  const d = {};
  let E = 0;
  const R = n.metricsAsRows ? Array.from(
    new Map(
      b.map((s) => [
        s.pivotValues.map(
          ({ referenceField: i, value: u }) => `${i}:${u}`
        ).join("|"),
        s
      ])
    ).values()
  ) : b;
  n.metricsAsRows ? I = e.reduce((s, i) => (N.forEach((u) => {
    const m = [
      ...f.map(
        (c) => String(i[c].value.raw)
      ),
      u
    ], a = R.map((c) => {
      const p = b.find(
        (w) => w.referenceField === u && w.pivotValues.every(
          (S) => c.pivotValues.some(
            (O) => O.referenceField === S.referenceField && O.value === S.value
          )
        )
      );
      return p && i[p.pivotColumnName] ? i[p.pivotColumnName].value : null;
    });
    s.push(a), ue(d, m, E), E += 1;
  }), s), []) : (I = e.map((s, i) => {
    const u = f.map(
      (m) => String(s[m].value.raw)
    );
    return ue(d, u, i), b.map(
      (m) => s[m.pivotColumnName] ? s[m.pivotColumnName].value : null
    );
  }), E = e.length);
  const x = {
    pivotDimensions: t.groupByColumns?.map((s) => s.reference) || [],
    metricsAsRows: n.metricsAsRows || !1,
    columnOrder: n.columnOrder,
    hiddenMetricFieldIds: n.hiddenMetricFieldIds || [],
    columnTotals: n.columnTotals,
    rowTotals: n.rowTotals
  };
  let v, g;
  const C = h.length > 0, G = y.length > 0, ie = G ? I.length : 1, X = C ? R.length : 1, ne = R.reduce(
    (s, i, u) => {
      const m = (t.groupByColumns || []).map(
        (c) => i.pivotValues.find(
          ({ referenceField: p }) => p === c.reference
        )?.value
      );
      let a = s;
      for (let c = 0; c < m.length; c += 1) {
        const p = String(m[c]);
        Object.prototype.hasOwnProperty.call(a, p) || Object.defineProperty(a, p, {
          value: {},
          writable: !0,
          enumerable: !0,
          configurable: !0
        }), a = a[p];
      }
      return n.metricsAsRows ? Object.defineProperty(a, "value", {
        value: u,
        writable: !0,
        enumerable: !0,
        configurable: !0
      }) : Object.defineProperty(a, i.referenceField, {
        value: u,
        writable: !0,
        enumerable: !0,
        configurable: !0
      }), s;
    },
    {}
  ), W = N.filter((s) => {
    const i = r(s);
    return !i || H(i) || A.includes(s) ? !1 : Ce(i);
  });
  if (x.rowTotals && C)
    if (x.metricsAsRows) {
      const i = T.length;
      v = B(i, 1), g = B(ie, 1), v[i - 1][0] = {
        fieldId: void 0
      }, g = g.map(
        (u, m) => u.map(
          () => I[m].reduce(
            (a, c) => a + ae(c),
            0
          )
        )
      );
    } else {
      const s = W.length, i = T.length;
      v = B(i, s), g = B(e.length, s), W.forEach((u, m) => {
        v[i - 1][m] = {
          fieldId: u
        };
      }), g = g.map(
        (u, m) => u.map((a, c) => {
          const p = v[i - 1][c]?.fieldId, w = p ? Ne(
            ne,
            p
          ) : [];
          return I[m].filter(
            (S, O) => w.includes(O)
          ).reduce(
            (S, O) => S + ae(O),
            0
          );
        })
      );
    }
  const { columnTotalFields: re, columnTotals: K } = je({
    summableMetricFieldIds: W,
    totalColumns: y.length,
    dataColumns: X,
    dataValues: I,
    rowIndices: d,
    pivotConfig: n,
    indexValues: V,
    hasIndex: G
  }), j = e.map((s) => {
    const i = {};
    if (f.forEach((u) => {
      i[u] = s[u];
    }), n.metricsAsRows) {
      const u = f.length, m = o(N[0]) || N[0];
      i[`label-${u}`] = {
        value: {
          raw: m,
          formatted: m
        }
      };
    }
    return b.forEach((u, m) => {
      const a = (t.groupByColumns || []).map(
        (p) => p.reference
      ), c = n.metricsAsRows ? `${a.join("__")}__${m}` : `${a.join("__")}__${u.referenceField}__${m}`;
      s[u.pivotColumnName] && (i[c] = s[u.pivotColumnName]);
    }), i;
  }).map((s, i) => {
    if (x.rowTotals && g) {
      const u = g[i]?.[0];
      if (u !== void 0) {
        const m = r(N[0]), a = m ? Ie(
          m,
          u,
          !1
        ) : String(u);
        return {
          ...s,
          "row-total-0": {
            value: {
              raw: u,
              formatted: a
            }
          }
        };
      }
    }
    return s;
  }), L = [
    ...f.map((s) => ({
      fieldId: s,
      baseId: void 0,
      underlyingId: void 0,
      columnType: "indexValue"
    })),
    ...n.metricsAsRows ? [
      {
        fieldId: `label-${f.length}`,
        baseId: void 0,
        underlyingId: void 0,
        columnType: "label"
      }
    ] : [],
    ...b.map((s, i) => {
      const u = (t.groupByColumns || []).map(
        (a) => a.reference
      );
      return {
        fieldId: n.metricsAsRows ? `${u.join("__")}__${i}` : `${u.join("__")}__${s.referenceField}__${i}`,
        baseId: n.metricsAsRows ? u[0] : s.referenceField,
        underlyingId: void 0,
        columnType: void 0
      };
    }),
    ...x.rowTotals ? [
      {
        fieldId: "row-total-0",
        baseId: "row-total-0",
        underlyingId: void 0,
        columnType: "rowTotal"
      }
    ] : []
  ], ye = {
    titleFields: Xe({
      hasIndex: G,
      hasHeader: C,
      headerValueTypes: h,
      indexValueTypes: y
    }),
    headerValueTypes: h,
    headerValues: U,
    indexValueTypes: y,
    indexValues: V,
    dataColumnCount: X,
    dataValues: I,
    rowTotalFields: v,
    columnTotalFields: re,
    rowTotals: g,
    columnTotals: K,
    cellsCount: n.metricsAsRows ? f.length + 1 + // label column
    R.length + (g ? g[0].length : 0) : f.length + R.length + (g ? g[0].length : 0),
    rowsCount: n.metricsAsRows ? e.length * N.length : e.length,
    pivotConfig: x,
    retrofitData: {
      allCombinedData: j,
      pivotColumnInfo: L
    },
    groupedSubtotals: l
  };
  return Ge(ye, r, o);
}, ht = ({
  pivotConfig: e,
  rows: t,
  itemMap: n,
  metricQuery: r,
  customLabels: o,
  onlyRaw: l,
  maxColumnLimit: A,
  undefinedCharacter: _ = "",
  pivotDetails: f
}) => {
  const b = (I) => {
    const d = o?.[I];
    if (d !== void 0) return d;
    const E = n[I];
    return E && Se(E) && E?.label || I;
  }, N = f ? Nt({
    getField: (I) => n && n[I],
    getFieldLabel: b,
    rows: t,
    pivotDetails: f,
    pivotConfig: e,
    groupedSubtotals: void 0
    // TODO: is this something that we have?
  }) : bt({
    pivotConfig: e,
    metricQuery: r,
    rows: t,
    options: {
      maxColumns: A
    },
    getField: (I) => n && n[I],
    // itemsMap && itemsMap[fieldId],
    getFieldLabel: b
  }), h = l ? "raw" : "formatted", y = N.headerValues.reduce(
    (I, d, E) => {
      const R = d.map(
        (C) => "value" in C ? C.value[h] : b(C.fieldId)
      ), v = N.titleFields[E].map(
        (C) => C ? b(C.fieldId) : _
      ), g = N.rowTotalFields?.[E]?.map(
        (C) => C?.fieldId ? `Total ${b(C.fieldId)}` : "Total"
      ) || [];
      return I[E] = [...v, ...R, ...g], I;
    },
    [[]]
  ), T = Object.values(
    N.retrofitData.pivotColumnInfo
  ).map((I) => I.fieldId), U = N.indexValues.length > 0, V = N.retrofitData.allCombinedData.map((I) => {
    const d = U ? [] : [""], E = T.map(
      (R) => I[R]?.value?.[h] || _
    );
    return [...d, ...E];
  });
  return [...y, ...V];
};
export {
  Nt as convertSqlPivotedRowsToPivotData,
  bt as pivotQueryResults,
  ht as pivotResultsAsCsv
};
//# sourceMappingURL=pivotQueryResults-Cgf1ZdhE.mjs.map
