teodor-new-chat-ui 4.0.19 → 4.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -2,7 +2,7 @@ var Np = Object.defineProperty;
2
2
  var Ap = (e, t, n) => t in e ? Np(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
3
  var Ba = (e, t, n) => Ap(e, typeof t != "symbol" ? t + "" : t, n);
4
4
  import * as p from "react";
5
- import H, { createContext as ir, useContext as ar, useEffect as tt, useReducer as Cc, useState as fe, useRef as Xe, useCallback as Pe, useMemo as vt, createElement as go, useLayoutEffect as _p } from "react";
5
+ import H, { createContext as ir, useContext as ar, useReducer as Cc, useState as fe, useRef as Xe, useEffect as nt, useCallback as Pe, useMemo as vt, createElement as go, useLayoutEffect as _p } from "react";
6
6
  import { Square as jp, Send as Pp, X as Jn, ExternalLink as Op, Download as Mp, Image as Dp, FileText as Ha, Loader as Tc, Bot as Ua, Wrench as Lp, User as $p, ChevronUp as Cr, ChevronDown as Xn, Paperclip as ui, Copy as Wa, Edit as Va, RotateCcw as di, ChevronRight as Fp, Check as Wi, Circle as zp, Loader2 as fi, Edit3 as Rc, Plus as Bp, FileSpreadsheet as Hp, MessageSquarePlus as Up, MessageSquare as Wp, Calendar as Vp, Trash2 as Kp, Settings as qp, Server as Gp, EyeOff as Yp, Eye as Xp, Layout as Jp, MessageCircle as Zp, Save as Qp } from "lucide-react";
7
7
  import { Slot as em, createSlot as nr } from "@radix-ui/react-slot";
8
8
  import { cva as Xo } from "class-variance-authority";
@@ -332,7 +332,7 @@ function om() {
332
332
  } else
333
333
  je.setExtraStackFrame(null);
334
334
  }
335
- function nt(T, U, te, Se, He) {
335
+ function tt(T, U, te, Se, He) {
336
336
  {
337
337
  var Ke = Function.call.bind(X);
338
338
  for (var $e in T)
@@ -558,7 +558,7 @@ Check the top-level render call using <` + te + ">.");
558
558
  return;
559
559
  if (te) {
560
560
  var Se = $(U);
561
- nt(te, T.props, "prop", Se, T);
561
+ tt(te, T.props, "prop", Se, T);
562
562
  } else if (U.PropTypes !== void 0 && !xr) {
563
563
  xr = !0;
564
564
  var He = $(U);
@@ -2530,12 +2530,14 @@ class Lg {
2530
2530
  const Pn = new Lg(), Jc = ir(null);
2531
2531
  function $g({ children: e, apiConfig: t }) {
2532
2532
  const n = Pn;
2533
- tt(() => {
2534
- t && n.updateConfig({
2535
- baseUrl: t.baseUrl,
2533
+ if (t) {
2534
+ const o = n.baseUrl, s = n.getAuthToken();
2535
+ t.baseUrl && t.baseUrl !== o && n.updateConfig({
2536
+ baseUrl: t.baseUrl
2537
+ }), t.apiKey !== void 0 && t.apiKey !== s && n.updateConfig({
2536
2538
  authToken: t.apiKey
2537
2539
  });
2538
- }, [n, t]);
2540
+ }
2539
2541
  const r = {
2540
2542
  token: n.getAuthToken(),
2541
2543
  setToken: (o) => n.setAuthToken(o),
@@ -2672,7 +2674,7 @@ function qg({
2672
2674
  const { api: i } = Gi(), [a, c] = fe([]), [u, d] = fe(t), [f, h] = fe(!1), [m, w] = fe(!1), [v, g] = fe(void 0), [x, b] = fe(void 0), y = Xe(!1), R = Xe([]), S = Xe(null), C = Xe(null);
2673
2675
  Xe(!1);
2674
2676
  const E = Xe(u);
2675
- tt(() => {
2677
+ nt(() => {
2676
2678
  E.current = u;
2677
2679
  }, [u]);
2678
2680
  const k = ar(tu), N = Pe(
@@ -2779,14 +2781,14 @@ function qg({
2779
2781
  if (!u) throw new Error("No active thread");
2780
2782
  await P(u, void 0, void 0, !0);
2781
2783
  }, [u, P]);
2782
- tt(() => {
2784
+ nt(() => {
2783
2785
  if (o == null || o(u), u)
2784
2786
  try {
2785
2787
  localStorage.setItem("lastThreadId", u);
2786
2788
  } catch (M) {
2787
2789
  console.warn("[ThreadProvider] Failed to persist thread ID:", M);
2788
2790
  }
2789
- }, [u, o]), tt(() => {
2791
+ }, [u, o]), nt(() => {
2790
2792
  let M = !0;
2791
2793
  return (async () => {
2792
2794
  try {
@@ -2920,7 +2922,7 @@ function Zg(e = []) {
2920
2922
  }, [i]), c = Pe((d) => {
2921
2923
  r.current.push(d), a();
2922
2924
  }, [a]);
2923
- tt(() => () => {
2925
+ nt(() => () => {
2924
2926
  o.current !== null && typeof window < "u" && window.cancelAnimationFrame(o.current), s.current !== null && clearTimeout(s.current), r.current = [];
2925
2927
  }, []);
2926
2928
  const u = vt(() => ({
@@ -3215,8 +3217,8 @@ function cx(e = {}) {
3215
3217
  const X = window.__AUTH_TOKEN__, xe = ((P = window.localStorage) == null ? void 0 : P.getItem("authToken")) || null;
3216
3218
  let je = null;
3217
3219
  try {
3218
- const nt = (W = window.localStorage) == null ? void 0 : W.getItem("chat-settings");
3219
- nt && (je = ((z = JSON.parse(nt)) == null ? void 0 : z.apiKey) || null);
3220
+ const tt = (W = window.localStorage) == null ? void 0 : W.getItem("chat-settings");
3221
+ tt && (je = ((z = JSON.parse(tt)) == null ? void 0 : z.apiKey) || null);
3220
3222
  } catch {
3221
3223
  }
3222
3224
  const Ie = X || xe || je || null;
@@ -3273,8 +3275,8 @@ function cx(e = {}) {
3273
3275
  try {
3274
3276
  const V = Q.headers.get("X-Thread-Id") || Q.headers.get("x-thread-id"), X = Q.headers.get("X-Thread-Created") || Q.headers.get("x-thread-created"), xe = V ?? null, je = String(X ?? "").toLowerCase() === "true";
3275
3277
  for ((q = _ == null ? void 0 : _.onOpen) == null || q.call(_, { threadId: xe, created: je }); ; ) {
3276
- const { value: Ie, done: nt } = await ce.read();
3277
- if (nt) break;
3278
+ const { value: Ie, done: tt } = await ce.read();
3279
+ if (tt) break;
3278
3280
  Ee += we.decode(Ie, { stream: !0 }), Ee.length > Ye && (Ee = "", console.warn("Stream buffer reset: exceeded 1MB"));
3279
3281
  let it;
3280
3282
  for (; (it = Ee.indexOf(`
@@ -3337,7 +3339,7 @@ function cx(e = {}) {
3337
3339
  },
3338
3340
  [t, n, r, e.autoAppendAssistant]
3339
3341
  );
3340
- return tt(() => () => {
3342
+ return nt(() => () => {
3341
3343
  var N;
3342
3344
  y.current = !1, (N = b.current) == null || N.abort();
3343
3345
  }, []), {
@@ -3377,7 +3379,7 @@ function fx({
3377
3379
  const V = (s ?? "").replace(/\/+$/, "");
3378
3380
  return V ? V.endsWith("/chat") ? V : `${V}/chat` : "/api/chat";
3379
3381
  }, [s]), { currentThreadId: a, setCurrentThreadId: c, isLoadingThread: u } = rs(), d = Ug(), { state: f, dispatch: h, seed: m, prepend: w, pushUser: v, onEvent: g, reset: x } = Zg(), [b, y] = fe(!1), [R, S] = fe(!1), [C, E] = fe(null), [k, N] = fe(void 0), [A, _] = fe(void 0), L = 20, $ = Xe(a);
3380
- tt(() => {
3382
+ nt(() => {
3381
3383
  $.current = a;
3382
3384
  }, [a]);
3383
3385
  const P = Xe(null), W = Xe(!1), z = Pe(() => {
@@ -3386,7 +3388,7 @@ function fx({
3386
3388
  baseUrl: i,
3387
3389
  token: null
3388
3390
  });
3389
- tt(() => {
3391
+ nt(() => {
3390
3392
  var xe;
3391
3393
  const V = o.getAuthToken();
3392
3394
  B(V);
@@ -3396,17 +3398,17 @@ function fx({
3396
3398
  return () => {
3397
3399
  X == null || X();
3398
3400
  };
3399
- }, [o, B]), tt(() => {
3401
+ }, [o, B]), nt(() => {
3400
3402
  d(q ? { type: "STREAM_START", assistantId: f.assemblingId ?? void 0 } : { type: "STREAM_END" });
3401
- }, [q, f.assemblingId, d]), tt(() => {
3403
+ }, [q, f.assemblingId, d]), nt(() => {
3402
3404
  d(D ? { type: "STREAM_ERROR", error: D } : { type: "CLEAR_ERROR" });
3403
- }, [D, d]), tt(() => {
3405
+ }, [D, d]), nt(() => {
3404
3406
  f.lastCheckpointId && d({
3405
3407
  type: "UPDATE_CHECKPOINT",
3406
3408
  checkpointId: f.lastCheckpointId,
3407
3409
  checkpointNs: f.lastCheckpointNs ?? void 0
3408
3410
  });
3409
- }, [f.lastCheckpointId, f.lastCheckpointNs, d]), tt(() => {
3411
+ }, [f.lastCheckpointId, f.lastCheckpointNs, d]), nt(() => {
3410
3412
  d({
3411
3413
  type: "UPDATE_ASSEMBLING_ID",
3412
3414
  assistantId: f.assemblingId
@@ -3495,7 +3497,7 @@ function fx({
3495
3497
  }),
3496
3498
  [Y, ee]
3497
3499
  );
3498
- tt(() => {
3500
+ nt(() => {
3499
3501
  if (r)
3500
3502
  return r(ue), () => {
3501
3503
  r({
@@ -3513,18 +3515,18 @@ function fx({
3513
3515
  const xe = (X == null ? void 0 : X.attachments) || [], { contentParts: je, filesInfo: Ie } = await Kg(
3514
3516
  o,
3515
3517
  xe
3516
- ), nt = [...je];
3517
- V && V.trim() && nt.push({ type: "text", text: V.trim() });
3518
+ ), tt = [...je];
3519
+ V && V.trim() && tt.push({ type: "text", text: V.trim() });
3518
3520
  const it = {
3519
3521
  id: ((Te = crypto.randomUUID) == null ? void 0 : Te.call(crypto)) || `user-${Date.now()}`,
3520
3522
  role: "user",
3521
- content: nt,
3523
+ content: tt,
3522
3524
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3523
3525
  checkpointId: (X == null ? void 0 : X.checkpointId) ?? f.lastCheckpointId ?? void 0,
3524
3526
  checkpointNs: (X == null ? void 0 : X.checkpointNs) ?? f.lastCheckpointNs ?? void 0
3525
3527
  };
3526
3528
  v(it);
3527
- const oe = { ...it, content: nt }, se = { ...(X == null ? void 0 : X.payloadExtras) ?? {} }, he = xe && xe.length > 0, pe = {
3529
+ const oe = { ...it, content: tt }, se = { ...(X == null ? void 0 : X.payloadExtras) ?? {} }, he = xe && xe.length > 0, pe = {
3528
3530
  ...a ? { threadId: a } : {},
3529
3531
  payload: {
3530
3532
  messages: [oe],
@@ -6583,7 +6585,7 @@ const _v = /* @__PURE__ */ Be(
6583
6585
  X,
6584
6586
  xe
6585
6587
  ]) => {
6586
- const { column: je, row: Ie } = ue, { height: nt, width: it } = le, { width: oe } = Fe;
6588
+ const { column: je, row: Ie } = ue, { height: tt, width: it } = le, { width: oe } = Fe;
6587
6589
  if (V === 0 && (O === 0 || oe === 0))
6588
6590
  return Il;
6589
6591
  if (it === 0) {
@@ -6592,9 +6594,9 @@ const _v = /* @__PURE__ */ Be(
6592
6594
  }
6593
6595
  const se = Du(oe, it, je);
6594
6596
  let he, pe;
6595
- X ? Y === 0 && ee === 0 && V > 0 ? (he = 0, pe = V - 1) : (he = se * Do((Y + Ie) / (nt + Ie)), pe = se * Nl((ee + Ie) / (nt + Ie)) - 1, pe = Xs(O - 1, kr(pe, se - 1)), he = Xs(pe, kr(0, he))) : (he = 0, pe = -1);
6596
- const Te = _l(he, pe, Ye), { bottom: Ne, top: We } = jl(Fe, ue, le, Te), Ve = Nl(O / se), ct = Ve * nt + (Ve - 1) * Ie - Ne;
6597
- return { bottom: Ne, itemHeight: nt, items: Te, itemWidth: it, offsetBottom: ct, offsetTop: We, top: We };
6597
+ X ? Y === 0 && ee === 0 && V > 0 ? (he = 0, pe = V - 1) : (he = se * Do((Y + Ie) / (tt + Ie)), pe = se * Nl((ee + Ie) / (tt + Ie)) - 1, pe = Xs(O - 1, kr(pe, se - 1)), he = Xs(pe, kr(0, he))) : (he = 0, pe = -1);
6598
+ const Te = _l(he, pe, Ye), { bottom: Ne, top: We } = jl(Fe, ue, le, Te), Ve = Nl(O / se), ct = Ve * tt + (Ve - 1) * Ie - Ne;
6599
+ return { bottom: Ne, itemHeight: tt, items: Te, itemWidth: it, offsetBottom: ct, offsetTop: We, top: We };
6598
6600
  }
6599
6601
  )
6600
6602
  ),
@@ -10172,7 +10174,7 @@ function Ub({ isOpen: e, onClose: t, fileId: n, fileName: r, mimeType: o }) {
10172
10174
  }
10173
10175
  }
10174
10176
  }, [n]);
10175
- tt(() => {
10177
+ nt(() => {
10176
10178
  e && n && h();
10177
10179
  }, [e, n, h]);
10178
10180
  const m = async () => {
@@ -10421,7 +10423,7 @@ function sc(e) {
10421
10423
  }
10422
10424
  function Xb({ className: e }) {
10423
10425
  const [t, n] = fe(0);
10424
- return tt(() => {
10426
+ return nt(() => {
10425
10427
  const r = setInterval(() => n((o) => (o + 1) % 4), 500);
10426
10428
  return () => clearInterval(r);
10427
10429
  }, []), /* @__PURE__ */ l.jsxs(
@@ -10705,7 +10707,7 @@ const Jb = H.memo(function({
10705
10707
  ]), Ie = H.useCallback(() => /* @__PURE__ */ l.jsxs("div", { className: "flex items-center gap-2 p-2 bg-muted/30 rounded", children: [
10706
10708
  /* @__PURE__ */ l.jsx(ui, { className: "h-4 w-4 text-muted-foreground" }),
10707
10709
  /* @__PURE__ */ l.jsx("span", { className: "text-sm text-muted-foreground", children: "File upload" })
10708
- ] }), []), nt = H.useCallback(() => {
10710
+ ] }), []), tt = H.useCallback(() => {
10709
10711
  if (!(J.trim().length > 0 || ce.length > 0 || we.length > 0 || Ee.length > 0) && !r)
10710
10712
  return Ie();
10711
10713
  if (t.model === "reflection") {
@@ -10884,7 +10886,7 @@ const Jb = H.memo(function({
10884
10886
  ]
10885
10887
  }
10886
10888
  ),
10887
- /* @__PURE__ */ l.jsx("div", { className: "relative", children: nt() }),
10889
+ /* @__PURE__ */ l.jsx("div", { className: "relative", children: tt() }),
10888
10890
  I && R === "expanded" && (Q.toolCallId || Q.name) && /* @__PURE__ */ l.jsxs("div", { className: Z("mt-2 pt-2 border-t border-current/10 text-xs opacity-60", q && "text-xs"), children: [
10889
10891
  Q.name && /* @__PURE__ */ l.jsxs("div", { children: [
10890
10892
  "Function: ",
@@ -13860,23 +13862,23 @@ function ci({
13860
13862
  streamingAssistantId: L,
13861
13863
  lastCheckpointId: $,
13862
13864
  lastCheckpointNs: P
13863
- } = Hg(), [W, z] = fe(null), [q, D] = fe(""), [I, M] = fe(null), [B, J] = fe([]), [Q, ce] = fe(0), [we, Ee] = fe(0), [K, O] = fe(!1), [Y, ee] = fe(null), [ue, le] = fe(null), [Fe, Ye] = fe(!1), [V, X] = fe(null), [xe, je] = fe([]), [Ie, nt] = fe(null), [it, oe] = fe(null), [se, he] = fe(!1), pe = Xe(null), Te = Xe(null), Ne = Xe(null), We = Pe(() => {
13865
+ } = Hg(), [W, z] = fe(null), [q, D] = fe(""), [I, M] = fe(null), [B, J] = fe([]), [Q, ce] = fe(0), [we, Ee] = fe(0), [K, O] = fe(!1), [Y, ee] = fe(null), [ue, le] = fe(null), [Fe, Ye] = fe(!1), [V, X] = fe(null), [xe, je] = fe([]), [Ie, tt] = fe(null), [it, oe] = fe(null), [se, he] = fe(!1), pe = Xe(null), Te = Xe(null), Ne = Xe(null), We = Pe(() => {
13864
13866
  pe.current && (pe.current.value = ""), Te.current && (Te.current.value = ""), ce((ie) => ie + 1), Ee((ie) => ie + 1);
13865
13867
  }, []), Ve = Xe(!1);
13866
- tt(() => {
13868
+ nt(() => {
13867
13869
  Ve.current && !A && (J([]), We()), Ve.current = A;
13868
13870
  }, [A, We]);
13869
13871
  const [ct, jt] = fe("desktop");
13870
- tt(() => {
13872
+ nt(() => {
13871
13873
  const ie = () => {
13872
13874
  const ve = window.innerWidth;
13873
13875
  jt(ve < 640 ? "phone" : ve < 1024 ? "tablet" : "desktop");
13874
13876
  };
13875
13877
  return ie(), window.addEventListener("resize", ie), () => window.removeEventListener("resize", ie);
13876
- }, []), tt(() => {
13878
+ }, []), nt(() => {
13877
13879
  let ie = !1;
13878
13880
  if (!v) {
13879
- je([]), nt(null), oe(null), Ne.current = null;
13881
+ je([]), tt(null), oe(null), Ne.current = null;
13880
13882
  return;
13881
13883
  }
13882
13884
  const ve = {
@@ -13896,14 +13898,14 @@ function ci({
13896
13898
  const ln = Rt.find((T) => T.checkpointId === wr);
13897
13899
  ro = (ln == null ? void 0 : ln.checkpointNs) ?? null;
13898
13900
  }
13899
- nt(wr), oe(ro), Ne.current = ve;
13901
+ tt(wr), oe(ro), Ne.current = ve;
13900
13902
  }).catch((Qe) => {
13901
13903
  console.error("ChatInterface - listCheckpoints error:", Qe), ie || (je([]), Ne.current = null);
13902
13904
  }), () => {
13903
13905
  ie = !0;
13904
13906
  };
13905
- }, [v, $, P, Ie, x]), tt(() => {
13906
- $ && (nt($), oe(P ?? null));
13907
+ }, [v, $, P, Ie, x]), nt(() => {
13908
+ $ && (tt($), oe(P ?? null));
13907
13909
  }, [$, P]);
13908
13910
  const Vn = Pe(async () => {
13909
13911
  if (!(!S || C))
@@ -13913,7 +13915,7 @@ function ci({
13913
13915
  console.warn("loadOlderMessages failed", ie);
13914
13916
  }
13915
13917
  }, [S, C, N]);
13916
- tt(() => {
13918
+ nt(() => {
13917
13919
  (async () => {
13918
13920
  if (!w.baseUrl) {
13919
13921
  X(null);
@@ -13926,7 +13928,7 @@ function ci({
13926
13928
  console.warn("Failed to fetch default message:", ve), X(null);
13927
13929
  }
13928
13930
  })();
13929
- }, [w]), tt(() => {
13931
+ }, [w]), nt(() => {
13930
13932
  _ && !Fe && (m == null || m(_));
13931
13933
  }, [_, Fe, m]);
13932
13934
  const Ps = (ie) => {
@@ -14020,11 +14022,11 @@ function ci({
14020
14022
  he(!0);
14021
14023
  try {
14022
14024
  if (!ie) {
14023
- await y(), nt(null), oe(null);
14025
+ await y(), tt(null), oe(null);
14024
14026
  return;
14025
14027
  }
14026
14028
  const ve = xe.find((Qe) => Qe.checkpointId === ie), De = (ve == null ? void 0 : ve.checkpointNs) ?? null;
14027
- await b(ie, De), nt(ie), oe(De);
14029
+ await b(ie, De), tt(ie), oe(De);
14028
14030
  } finally {
14029
14031
  he(!1);
14030
14032
  }
@@ -14808,7 +14810,7 @@ function wc({
14808
14810
  renameThread: g,
14809
14811
  isLoadingThreads: x
14810
14812
  } = rs(), [b, y] = fe(h ?? []), [R, S] = fe(null), [C, E] = fe(""), [k, N] = fe(!1);
14811
- tt(() => {
14813
+ nt(() => {
14812
14814
  y(h ?? []);
14813
14815
  }, [h]);
14814
14816
  const A = async (I) => {
@@ -16235,10 +16237,10 @@ const uT = {
16235
16237
  };
16236
16238
  function qT({ settings: e, onSettingsChange: t, className: n = "" }) {
16237
16239
  const [r, o] = fe(!1), [s, i] = fe(!1), [a, c] = fe(e), [u, d] = fe(!1), { toast: f } = ha();
16238
- tt(() => {
16240
+ nt(() => {
16239
16241
  const g = JSON.stringify(a) !== JSON.stringify(e);
16240
16242
  d(g);
16241
- }, [a, e]), tt(() => {
16243
+ }, [a, e]), nt(() => {
16242
16244
  c(e);
16243
16245
  }, [e]);
16244
16246
  const h = () => {
package/dist/index.umd.js CHANGED
@@ -32,7 +32,7 @@ React keys must be passed directly to JSX without using spread:
32
32
  `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[ol]=this[ol]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=pr(i);r[a]||(Em(o,i),r[a]=!0)}return P.isArray(t)?t.forEach(s):s(t),this}};wt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),P.reduceDescriptors(wt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),P.freezeMethods(wt);function Ls(e,t){const n=this||hr,r=t||n,o=wt.from(r.headers);let s=r.data;return P.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function sl(e){return!!(e&&e.__CANCEL__)}function Vn(e,t,n){Ne.call(this,e??"canceled",Ne.ERR_CANCELED,t,n),this.name="CanceledError"}P.inherits(Vn,Ne,{__CANCEL__:!0});function il(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Ne("Request failed with status code "+n.status,[Ne.ERR_BAD_REQUEST,Ne.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function km(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Im(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(c){const u=Date.now(),d=r[s];i||(i=u),n[o]=c,r[o]=u;let f=s,h=0;for(;f!==o;)h+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),u-i<t)return;const m=d&&u-d;return m?Math.round(h*1e3/m):void 0}}function Nm(e,t){let n=0,r=1e3/t,o,s;const i=(u,d=Date.now())=>{n=d,o=null,s&&(clearTimeout(s),s=null),e(...u)};return[(...u)=>{const d=Date.now(),f=d-n;f>=r?i(u,d):(o=u,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const eo=(e,t,n=3)=>{let r=0;const o=Im(50,250);return Nm(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,c=i-r,u=o(c),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:c,rate:u||void 0,estimated:u&&a&&d?(a-i)/u:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},al=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},ll=e=>(...t)=>P.asap(()=>e(...t)),Am=dt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,dt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(dt.origin),dt.navigator&&/(msie|trident)/i.test(dt.navigator.userAgent)):()=>!0,_m=dt.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];P.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),P.isString(r)&&i.push("path="+r),P.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function jm(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Rm(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function cl(e,t,n){let r=!jm(t);return e&&(r||n==!1)?Rm(e,t):t}const ul=e=>e instanceof wt?{...e}:e;function En(e,t){t=t||{};const n={};function r(u,d,f,h){return P.isPlainObject(u)&&P.isPlainObject(d)?P.merge.call({caseless:h},u,d):P.isPlainObject(d)?P.merge({},d):P.isArray(d)?d.slice():d}function o(u,d,f,h){if(P.isUndefined(d)){if(!P.isUndefined(u))return r(void 0,u,f,h)}else return r(u,d,f,h)}function s(u,d){if(!P.isUndefined(d))return r(void 0,d)}function i(u,d){if(P.isUndefined(d)){if(!P.isUndefined(u))return r(void 0,u)}else return r(void 0,d)}function a(u,d,f){if(f in t)return r(u,d);if(f in e)return r(void 0,u)}const c={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(u,d,f)=>o(ul(u),ul(d),f,!0)};return P.forEach(Object.keys({...e,...t}),function(d){const f=c[d]||o,h=f(e[d],t[d],d);P.isUndefined(h)&&f!==a||(n[d]=h)}),n}const dl=e=>{const t=En({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=wt.from(i),t.url=el(cl(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),P.isFormData(n)){if(dt.hasStandardBrowserEnv||dt.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(P.isFunction(n.getHeaders)){const c=n.getHeaders(),u=["content-type","content-length"];Object.entries(c).forEach(([d,f])=>{u.includes(d.toLowerCase())&&i.set(d,f)})}}if(dt.hasStandardBrowserEnv&&(r&&P.isFunction(r)&&(r=r(t)),r||r!==!1&&Am(t.url))){const c=o&&s&&_m.read(s);c&&i.set(o,c)}return t},Pm=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=dl(e);let s=o.data;const i=wt.from(o.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:u}=o,d,f,h,m,w;function v(){m&&m(),w&&w(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let g=new XMLHttpRequest;g.open(o.method.toUpperCase(),o.url,!0),g.timeout=o.timeout;function x(){if(!g)return;const S=wt.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?g.responseText:g.response,status:g.status,statusText:g.statusText,headers:S,config:e,request:g};il(function(I){n(I),v()},function(I){r(I),v()},C),g=null}"onloadend"in g?g.onloadend=x:g.onreadystatechange=function(){!g||g.readyState!==4||g.status===0&&!(g.responseURL&&g.responseURL.indexOf("file:")===0)||setTimeout(x)},g.onabort=function(){g&&(r(new Ne("Request aborted",Ne.ECONNABORTED,e,g)),g=null)},g.onerror=function(k){const C=k&&k.message?k.message:"Network Error",T=new Ne(C,Ne.ERR_NETWORK,e,g);T.event=k||null,r(T),g=null},g.ontimeout=function(){let k=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const C=o.transitional||nl;o.timeoutErrorMessage&&(k=o.timeoutErrorMessage),r(new Ne(k,C.clarifyTimeoutError?Ne.ETIMEDOUT:Ne.ECONNABORTED,e,g)),g=null},s===void 0&&i.setContentType(null),"setRequestHeader"in g&&P.forEach(i.toJSON(),function(k,C){g.setRequestHeader(C,k)}),P.isUndefined(o.withCredentials)||(g.withCredentials=!!o.withCredentials),a&&a!=="json"&&(g.responseType=o.responseType),u&&([h,w]=eo(u,!0),g.addEventListener("progress",h)),c&&g.upload&&([f,m]=eo(c),g.upload.addEventListener("progress",f),g.upload.addEventListener("loadend",m)),(o.cancelToken||o.signal)&&(d=S=>{g&&(r(!S||S.type?new Vn(null,e,g):S),g.abort(),g=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const b=km(o.url);if(b&&dt.protocols.indexOf(b)===-1){r(new Ne("Unsupported protocol "+b+":",Ne.ERR_BAD_REQUEST,e));return}g.send(s||null)})},Om=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(u){if(!o){o=!0,a();const d=u instanceof Error?u:this.reason;r.abort(d instanceof Ne?d:new Vn(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new Ne(`timeout ${t} of ms exceeded`,Ne.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(s):u.removeEventListener("abort",s)}),e=null)};e.forEach(u=>u.addEventListener("abort",s));const{signal:c}=r;return c.unsubscribe=()=>P.asap(a),c}},Mm=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},Dm=async function*(e,t){for await(const n of Lm(e))yield*Mm(n,t)},Lm=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},fl=(e,t,n,r)=>{const o=Dm(e,t);let s=0,i,a=c=>{i||(i=!0,r&&r(c))};return new ReadableStream({async pull(c){try{const{done:u,value:d}=await o.next();if(u){a(),c.close();return}let f=d.byteLength;if(n){let h=s+=f;n(h)}c.enqueue(new Uint8Array(d))}catch(u){throw a(u),u}},cancel(c){return a(c),o.return()}},{highWaterMark:2})},hl=64*1024,{isFunction:to}=P,$m=(({Request:e,Response:t})=>({Request:e,Response:t}))(P.global),{ReadableStream:pl,TextEncoder:ml}=P.global,gl=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Fm=e=>{e=P.merge.call({skipUndefined:!0},$m,e);const{fetch:t,Request:n,Response:r}=e,o=t?to(t):typeof fetch=="function",s=to(n),i=to(r);if(!o)return!1;const a=o&&to(pl),c=o&&(typeof ml=="function"?(w=>v=>w.encode(v))(new ml):async w=>new Uint8Array(await new n(w).arrayBuffer())),u=s&&a&&gl(()=>{let w=!1;const v=new n(dt.origin,{body:new pl,method:"POST",get duplex(){return w=!0,"half"}}).headers.has("Content-Type");return w&&!v}),d=i&&a&&gl(()=>P.isReadableStream(new r("").body)),f={stream:d&&(w=>w.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(w=>{!f[w]&&(f[w]=(v,g)=>{let x=v&&v[w];if(x)return x.call(v);throw new Ne(`Response type '${w}' is not supported`,Ne.ERR_NOT_SUPPORT,g)})});const h=async w=>{if(w==null)return 0;if(P.isBlob(w))return w.size;if(P.isSpecCompliantForm(w))return(await new n(dt.origin,{method:"POST",body:w}).arrayBuffer()).byteLength;if(P.isArrayBufferView(w)||P.isArrayBuffer(w))return w.byteLength;if(P.isURLSearchParams(w)&&(w=w+""),P.isString(w))return(await c(w)).byteLength},m=async(w,v)=>{const g=P.toFiniteNumber(w.getContentLength());return g??h(v)};return async w=>{let{url:v,method:g,data:x,signal:b,cancelToken:S,timeout:k,onDownloadProgress:C,onUploadProgress:T,responseType:I,headers:N,withCredentials:_="same-origin",fetchOptions:j}=dl(w),R=t||fetch;I=I?(I+"").toLowerCase():"text";let $=Om([b,S&&S.toAbortSignal()],k),z=null;const O=$&&$.unsubscribe&&(()=>{$.unsubscribe()});let W;try{if(T&&u&&g!=="get"&&g!=="head"&&(W=await m(N,x))!==0){let H=new n(v,{method:"POST",body:x,duplex:"half"}),J;if(P.isFormData(x)&&(J=H.headers.get("content-type"))&&N.setContentType(J),H.body){const[Q,ue]=al(W,eo(ll(T)));x=fl(H.body,hl,Q,ue)}}P.isString(_)||(_=_?"include":"omit");const B=s&&"credentials"in n.prototype,q={...j,signal:$,method:g.toUpperCase(),headers:N.normalize().toJSON(),body:x,duplex:"half",credentials:B?_:void 0};z=s&&new n(v,q);let L=await(s?R(z,j):R(v,q));const A=d&&(I==="stream"||I==="response");if(d&&(C||A&&O)){const H={};["status","statusText","headers"].forEach(be=>{H[be]=L[be]});const J=P.toFiniteNumber(L.headers.get("content-length")),[Q,ue]=C&&al(J,eo(ll(C),!0))||[];L=new r(fl(L.body,hl,Q,()=>{ue&&ue(),O&&O()}),H)}I=I||"text";let D=await f[P.findKey(f,I)||"text"](L,w);return!A&&O&&O(),await new Promise((H,J)=>{il(H,J,{data:D,headers:wt.from(L.headers),status:L.status,statusText:L.statusText,config:w,request:z})})}catch(B){throw O&&O(),B&&B.name==="TypeError"&&/Load failed|fetch/i.test(B.message)?Object.assign(new Ne("Network Error",Ne.ERR_NETWORK,w,z),{cause:B.cause||B}):Ne.from(B,B&&B.code,w,z)}}},zm=new Map,xl=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,c,u,d=zm;for(;a--;)c=s[a],u=d.get(c),u===void 0&&d.set(c,u=a?new Map:Fm(t)),d=u;return u};xl();const $s={http:lm,xhr:Pm,fetch:{get:xl}};P.forEach($s,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vl=e=>`- ${e}`,Bm=e=>P.isFunction(e)||e===null||e===!1,wl={getAdapter:(e,t)=>{e=P.isArray(e)?e:[e];const{length:n}=e;let r,o;const s={};for(let i=0;i<n;i++){r=e[i];let a;if(o=r,!Bm(r)&&(o=$s[(a=String(r)).toLowerCase()],o===void 0))throw new Ne(`Unknown adapter '${a}'`);if(o&&(P.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([c,u])=>`adapter ${c} `+(u===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
33
33
  `+i.map(vl).join(`
34
34
  `):" "+vl(i[0]):"as no adapter specified";throw new Ne("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:$s};function Fs(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Vn(null,e)}function bl(e){return Fs(e),e.headers=wt.from(e.headers),e.data=Ls.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),wl.getAdapter(e.adapter||hr.adapter,e)(e).then(function(r){return Fs(e),r.data=Ls.call(e,e.transformResponse,r),r.headers=wt.from(r.headers),r},function(r){return sl(r)||(Fs(e),r&&r.response&&(r.response.data=Ls.call(e,e.transformResponse,r.response),r.response.headers=wt.from(r.response.headers))),Promise.reject(r)})}const yl="1.12.2",no={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{no[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Sl={};no.transitional=function(t,n,r){function o(s,i){return"[Axios v"+yl+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new Ne(o(i," has been removed"+(n?" in "+n:"")),Ne.ERR_DEPRECATED);return n&&!Sl[i]&&(Sl[i]=!0,console.warn(o(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,i,a):!0}},no.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Hm(e,t,n){if(typeof e!="object")throw new Ne("options must be an object",Ne.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const a=e[s],c=a===void 0||i(a,s,e);if(c!==!0)throw new Ne("option "+s+" must be "+c,Ne.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Ne("Unknown option "+s,Ne.ERR_BAD_OPTION)}}const ro={assertOptions:Hm,validators:no},Vt=ro.validators;let kn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new tl,response:new tl}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
35
- `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=En(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&ro.assertOptions(r,{silentJSONParsing:Vt.transitional(Vt.boolean),forcedJSONParsing:Vt.transitional(Vt.boolean),clarifyTimeoutError:Vt.transitional(Vt.boolean)},!1),o!=null&&(P.isFunction(o)?n.paramsSerializer={serialize:o}:ro.assertOptions(o,{encode:Vt.function,serialize:Vt.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ro.assertOptions(n,{baseUrl:Vt.spelling("baseURL"),withXsrfToken:Vt.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&P.merge(s.common,s[n.method]);s&&P.forEach(["delete","get","head","post","put","patch","common"],w=>{delete s[w]}),n.headers=wt.concat(i,s);const a=[];let c=!0;this.interceptors.request.forEach(function(v){typeof v.runWhen=="function"&&v.runWhen(n)===!1||(c=c&&v.synchronous,a.unshift(v.fulfilled,v.rejected))});const u=[];this.interceptors.response.forEach(function(v){u.push(v.fulfilled,v.rejected)});let d,f=0,h;if(!c){const w=[bl.bind(this),void 0];for(w.unshift(...a),w.push(...u),h=w.length,d=Promise.resolve(n);f<h;)d=d.then(w[f++],w[f++]);return d}h=a.length;let m=n;for(;f<h;){const w=a[f++],v=a[f++];try{m=w(m)}catch(g){v.call(this,g);break}}try{d=bl.call(this,m)}catch(w){return Promise.reject(w)}for(f=0,h=u.length;f<h;)d=d.then(u[f++],u[f++]);return d}getUri(t){t=En(this.defaults,t);const n=cl(t.baseURL,t.url,t.allowAbsoluteUrls);return el(n,t.params,t.paramsSerializer)}};P.forEach(["delete","get","head","options"],function(t){kn.prototype[t]=function(n,r){return this.request(En(r||{},{method:t,url:n,data:(r||{}).data}))}}),P.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(En(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}kn.prototype[t]=n(),kn.prototype[t+"Form"]=n(!0)});let Um=class wp{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new Vn(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new wp(function(o){t=o}),cancel:t}}};function Wm(e){return function(n){return e.apply(null,n)}}function Vm(e){return P.isObject(e)&&e.isAxiosError===!0}const zs={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(zs).forEach(([e,t])=>{zs[t]=e});function Cl(e){const t=new kn(e),n=Fa(kn.prototype.request,t);return P.extend(n,kn.prototype,t,{allOwnKeys:!0}),P.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Cl(En(e,o))},n}const tt=Cl(hr);tt.Axios=kn,tt.CanceledError=Vn,tt.CancelToken=Um,tt.isCancel=sl,tt.VERSION=yl,tt.toFormData=Zr,tt.AxiosError=Ne,tt.Cancel=tt.CanceledError,tt.all=function(t){return Promise.all(t)},tt.spread=Wm,tt.isAxiosError=Vm,tt.mergeConfig=En,tt.AxiosHeaders=wt,tt.formToJSON=e=>rl(P.isHTMLForm(e)?new FormData(e):e),tt.getAdapter=wl.getAdapter,tt.HttpStatusCode=zs,tt.default=tt;const{Axios:kC,AxiosError:IC,CanceledError:NC,isCancel:AC,CancelToken:_C,VERSION:jC,all:RC,Cancel:PC,isAxiosError:OC,spread:MC,toFormData:DC,AxiosHeaders:LC,HttpStatusCode:$C,formToJSON:FC,getAdapter:zC,mergeConfig:BC}=tt,Tl=typeof window<"u"?window.__API_BASE_URL__:void 0,El=Tl?Tl.replace(/\/+$/,""):void 0;let oo=null;const Bs=new Set;function kl(){return oo}function Hs(e){oo=e,Bs.forEach(t=>t(e))}function Il(e){return Bs.add(e),()=>Bs.delete(e)}const _t=tt.create({...El?{baseURL:El}:{},timeout:3e4,withCredentials:!0});_t.interceptors.request.use(e=>(oo&&(e.headers.Authorization=`Bearer ${oo}`),e)),_t.interceptors.response.use(e=>e,e=>Promise.reject(e));async function St(e,t){return _t.defaults.baseURL?(await _t.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Us(e,t,n){return _t.defaults.baseURL?(await _t.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Nl(e,t,n){return _t.defaults.baseURL?(await _t.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Al(e,t){return _t.defaults.baseURL?(await _t.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Ct(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class _l{get baseUrl(){const t=_t.defaults.baseURL||"";return String(t).replace(/\/+$|^\s+|\s+$/g,"")}updateConfig(t){t.baseUrl&&(_t.defaults.baseURL=String(t.baseUrl).replace(/\/+$/g,"")),t.authToken!==void 0&&Hs(t.authToken)}getAuthToken(){return kl()}setAuthToken(t){Hs(t)}onTokenChange(t){return Il(t)}async listThreads(){const t=await St("/chat/threads"),n=Ct(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Us("/chat/threads",t?{title:t}:void 0);return Ct(r)}async updateThread(t,n){const r=await Nl(`/chat/threads/${t}`,{title:n});return Ct(r)}async deleteThread(t){const n=await Al(`/chat/threads/${t}`);return Ct(n)}async threadInfo(t){const n=await St(`/chat/threads/${t}/info`);return Ct(n)}async listAgents(){const t=await St("/chat/agents"),n=Ct(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await St(`/chat/agents/${t}`);return Ct(n)}async getAgentSchema(t){const n=await St(`/chat/agents/${t}/schema`);return Ct(n)}async getMessages(t){const n=await St(`/chat/threads/${t.threadId}/messages`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs,limit:t.limit,before_id:t.beforeId??void 0}});return Ct(n)}async getState(t){const n=await St(`/chat/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Ct(n)}async getStateHistory(t){const n=await St(`/chat/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Ct(n)}async listCheckpoints(t){const n=await St(`/chat/threads/${t}/checkpoints`,{params:{thread_id:t}});return Ct(n)}async resume(t){const n=await Us("/chat/runs/resume",{thread_id:t.threadId,value:t.value});return Ct(n)}}const cn=new _l,jl=y.createContext(null);function Km({children:e,apiConfig:t}){const n=cn;y.useEffect(()=>{t&&n.updateConfig({baseUrl:t.baseUrl,authToken:t.apiKey})},[n,t]);const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return l.jsx(jl.Provider,{value:r,children:e})}function so(){const e=y.useContext(jl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}const Rl=y.createContext(null),Pl=y.createContext(null);function qm(e,t){switch(t.type){case"STREAM_START":return{...e,isStreaming:!0,error:null,streamingAssistantId:t.assistantId??null};case"STREAM_END":return{...e,isStreaming:!1,streamingAssistantId:null};case"STREAM_ERROR":return{...e,isStreaming:!1,error:t.error};case"UPDATE_CHECKPOINT":return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:t.checkpointNs??e.lastCheckpointNs};case"UPDATE_ASSEMBLING_ID":return{...e,streamingAssistantId:t.assistantId};case"CLEAR_ERROR":return{...e,error:null};default:return e}}const Gm={isStreaming:!1,error:null,streamingAssistantId:null,lastCheckpointId:null,lastCheckpointNs:null};function Ym({children:e}){const[t,n]=y.useReducer(qm,Gm);return l.jsx(Pl.Provider,{value:n,children:l.jsx(Rl.Provider,{value:t,children:e})})}function Ol(){const e=y.useContext(Rl);if(!e)throw new Error("useStream must be used within StreamProvider");return e}function Xm(){const e=y.useContext(Pl);if(!e)throw new Error("useStreamDispatch must be used within StreamProvider");return e}function Jm(e,t){const n=e==null?void 0:e.checkpoints,r=Array.isArray(n)?n.slice():n?Object.values(n):[],o=i=>i&&typeof i=="object"&&i!==null&&"checkpointId"in i&&"createdAt"in i&&typeof i.checkpointId=="string"&&typeof i.createdAt=="string",s=r.filter(o).map(i=>{const a=i;return{checkpointId:a.checkpointId,checkpointNs:a.checkpointNs??"",createdAt:a.createdAt,messagesLen:a.messagesLen??0,preview:a.preview??"",role:a.role??null,parentId:a.parentId??null,editedMessageId:a.editedMessageId??null,branchLabel:a.branchLabel??null,lastMessageId:a.lastMessageId??null,hasMessages:typeof a.hasMessages=="boolean"?a.hasMessages:void 0}});return{threadId:(e==null?void 0:e.threadId)??t??null,checkpoints:s}}async function Zm(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let c=0;c<a;c++)i+=String.fromCharCode(s[c]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Qm(e,t=[],n,r,o,s){const i=[],a=[];for(const c of t)try{const u=await Zm(c);a.push({filename:c.name,data:u,mime_type:c.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Ml=y.createContext(null),Dl=y.createContext(null);function eg({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,onThreadChange:o,onError:s}){const{api:i}=so(),[a,c]=y.useState([]),[u,d]=y.useState(t),[f,h]=y.useState(!1),[m,w]=y.useState(!1),[v,g]=y.useState(void 0),[x,b]=y.useState(void 0),S=y.useRef(!1),k=y.useRef([]),C=y.useRef(null),T=y.useRef(null);y.useRef(!1);const I=y.useRef(u);y.useEffect(()=>{I.current=u},[u]);const N=y.useContext(Dl),_=y.useCallback((D,H)=>new Promise((J,Q)=>{const ue=async()=>{S.current=!0;try{console.log(`[ThreadProvider] Executing operation: ${H||"unnamed"}`),await D(),J()}catch(be){console.error(`[ThreadProvider] Operation "${H}" failed:`,be),Q(be)}finally{S.current=!1;const be=k.current.shift();be&&be().catch(()=>{})}};S.current?(k.current.push(ue),console.log(`[ThreadProvider] Queued operation: ${H||"unnamed"}`)):ue().catch(be=>{Q(be)})}),[]),j=y.useCallback(async()=>{h(!0);try{const D=await i.listThreads();c(D)}catch(D){console.error("[ThreadProvider] Failed to refresh threads:",D),s==null||s(String(D))}finally{h(!1)}},[i,s]),R=y.useCallback(async D=>{const H=await i.createThread(D),J=typeof H=="string"?H:H.threadId;return await j(),d(J),J},[i,j]),$=y.useCallback(async D=>{await i.deleteThread(D),u===D&&(d(null),N==null||N.onThreadCleared()),await j()},[i,u,j,N]),z=y.useCallback(async(D,H)=>{try{await i.updateThread(D,H),c(J=>J.map(Q=>Q.threadId===D?{...Q,title:H}:Q))}catch(J){throw await j(),J}},[i,j]),O=y.useCallback(async(D,H,J,Q=!1)=>{await _(async()=>{if(T.current===D&&!Q){console.log("[ThreadProvider] Skipping load for thread:",D),T.current=null;return}if(C.current===D&&!Q){console.log("[ThreadProvider] Load already in progress for thread:",D);return}d(ue=>ue===D?ue:D),C.current=D,w(!0);try{const ue=await i.getMessages({threadId:D,checkpointId:H,checkpointNs:J});N==null||N.onThreadLoaded(D,ue),g((ue==null?void 0:ue.checkpointId)??void 0),b((ue==null?void 0:ue.checkpointNs)??void 0)}finally{C.current=null,w(!1)}},`loadThread-${D}`)},[i,_,N,d]),W=y.useCallback(async()=>{console.log("[ThreadProvider] 🔄 clearCurrentThread called"),await _(async()=>{u&&(T.current=u),N==null||N.onThreadCleared(),d(null),g(void 0),b(void 0);try{localStorage.removeItem("lastThreadId")}catch(D){console.warn("[ThreadProvider] Failed to clear localStorage:",D)}},"clearCurrentThread")},[u,_,N]),B=y.useCallback(async D=>{const H=await i.listCheckpoints(D);return Jm(H,D)},[i]),q=y.useCallback(async(D,H)=>{if(!u)throw new Error("No active thread");await O(u,D,H??void 0,!0)},[u,O]),L=y.useCallback(async()=>{if(!u)throw new Error("No active thread");await O(u,void 0,void 0,!0)},[u,O]);y.useEffect(()=>{if(o==null||o(u),u)try{localStorage.setItem("lastThreadId",u)}catch(D){console.warn("[ThreadProvider] Failed to persist thread ID:",D)}},[u,o]),y.useEffect(()=>{let D=!0;return(async()=>{try{if(await j(),!D)return;if(!r&&!t)try{const J=localStorage.getItem("lastThreadId");J&&(d(J),n&&await O(J))}catch(J){console.warn("[ThreadProvider] Failed to restore from localStorage:",J)}else t&&n&&await O(t)}catch(J){console.error("[ThreadProvider] Initialization failed:",J),s==null||s(String(J))}})(),()=>{D=!1}},[]);const A={threads:a,currentThreadId:u,isLoadingThreads:f,isLoadingThread:m,setCurrentThreadId:d,createThread:R,deleteThread:$,renameThread:z,refreshThreads:j,loadThread:O,clearCurrentThread:W,listCheckpoints:B,navigateToCheckpoint:q,returnToLatest:L};return l.jsx(Ml.Provider,{value:A,children:e})}function mr(){const e=y.useContext(Ml);if(!e)throw new Error("useThreads must be used within ThreadProvider");return e}function tg({children:e,onThreadLoaded:t,onThreadCleared:n,...r}){return l.jsx(Dl.Provider,{value:{onThreadLoaded:t,onThreadCleared:n},children:l.jsx(eg,{...r,children:e})})}function ng(e){return e.type!=="thread_info"&&e.type!=="token"}const rg={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null};function og(e,t){var n;switch(t.type){case"reset":{console.log("[MessageReducer] 🔄 RESET action received"),console.log("[MessageReducer] 📊 Before reset - messages count:",e.messages.length);const r={messages:Ws(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null};return console.log("[MessageReducer] 📊 After reset - messages count:",r.messages.length),r}case"seed":{const r=Ws(t.payload.messages),o={...e,messages:r,assemblingId:null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),console.log("[MessageReducer] seed action (REPLACE mode):",{incomingCount:t.payload.messages.length,sanitizedCount:r.length,previousCount:e.messages.length,checkpointId:o.lastCheckpointId}),o}case"prepend":{const r=Ws(t.payload.messages);if(!r.length)return console.log("[MessageReducer] No incoming messages after sanitize - skipping"),e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return console.log("[MessageReducer] After dedup:",{uniqueCount:s.length,duplicates:r.length-s.length,finalTotal:s.length+e.messages.length}),s.length?{...e,messages:[...s,...e.messages]}:(console.log("[MessageReducer] All messages were duplicates - skipping"),e)}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return $l(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>$l(o,s),e):e}case"interrupt_response":{const{interruptId:r}=t.payload,o=e.messages.map(s=>({...s,content:s.content.filter(i=>i.type!=="interrupt")}));return{...e,messages:o,pendingInterrupt:null}}default:return e}}function Ll(e=[]){const[t,n]=y.useReducer(og,{...rg,messages:e}),r=y.useRef([]),o=y.useRef(null),s=y.useRef(null),i=y.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=y.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),c=y.useCallback(d=>{r.current.push(d),a()},[a]);y.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const u=y.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:c}),[c]);return{state:t,dispatch:n,...u}}function $l(e,t){var n,r;if(t.type==="message_start"&&t.role==="assistant"){const o=t.id,s=ug(t.model);if(e.messages.some(c=>c.id===o))return{...e,assemblingId:o};const a={id:o,role:"assistant",name:s||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:o,messages:[...e.messages,a]}}if(t.type==="message_delta"){const o=e.assemblingId??Vs(e.messages);return o?{...e,messages:Ks(e.messages,o,t.delta)}:e}if(t.type==="message_end"){const o=e.assemblingId??Vs(e.messages);if(!o)return{...e,assemblingId:null};const s=e.messages,i=s.findIndex(a=>a.id===o&&a.role==="assistant");if(i>=0&&!((n=s[i].content)==null?void 0:n.some(u=>{var d;return(u==null?void 0:u.type)==="text"&&((d=u.text)==null?void 0:d.trim())}))){const u=[...s.slice(0,i),...s.slice(i+1)];return{...e,assemblingId:null,messages:u}}return e}if(t.type==="tool_start"){const o=t.id??t.call_id,s=t.name??t.tool??"tool";if(!o)return e;const i=`tool-${o}`,a={type:"tool_call",id:o,name:s,args:t.args};if(e.messages.find(d=>d.id===i))return{...e,toolIndex:{...e.toolIndex,[o]:i}};const u={id:i,role:"tool",name:s,createdAt:new Date().toISOString(),content:[a]};return{...e,messages:[...e.messages,u],toolIndex:{...e.toolIndex,[o]:i}}}if(t.type==="tool_end"){const o=t.id??t.call_id;if(!o)return e;const s=e.toolIndex[o]??`tool-${o}`,i={type:"tool_end",toolCallId:o,output:t.output,error:t.error},a=e.messages.find(d=>d.id===s),c={id:s,role:"tool",name:t.name??((r=e.messages.find(d=>d.id===s))==null?void 0:r.name),content:[i],createdAt:new Date().toISOString()},u=a?Ks(e.messages,s,[i]):[...e.messages,c];return{...e,messages:u,toolIndex:{...e.toolIndex,[o]:s}}}if(t.type==="checkpoint"){const o=t.checkpointNs??e.lastCheckpointNs??null,s=cg(e.messages,t.checkpointId,o);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:o,messages:s}}if(t.type==="branch"){const o=t.checkpointId??e.lastCheckpointId,s=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:o??null,lastCheckpointNs:s??null}}if(t.type==="error"){const o={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,o]}}if(t.type==="interrupt"){const o=e.assemblingId??Vs(e.messages),s={type:"interrupt",value:t.value};if(o)return{...e,assemblingId:null,messages:Ks(e.messages,o,[s]),pendingInterrupt:{id:t.id,value:t.value}};const i={id:`interrupt-${t.id}`,role:"system",createdAt:new Date().toISOString(),content:[s]};return{...e,messages:[...e.messages,i],pendingInterrupt:{id:t.id,value:t.value}}}return e}function Ws(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function sg(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Vs(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function ig(e,t,n){const r=e.findIndex(i=>i.id===t);if(r===-1)return e;const o=e[r],s=n(o);return s===o?e:[...e.slice(0,r),s,...e.slice(r+1)]}function Ks(e,t,n){return ig(e,t,r=>({...r,content:ag(r.content,n)}))}function ag(e,t){const n=e.slice();for(const r of t)if(r.type==="text"){const o=n[n.length-1],s=r.text??"";if(!s)continue;if((o==null?void 0:o.type)==="text"){const i=o,a=lg(i.text??"",s);if(!a)continue;i.text=(i.text??"")+a}else n.push({type:"text",text:s})}else n.push(r);return n}function lg(e,t){if(!t)return"";if(!e)return t;if(t===e)return"";const n=t.indexOf(e);if(n===0)return t.slice(e.length);if(n>0){const o=t.slice(n+e.length);if(o)return o}if(e.endsWith(t)||e.includes(t))return"";const r=Math.min(e.length,t.length);for(let o=r;o>0;o--)if(e.slice(-o)===t.slice(0,o))return t.slice(o);return t}function cg(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return sg(e,r,s)}return e}function ug(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const dg={MODE:"library"};function fg(){var i;const e=typeof globalThis<"u"?globalThis.process:void 0,t=typeof((i=e==null?void 0:e.env)==null?void 0:i.NODE_ENV)=="string"?e.env.NODE_ENV:void 0;if(t)return t==="production";const n=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Ns&&Ns.tagName.toUpperCase()==="SCRIPT"&&Ns.src||new URL("index.umd.js",document.baseURI).href}<"u"?dg:void 0,r=typeof(n==null?void 0:n.MODE)=="string"?n.MODE:void 0,o=typeof(n==null?void 0:n.NODE_ENV)=="string"?n.NODE_ENV:void 0;return(r??o)==="production"}function hg(){return!fg()}function pg({onThreadInfo:e,onMessageEvent:t,onUnhandledEvent:n,onSequenceGap:r}){const o=y.useRef(null),s=y.useCallback(a=>{const c=a.seq;if(c!=null){const u=o.current;if(u!==null){if(c<=u){hg()&&console.debug("[StreamEventCoordinator] drop out-of-order seq",{prev:u,seq:c,type:a.type});return}c>u+1&&(r==null||r({from:u,to:c}))}o.current=c}if(a.type==="thread_info"){e==null||e(a);return}if(ng(a)){t(a);return}n==null||n(a)},[t,r,e,n]),i=y.useCallback(()=>{o.current=null},[]);return{handleEvent:s,reset:i}}function Fl(e={}){const t=y.useMemo(()=>{const j=(e.baseUrl??"/api/chat").replace(/\/+$/,"");return j.endsWith("/chat")?j:`${j}/chat`},[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=y.useState(e.token??null),s=y.useRef(e.headers??{}),[i,a]=y.useState(!1),[c,u]=y.useState(null),[d,f]=y.useState(""),[h,m]=y.useState(null),[w,v]=y.useState(0),[g,x]=y.useState(!1),b=y.useRef(null),S=y.useRef(!0),k=y.useRef(0),C=y.useCallback(_=>{o(_)},[]),T=y.useCallback(()=>{var _;(_=b.current)==null||_.abort(),b.current=null,a(!1),x(!1)},[]),I=y.useCallback(()=>{f(""),m(null),u(null)},[]),N=y.useCallback((_,j,R)=>{b.current&&(b.current.abort(),b.current=null),a(!0),u(null),e.autoAppendAssistant!==!1&&f("");const $=new AbortController;return b.current=$,(async()=>{var O,W,B,q,L,A,D,H;const z=J=>{var Q;try{const ue=JSON.parse(JSON.stringify(J));return(Q=ue==null?void 0:ue.payload)!=null&&Q.files_info&&Array.isArray(ue.payload.files_info)&&(ue.payload.files_info=ue.payload.files_info.map(be=>({...be,data:be!=null&&be.data?`<base64 ${String(be.data).length} chars>`:be==null?void 0:be.data}))),ue}catch{return J}};try{let J={};try{if(r)J={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const X=window.__AUTH_TOKEN__,xe=((O=window.localStorage)==null?void 0:O.getItem("authToken"))||null;let Pe=null;try{const et=(W=window.localStorage)==null?void 0:W.getItem("chat-settings");et&&(Pe=((B=JSON.parse(et))==null?void 0:B.apiKey)||null)}catch{}const _e=X||xe||Pe||null;_e&&(J={Authorization:`Bearer ${_e}`})}}catch{}console.debug("[use-chat] POST",t+n,z(_));const Q=await fetch(t+n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...J,...s.current},body:JSON.stringify(_),signal:$.signal});if(!Q.ok||!Q.body){const V=await Q.text().catch(()=>"");throw console.debug("[use-chat] non-OK response",Q.status,V==null?void 0:V.slice(0,500)),new Error(`stream ${Q.status}${V?": "+V:""}`)}x(!0);const ue=Q.body.getReader(),be=new TextDecoder;let Ie="",K=[],M=k.current,Y=null;const ee=()=>{if(K.length){const V=K.join("");K=[],S.current&&f(X=>X+V)}Y=null},de=()=>{typeof window<"u"&&Y==null&&(Y=requestAnimationFrame(ee))};let ce=Date.now();const ze=setInterval(()=>{var V;if(Date.now()-ce>2e4){const X="Stream idle timeout";u(X),$.abort(),(V=R==null?void 0:R.onError)==null||V.call(R,X)}},5e3),Ye=1024*1024;try{const V=Q.headers.get("X-Thread-Id")||Q.headers.get("x-thread-id"),X=Q.headers.get("X-Thread-Created")||Q.headers.get("x-thread-created"),xe=V??null,Pe=String(X??"").toLowerCase()==="true";for((q=R==null?void 0:R.onOpen)==null||q.call(R,{threadId:xe,created:Pe});;){const{value:_e,done:et}=await ue.read();if(et)break;Ie+=be.decode(_e,{stream:!0}),Ie.length>Ye&&(Ie="",console.warn("Stream buffer reset: exceeded 1MB"));let st;for(;(st=Ie.indexOf(`
35
+ `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=En(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&ro.assertOptions(r,{silentJSONParsing:Vt.transitional(Vt.boolean),forcedJSONParsing:Vt.transitional(Vt.boolean),clarifyTimeoutError:Vt.transitional(Vt.boolean)},!1),o!=null&&(P.isFunction(o)?n.paramsSerializer={serialize:o}:ro.assertOptions(o,{encode:Vt.function,serialize:Vt.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ro.assertOptions(n,{baseUrl:Vt.spelling("baseURL"),withXsrfToken:Vt.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&P.merge(s.common,s[n.method]);s&&P.forEach(["delete","get","head","post","put","patch","common"],w=>{delete s[w]}),n.headers=wt.concat(i,s);const a=[];let c=!0;this.interceptors.request.forEach(function(v){typeof v.runWhen=="function"&&v.runWhen(n)===!1||(c=c&&v.synchronous,a.unshift(v.fulfilled,v.rejected))});const u=[];this.interceptors.response.forEach(function(v){u.push(v.fulfilled,v.rejected)});let d,f=0,h;if(!c){const w=[bl.bind(this),void 0];for(w.unshift(...a),w.push(...u),h=w.length,d=Promise.resolve(n);f<h;)d=d.then(w[f++],w[f++]);return d}h=a.length;let m=n;for(;f<h;){const w=a[f++],v=a[f++];try{m=w(m)}catch(g){v.call(this,g);break}}try{d=bl.call(this,m)}catch(w){return Promise.reject(w)}for(f=0,h=u.length;f<h;)d=d.then(u[f++],u[f++]);return d}getUri(t){t=En(this.defaults,t);const n=cl(t.baseURL,t.url,t.allowAbsoluteUrls);return el(n,t.params,t.paramsSerializer)}};P.forEach(["delete","get","head","options"],function(t){kn.prototype[t]=function(n,r){return this.request(En(r||{},{method:t,url:n,data:(r||{}).data}))}}),P.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(En(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}kn.prototype[t]=n(),kn.prototype[t+"Form"]=n(!0)});let Um=class wp{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new Vn(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new wp(function(o){t=o}),cancel:t}}};function Wm(e){return function(n){return e.apply(null,n)}}function Vm(e){return P.isObject(e)&&e.isAxiosError===!0}const zs={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(zs).forEach(([e,t])=>{zs[t]=e});function Cl(e){const t=new kn(e),n=Fa(kn.prototype.request,t);return P.extend(n,kn.prototype,t,{allOwnKeys:!0}),P.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Cl(En(e,o))},n}const tt=Cl(hr);tt.Axios=kn,tt.CanceledError=Vn,tt.CancelToken=Um,tt.isCancel=sl,tt.VERSION=yl,tt.toFormData=Zr,tt.AxiosError=Ne,tt.Cancel=tt.CanceledError,tt.all=function(t){return Promise.all(t)},tt.spread=Wm,tt.isAxiosError=Vm,tt.mergeConfig=En,tt.AxiosHeaders=wt,tt.formToJSON=e=>rl(P.isHTMLForm(e)?new FormData(e):e),tt.getAdapter=wl.getAdapter,tt.HttpStatusCode=zs,tt.default=tt;const{Axios:kC,AxiosError:IC,CanceledError:NC,isCancel:AC,CancelToken:_C,VERSION:jC,all:RC,Cancel:PC,isAxiosError:OC,spread:MC,toFormData:DC,AxiosHeaders:LC,HttpStatusCode:$C,formToJSON:FC,getAdapter:zC,mergeConfig:BC}=tt,Tl=typeof window<"u"?window.__API_BASE_URL__:void 0,El=Tl?Tl.replace(/\/+$/,""):void 0;let oo=null;const Bs=new Set;function kl(){return oo}function Hs(e){oo=e,Bs.forEach(t=>t(e))}function Il(e){return Bs.add(e),()=>Bs.delete(e)}const _t=tt.create({...El?{baseURL:El}:{},timeout:3e4,withCredentials:!0});_t.interceptors.request.use(e=>(oo&&(e.headers.Authorization=`Bearer ${oo}`),e)),_t.interceptors.response.use(e=>e,e=>Promise.reject(e));async function St(e,t){return _t.defaults.baseURL?(await _t.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Us(e,t,n){return _t.defaults.baseURL?(await _t.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Nl(e,t,n){return _t.defaults.baseURL?(await _t.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Al(e,t){return _t.defaults.baseURL?(await _t.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Ct(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class _l{get baseUrl(){const t=_t.defaults.baseURL||"";return String(t).replace(/\/+$|^\s+|\s+$/g,"")}updateConfig(t){t.baseUrl&&(_t.defaults.baseURL=String(t.baseUrl).replace(/\/+$/g,"")),t.authToken!==void 0&&Hs(t.authToken)}getAuthToken(){return kl()}setAuthToken(t){Hs(t)}onTokenChange(t){return Il(t)}async listThreads(){const t=await St("/chat/threads"),n=Ct(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Us("/chat/threads",t?{title:t}:void 0);return Ct(r)}async updateThread(t,n){const r=await Nl(`/chat/threads/${t}`,{title:n});return Ct(r)}async deleteThread(t){const n=await Al(`/chat/threads/${t}`);return Ct(n)}async threadInfo(t){const n=await St(`/chat/threads/${t}/info`);return Ct(n)}async listAgents(){const t=await St("/chat/agents"),n=Ct(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await St(`/chat/agents/${t}`);return Ct(n)}async getAgentSchema(t){const n=await St(`/chat/agents/${t}/schema`);return Ct(n)}async getMessages(t){const n=await St(`/chat/threads/${t.threadId}/messages`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs,limit:t.limit,before_id:t.beforeId??void 0}});return Ct(n)}async getState(t){const n=await St(`/chat/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Ct(n)}async getStateHistory(t){const n=await St(`/chat/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Ct(n)}async listCheckpoints(t){const n=await St(`/chat/threads/${t}/checkpoints`,{params:{thread_id:t}});return Ct(n)}async resume(t){const n=await Us("/chat/runs/resume",{thread_id:t.threadId,value:t.value});return Ct(n)}}const cn=new _l,jl=y.createContext(null);function Km({children:e,apiConfig:t}){const n=cn;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return l.jsx(jl.Provider,{value:r,children:e})}function so(){const e=y.useContext(jl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}const Rl=y.createContext(null),Pl=y.createContext(null);function qm(e,t){switch(t.type){case"STREAM_START":return{...e,isStreaming:!0,error:null,streamingAssistantId:t.assistantId??null};case"STREAM_END":return{...e,isStreaming:!1,streamingAssistantId:null};case"STREAM_ERROR":return{...e,isStreaming:!1,error:t.error};case"UPDATE_CHECKPOINT":return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:t.checkpointNs??e.lastCheckpointNs};case"UPDATE_ASSEMBLING_ID":return{...e,streamingAssistantId:t.assistantId};case"CLEAR_ERROR":return{...e,error:null};default:return e}}const Gm={isStreaming:!1,error:null,streamingAssistantId:null,lastCheckpointId:null,lastCheckpointNs:null};function Ym({children:e}){const[t,n]=y.useReducer(qm,Gm);return l.jsx(Pl.Provider,{value:n,children:l.jsx(Rl.Provider,{value:t,children:e})})}function Ol(){const e=y.useContext(Rl);if(!e)throw new Error("useStream must be used within StreamProvider");return e}function Xm(){const e=y.useContext(Pl);if(!e)throw new Error("useStreamDispatch must be used within StreamProvider");return e}function Jm(e,t){const n=e==null?void 0:e.checkpoints,r=Array.isArray(n)?n.slice():n?Object.values(n):[],o=i=>i&&typeof i=="object"&&i!==null&&"checkpointId"in i&&"createdAt"in i&&typeof i.checkpointId=="string"&&typeof i.createdAt=="string",s=r.filter(o).map(i=>{const a=i;return{checkpointId:a.checkpointId,checkpointNs:a.checkpointNs??"",createdAt:a.createdAt,messagesLen:a.messagesLen??0,preview:a.preview??"",role:a.role??null,parentId:a.parentId??null,editedMessageId:a.editedMessageId??null,branchLabel:a.branchLabel??null,lastMessageId:a.lastMessageId??null,hasMessages:typeof a.hasMessages=="boolean"?a.hasMessages:void 0}});return{threadId:(e==null?void 0:e.threadId)??t??null,checkpoints:s}}async function Zm(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let c=0;c<a;c++)i+=String.fromCharCode(s[c]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Qm(e,t=[],n,r,o,s){const i=[],a=[];for(const c of t)try{const u=await Zm(c);a.push({filename:c.name,data:u,mime_type:c.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Ml=y.createContext(null),Dl=y.createContext(null);function eg({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,onThreadChange:o,onError:s}){const{api:i}=so(),[a,c]=y.useState([]),[u,d]=y.useState(t),[f,h]=y.useState(!1),[m,w]=y.useState(!1),[v,g]=y.useState(void 0),[x,b]=y.useState(void 0),S=y.useRef(!1),k=y.useRef([]),C=y.useRef(null),T=y.useRef(null);y.useRef(!1);const I=y.useRef(u);y.useEffect(()=>{I.current=u},[u]);const N=y.useContext(Dl),_=y.useCallback((D,H)=>new Promise((J,Q)=>{const ue=async()=>{S.current=!0;try{console.log(`[ThreadProvider] Executing operation: ${H||"unnamed"}`),await D(),J()}catch(be){console.error(`[ThreadProvider] Operation "${H}" failed:`,be),Q(be)}finally{S.current=!1;const be=k.current.shift();be&&be().catch(()=>{})}};S.current?(k.current.push(ue),console.log(`[ThreadProvider] Queued operation: ${H||"unnamed"}`)):ue().catch(be=>{Q(be)})}),[]),j=y.useCallback(async()=>{h(!0);try{const D=await i.listThreads();c(D)}catch(D){console.error("[ThreadProvider] Failed to refresh threads:",D),s==null||s(String(D))}finally{h(!1)}},[i,s]),R=y.useCallback(async D=>{const H=await i.createThread(D),J=typeof H=="string"?H:H.threadId;return await j(),d(J),J},[i,j]),$=y.useCallback(async D=>{await i.deleteThread(D),u===D&&(d(null),N==null||N.onThreadCleared()),await j()},[i,u,j,N]),z=y.useCallback(async(D,H)=>{try{await i.updateThread(D,H),c(J=>J.map(Q=>Q.threadId===D?{...Q,title:H}:Q))}catch(J){throw await j(),J}},[i,j]),O=y.useCallback(async(D,H,J,Q=!1)=>{await _(async()=>{if(T.current===D&&!Q){console.log("[ThreadProvider] Skipping load for thread:",D),T.current=null;return}if(C.current===D&&!Q){console.log("[ThreadProvider] Load already in progress for thread:",D);return}d(ue=>ue===D?ue:D),C.current=D,w(!0);try{const ue=await i.getMessages({threadId:D,checkpointId:H,checkpointNs:J});N==null||N.onThreadLoaded(D,ue),g((ue==null?void 0:ue.checkpointId)??void 0),b((ue==null?void 0:ue.checkpointNs)??void 0)}finally{C.current=null,w(!1)}},`loadThread-${D}`)},[i,_,N,d]),W=y.useCallback(async()=>{console.log("[ThreadProvider] 🔄 clearCurrentThread called"),await _(async()=>{u&&(T.current=u),N==null||N.onThreadCleared(),d(null),g(void 0),b(void 0);try{localStorage.removeItem("lastThreadId")}catch(D){console.warn("[ThreadProvider] Failed to clear localStorage:",D)}},"clearCurrentThread")},[u,_,N]),B=y.useCallback(async D=>{const H=await i.listCheckpoints(D);return Jm(H,D)},[i]),q=y.useCallback(async(D,H)=>{if(!u)throw new Error("No active thread");await O(u,D,H??void 0,!0)},[u,O]),L=y.useCallback(async()=>{if(!u)throw new Error("No active thread");await O(u,void 0,void 0,!0)},[u,O]);y.useEffect(()=>{if(o==null||o(u),u)try{localStorage.setItem("lastThreadId",u)}catch(D){console.warn("[ThreadProvider] Failed to persist thread ID:",D)}},[u,o]),y.useEffect(()=>{let D=!0;return(async()=>{try{if(await j(),!D)return;if(!r&&!t)try{const J=localStorage.getItem("lastThreadId");J&&(d(J),n&&await O(J))}catch(J){console.warn("[ThreadProvider] Failed to restore from localStorage:",J)}else t&&n&&await O(t)}catch(J){console.error("[ThreadProvider] Initialization failed:",J),s==null||s(String(J))}})(),()=>{D=!1}},[]);const A={threads:a,currentThreadId:u,isLoadingThreads:f,isLoadingThread:m,setCurrentThreadId:d,createThread:R,deleteThread:$,renameThread:z,refreshThreads:j,loadThread:O,clearCurrentThread:W,listCheckpoints:B,navigateToCheckpoint:q,returnToLatest:L};return l.jsx(Ml.Provider,{value:A,children:e})}function mr(){const e=y.useContext(Ml);if(!e)throw new Error("useThreads must be used within ThreadProvider");return e}function tg({children:e,onThreadLoaded:t,onThreadCleared:n,...r}){return l.jsx(Dl.Provider,{value:{onThreadLoaded:t,onThreadCleared:n},children:l.jsx(eg,{...r,children:e})})}function ng(e){return e.type!=="thread_info"&&e.type!=="token"}const rg={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null};function og(e,t){var n;switch(t.type){case"reset":{console.log("[MessageReducer] 🔄 RESET action received"),console.log("[MessageReducer] 📊 Before reset - messages count:",e.messages.length);const r={messages:Ws(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null};return console.log("[MessageReducer] 📊 After reset - messages count:",r.messages.length),r}case"seed":{const r=Ws(t.payload.messages),o={...e,messages:r,assemblingId:null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),console.log("[MessageReducer] seed action (REPLACE mode):",{incomingCount:t.payload.messages.length,sanitizedCount:r.length,previousCount:e.messages.length,checkpointId:o.lastCheckpointId}),o}case"prepend":{const r=Ws(t.payload.messages);if(!r.length)return console.log("[MessageReducer] No incoming messages after sanitize - skipping"),e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return console.log("[MessageReducer] After dedup:",{uniqueCount:s.length,duplicates:r.length-s.length,finalTotal:s.length+e.messages.length}),s.length?{...e,messages:[...s,...e.messages]}:(console.log("[MessageReducer] All messages were duplicates - skipping"),e)}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return $l(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>$l(o,s),e):e}case"interrupt_response":{const{interruptId:r}=t.payload,o=e.messages.map(s=>({...s,content:s.content.filter(i=>i.type!=="interrupt")}));return{...e,messages:o,pendingInterrupt:null}}default:return e}}function Ll(e=[]){const[t,n]=y.useReducer(og,{...rg,messages:e}),r=y.useRef([]),o=y.useRef(null),s=y.useRef(null),i=y.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=y.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),c=y.useCallback(d=>{r.current.push(d),a()},[a]);y.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const u=y.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:c}),[c]);return{state:t,dispatch:n,...u}}function $l(e,t){var n,r;if(t.type==="message_start"&&t.role==="assistant"){const o=t.id,s=ug(t.model);if(e.messages.some(c=>c.id===o))return{...e,assemblingId:o};const a={id:o,role:"assistant",name:s||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:o,messages:[...e.messages,a]}}if(t.type==="message_delta"){const o=e.assemblingId??Vs(e.messages);return o?{...e,messages:Ks(e.messages,o,t.delta)}:e}if(t.type==="message_end"){const o=e.assemblingId??Vs(e.messages);if(!o)return{...e,assemblingId:null};const s=e.messages,i=s.findIndex(a=>a.id===o&&a.role==="assistant");if(i>=0&&!((n=s[i].content)==null?void 0:n.some(u=>{var d;return(u==null?void 0:u.type)==="text"&&((d=u.text)==null?void 0:d.trim())}))){const u=[...s.slice(0,i),...s.slice(i+1)];return{...e,assemblingId:null,messages:u}}return e}if(t.type==="tool_start"){const o=t.id??t.call_id,s=t.name??t.tool??"tool";if(!o)return e;const i=`tool-${o}`,a={type:"tool_call",id:o,name:s,args:t.args};if(e.messages.find(d=>d.id===i))return{...e,toolIndex:{...e.toolIndex,[o]:i}};const u={id:i,role:"tool",name:s,createdAt:new Date().toISOString(),content:[a]};return{...e,messages:[...e.messages,u],toolIndex:{...e.toolIndex,[o]:i}}}if(t.type==="tool_end"){const o=t.id??t.call_id;if(!o)return e;const s=e.toolIndex[o]??`tool-${o}`,i={type:"tool_end",toolCallId:o,output:t.output,error:t.error},a=e.messages.find(d=>d.id===s),c={id:s,role:"tool",name:t.name??((r=e.messages.find(d=>d.id===s))==null?void 0:r.name),content:[i],createdAt:new Date().toISOString()},u=a?Ks(e.messages,s,[i]):[...e.messages,c];return{...e,messages:u,toolIndex:{...e.toolIndex,[o]:s}}}if(t.type==="checkpoint"){const o=t.checkpointNs??e.lastCheckpointNs??null,s=cg(e.messages,t.checkpointId,o);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:o,messages:s}}if(t.type==="branch"){const o=t.checkpointId??e.lastCheckpointId,s=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:o??null,lastCheckpointNs:s??null}}if(t.type==="error"){const o={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,o]}}if(t.type==="interrupt"){const o=e.assemblingId??Vs(e.messages),s={type:"interrupt",value:t.value};if(o)return{...e,assemblingId:null,messages:Ks(e.messages,o,[s]),pendingInterrupt:{id:t.id,value:t.value}};const i={id:`interrupt-${t.id}`,role:"system",createdAt:new Date().toISOString(),content:[s]};return{...e,messages:[...e.messages,i],pendingInterrupt:{id:t.id,value:t.value}}}return e}function Ws(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function sg(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Vs(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function ig(e,t,n){const r=e.findIndex(i=>i.id===t);if(r===-1)return e;const o=e[r],s=n(o);return s===o?e:[...e.slice(0,r),s,...e.slice(r+1)]}function Ks(e,t,n){return ig(e,t,r=>({...r,content:ag(r.content,n)}))}function ag(e,t){const n=e.slice();for(const r of t)if(r.type==="text"){const o=n[n.length-1],s=r.text??"";if(!s)continue;if((o==null?void 0:o.type)==="text"){const i=o,a=lg(i.text??"",s);if(!a)continue;i.text=(i.text??"")+a}else n.push({type:"text",text:s})}else n.push(r);return n}function lg(e,t){if(!t)return"";if(!e)return t;if(t===e)return"";const n=t.indexOf(e);if(n===0)return t.slice(e.length);if(n>0){const o=t.slice(n+e.length);if(o)return o}if(e.endsWith(t)||e.includes(t))return"";const r=Math.min(e.length,t.length);for(let o=r;o>0;o--)if(e.slice(-o)===t.slice(0,o))return t.slice(o);return t}function cg(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return sg(e,r,s)}return e}function ug(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const dg={MODE:"library"};function fg(){var i;const e=typeof globalThis<"u"?globalThis.process:void 0,t=typeof((i=e==null?void 0:e.env)==null?void 0:i.NODE_ENV)=="string"?e.env.NODE_ENV:void 0;if(t)return t==="production";const n=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Ns&&Ns.tagName.toUpperCase()==="SCRIPT"&&Ns.src||new URL("index.umd.js",document.baseURI).href}<"u"?dg:void 0,r=typeof(n==null?void 0:n.MODE)=="string"?n.MODE:void 0,o=typeof(n==null?void 0:n.NODE_ENV)=="string"?n.NODE_ENV:void 0;return(r??o)==="production"}function hg(){return!fg()}function pg({onThreadInfo:e,onMessageEvent:t,onUnhandledEvent:n,onSequenceGap:r}){const o=y.useRef(null),s=y.useCallback(a=>{const c=a.seq;if(c!=null){const u=o.current;if(u!==null){if(c<=u){hg()&&console.debug("[StreamEventCoordinator] drop out-of-order seq",{prev:u,seq:c,type:a.type});return}c>u+1&&(r==null||r({from:u,to:c}))}o.current=c}if(a.type==="thread_info"){e==null||e(a);return}if(ng(a)){t(a);return}n==null||n(a)},[t,r,e,n]),i=y.useCallback(()=>{o.current=null},[]);return{handleEvent:s,reset:i}}function Fl(e={}){const t=y.useMemo(()=>{const j=(e.baseUrl??"/api/chat").replace(/\/+$/,"");return j.endsWith("/chat")?j:`${j}/chat`},[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=y.useState(e.token??null),s=y.useRef(e.headers??{}),[i,a]=y.useState(!1),[c,u]=y.useState(null),[d,f]=y.useState(""),[h,m]=y.useState(null),[w,v]=y.useState(0),[g,x]=y.useState(!1),b=y.useRef(null),S=y.useRef(!0),k=y.useRef(0),C=y.useCallback(_=>{o(_)},[]),T=y.useCallback(()=>{var _;(_=b.current)==null||_.abort(),b.current=null,a(!1),x(!1)},[]),I=y.useCallback(()=>{f(""),m(null),u(null)},[]),N=y.useCallback((_,j,R)=>{b.current&&(b.current.abort(),b.current=null),a(!0),u(null),e.autoAppendAssistant!==!1&&f("");const $=new AbortController;return b.current=$,(async()=>{var O,W,B,q,L,A,D,H;const z=J=>{var Q;try{const ue=JSON.parse(JSON.stringify(J));return(Q=ue==null?void 0:ue.payload)!=null&&Q.files_info&&Array.isArray(ue.payload.files_info)&&(ue.payload.files_info=ue.payload.files_info.map(be=>({...be,data:be!=null&&be.data?`<base64 ${String(be.data).length} chars>`:be==null?void 0:be.data}))),ue}catch{return J}};try{let J={};try{if(r)J={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const X=window.__AUTH_TOKEN__,xe=((O=window.localStorage)==null?void 0:O.getItem("authToken"))||null;let Pe=null;try{const et=(W=window.localStorage)==null?void 0:W.getItem("chat-settings");et&&(Pe=((B=JSON.parse(et))==null?void 0:B.apiKey)||null)}catch{}const _e=X||xe||Pe||null;_e&&(J={Authorization:`Bearer ${_e}`})}}catch{}console.debug("[use-chat] POST",t+n,z(_));const Q=await fetch(t+n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...J,...s.current},body:JSON.stringify(_),signal:$.signal});if(!Q.ok||!Q.body){const V=await Q.text().catch(()=>"");throw console.debug("[use-chat] non-OK response",Q.status,V==null?void 0:V.slice(0,500)),new Error(`stream ${Q.status}${V?": "+V:""}`)}x(!0);const ue=Q.body.getReader(),be=new TextDecoder;let Ie="",K=[],M=k.current,Y=null;const ee=()=>{if(K.length){const V=K.join("");K=[],S.current&&f(X=>X+V)}Y=null},de=()=>{typeof window<"u"&&Y==null&&(Y=requestAnimationFrame(ee))};let ce=Date.now();const ze=setInterval(()=>{var V;if(Date.now()-ce>2e4){const X="Stream idle timeout";u(X),$.abort(),(V=R==null?void 0:R.onError)==null||V.call(R,X)}},5e3),Ye=1024*1024;try{const V=Q.headers.get("X-Thread-Id")||Q.headers.get("x-thread-id"),X=Q.headers.get("X-Thread-Created")||Q.headers.get("x-thread-created"),xe=V??null,Pe=String(X??"").toLowerCase()==="true";for((q=R==null?void 0:R.onOpen)==null||q.call(R,{threadId:xe,created:Pe});;){const{value:_e,done:et}=await ue.read();if(et)break;Ie+=be.decode(_e,{stream:!0}),Ie.length>Ye&&(Ie="",console.warn("Stream buffer reset: exceeded 1MB"));let st;for(;(st=Ie.indexOf(`
36
36
 
37
37
  `))>=0;){const ie=Ie.slice(0,st);Ie=Ie.slice(st+2);const ae=gg(ie);if(!ae)continue;let me;try{me=JSON.parse(ae)}catch{console.debug("[use-chat] malformed SSE:",ae.slice(0,200));continue}const ge=mg(me)?me.data:me;ce=Date.now();const ke=ge.seq;if(ke!==void 0){if(ke<=M){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:ke,lastProcessedSeq:M,type:ge.type});continue}M>0&&ke>M+1&&((L=R==null?void 0:R.onGap)==null||L.call(R,{from:M,to:ke})),M=ke,k.current=ke,v(ke)}if(j==null||j(ge),ge.type==="token"&&e.autoAppendAssistant!==!1)K.push(ge.content),de();else if(ge.type==="message_delta"){const je=ge.delta.filter(Ke=>Ke.type==="text").map(Ke=>Ke.text).join("");je&&e.autoAppendAssistant!==!1&&(K.push(je),de())}else Y!==null&&cancelAnimationFrame(Y),ee(),ge.type==="checkpoint"?m(ge.checkpointId):ge.type==="error"&&u(ge.message)}}ee()}catch(V){if(V.name!=="AbortError"){const X=V.message||String(V);u(X),(A=R==null?void 0:R.onError)==null||A.call(R,X)}}finally{try{await ue.cancel()}catch{}finally{(D=ue.releaseLock)==null||D.call(ue)}Y!==null&&typeof window<"u"&&window.cancelAnimationFrame(Y),clearInterval(ze),a(!1),x(!1),b.current=null}}catch(J){if(J.name!=="AbortError"){const Q=J.message||String(J);u(Q),(H=R==null?void 0:R.onError)==null||H.call(R,Q)}}finally{a(!1),x(!1),b.current=null}})(),{close:()=>$.abort()}},[t,n,r,e.autoAppendAssistant]);return y.useEffect(()=>()=>{var _;S.current=!1,(_=b.current)==null||_.abort()},[]),{isStreaming:i,error:c,assistantText:d,lastCheckpointId:h,lastSeq:w,connected:g,stream:N,stop:T,clear:I,setToken:C}}function mg(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function gg(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
38
38
  `)}const zl=y.createContext(null);function xg({children:e,enableFileAgentRouting:t=!1,fileAgentId:n="invoice_reader",onRegisterThreadCallbacks:r}){const{api:o,baseUrl:s}=so(),i=y.useMemo(()=>{const V=(s??"").replace(/\/+$/,"");return V?V.endsWith("/chat")?V:`${V}/chat`:"/api/chat"},[s]),{currentThreadId:a,setCurrentThreadId:c,isLoadingThread:u}=mr(),d=Xm(),{state:f,dispatch:h,seed:m,prepend:w,pushUser:v,onEvent:g,reset:x}=Ll(),[b,S]=y.useState(!1),[k,C]=y.useState(!1),[T,I]=y.useState(null),[N,_]=y.useState(void 0),[j,R]=y.useState(void 0),$=20,z=y.useRef(a);y.useEffect(()=>{z.current=a},[a]);const O=y.useRef(null),W=y.useRef(!1),B=y.useCallback(()=>{W.current=!0},[]),{isStreaming:q,error:L,stream:A,stop:D,setToken:H}=Fl({baseUrl:i,token:null});y.useEffect(()=>{var xe;const V=o.getAuthToken();H(V);const X=(xe=o.onTokenChange)==null?void 0:xe.call(o,Pe=>{H(Pe)});return()=>{X==null||X()}},[o,H]),y.useEffect(()=>{d(q?{type:"STREAM_START",assistantId:f.assemblingId??void 0}:{type:"STREAM_END"})},[q,f.assemblingId,d]),y.useEffect(()=>{d(L?{type:"STREAM_ERROR",error:L}:{type:"CLEAR_ERROR"})},[L,d]),y.useEffect(()=>{f.lastCheckpointId&&d({type:"UPDATE_CHECKPOINT",checkpointId:f.lastCheckpointId,checkpointNs:f.lastCheckpointNs??void 0})},[f.lastCheckpointId,f.lastCheckpointNs,d]),y.useEffect(()=>{d({type:"UPDATE_ASSEMBLING_ID",assistantId:f.assemblingId})},[f.assemblingId,d]);const J=y.useCallback((V,X)=>{const xe=Array.isArray(V==null?void 0:V.messages)?V.messages:[];X==="replace"?(console.log("[MessagesProvider] Replacing messages, count:",xe.length),m(xe,{checkpointId:(V==null?void 0:V.checkpointId)??null,checkpointNs:(V==null?void 0:V.checkpointNs)??null})):X==="prepend"&&xe.length&&(console.log("[MessagesProvider] Prepending messages, count:",xe.length),w(xe)),I((V==null?void 0:V.nextCursor)??null),S(!!(V!=null&&V.hasMore)),_(Pe=>(V==null?void 0:V.checkpointId)??Pe??void 0),R(Pe=>(V==null?void 0:V.checkpointNs)??Pe??void 0)},[m,w]),Q=y.useCallback(V=>{const X=V.threadId,xe=!!V.created,Pe=!!V.ready;if(a!==X){const _e=!a&&f.messages.length<=1;_e&&(O.current=X),c(X),(Pe||xe||_e)&&B();return}(Pe||xe)&&B()},[a,f.messages.length,c,B]),ue=y.useCallback(({from:V,to:X})=>{const xe=z.current;xe&&console.warn(`[MessagesProvider] Stream sequence gap detected (${V} -> ${X}) for thread ${xe}`)},[]),{handleEvent:be,reset:Ie}=pg({onThreadInfo:Q,onMessageEvent:g,onUnhandledEvent:V=>{console.warn(`[MessagesProvider] Unhandled stream event type: ${V.type}`,V)},onSequenceGap:ue}),K=y.useCallback(async V=>{if(!a)throw new Error("No active thread");if(k||!b)return;const X=T;if(X){C(!0);try{const xe=await o.getMessages({threadId:a,checkpointId:N,checkpointNs:j,limit:(V==null?void 0:V.limit)??$,beforeId:X});J(xe,"prepend")}finally{C(!1)}}},[o,a,N,j,T,b,k,J,$]),M=y.useCallback(()=>{console.log("[MessagesProvider] Clearing messages"),x([]),S(!1),C(!1),I(null),_(void 0),R(void 0)},[x]),Y=y.useCallback((V,X)=>{console.log("[MessagesProvider] Handling thread load for",V),W.current=!1,J(X,"replace")},[J]),ee=y.useCallback(()=>{console.log("[MessagesProvider] Handling thread clear"),W.current=!1,M()},[M]),de=y.useMemo(()=>({onThreadLoaded:Y,onThreadCleared:ee}),[Y,ee]);y.useEffect(()=>{if(r)return r(de),()=>{r({onThreadLoaded:()=>{},onThreadCleared:()=>{}})}},[r,de]);const ce=y.useCallback(async(V,X)=>{var ke;!a&&!(X!=null&&X.payloadExtras)&&console.warn("[MessagesProvider] No thread ID - message will create new thread");const xe=(X==null?void 0:X.attachments)||[],{contentParts:Pe,filesInfo:_e}=await Qm(o,xe),et=[...Pe];V&&V.trim()&&et.push({type:"text",text:V.trim()});const st={id:((ke=crypto.randomUUID)==null?void 0:ke.call(crypto))||`user-${Date.now()}`,role:"user",content:et,createdAt:new Date().toISOString(),checkpointId:(X==null?void 0:X.checkpointId)??f.lastCheckpointId??void 0,checkpointNs:(X==null?void 0:X.checkpointNs)??f.lastCheckpointNs??void 0};v(st);const ie={...st,content:et},ae={...(X==null?void 0:X.payloadExtras)??{}},me=xe&&xe.length>0,ge={...a?{threadId:a}:{},payload:{messages:[ie],files_info:_e,...t&&me&&n?{active_agent:n}:{},...ae},checkpointId:(X==null?void 0:X.checkpointId)??f.lastCheckpointId??void 0,checkpointNs:(X==null?void 0:X.checkpointNs)??f.lastCheckpointNs??void 0,nodeFilter:X==null?void 0:X.nodeFilter,config:X==null?void 0:X.config};Ie(),B(),A(ge,je=>{be(je)},{onError:je=>console.warn("[MessagesProvider] Stream error:",je),onOpen:({threadId:je,created:Ke})=>{if(!a&&je){const qe=f.messages.length<=1;qe&&(O.current=je),c(je),(Ke||qe)&&B()}},onGap:ue})},[a,v,A,be,Ie,ue,f.lastCheckpointId,f.lastCheckpointNs,f.messages.length,o,B,c,t,n]),ze=y.useCallback(async(V,X,xe)=>{const Pe=z.current;if(!Pe)throw new Error("No active thread to handle interrupt");try{console.log(`[MessagesProvider] Handling interrupt ${V}: ${X?"approved":"rejected"}`);const _e=X?xe??!0:!1;await o.resume({threadId:Pe,value:_e}),console.log(`[MessagesProvider] Interrupt ${V} handled successfully`)}catch(_e){throw console.error(`[MessagesProvider] Failed to handle interrupt ${V}:`,_e),_e}},[o]),Ye={messages:f.messages,assemblingId:f.assemblingId,lastUserMessage:null,hasMoreHistory:b,isLoadingHistory:k,send:ce,stop:D,loadOlderMessages:K,clearMessages:M,handleInterrupt:ze};return l.jsx(zl.Provider,{value:Ye,children:e})}function vg(e){return l.jsx(xg,{...e})}function qs(){const e=y.useContext(zl);if(!e)throw new Error("useMessages must be used within MessagesProvider");return e}function io({children:e,apiConfig:t,initialThreadId:n=null,autoLoadInitial:r=!0,disableAutoRestore:o=!1,enableFileAgentRouting:s=!1,fileAgentId:i="invoice_reader",onError:a,onThreadChange:c}){const u=y.useRef({onThreadLoaded:()=>{},onThreadCleared:()=>{}}),d=y.useCallback(m=>{u.current=m},[]),f=y.useCallback((m,w)=>{u.current.onThreadLoaded(m,w)},[]),h=y.useCallback(()=>{u.current.onThreadCleared()},[]);return l.jsx(Km,{apiConfig:t,children:l.jsx(Ym,{children:l.jsx(tg,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,onError:a,onThreadChange:c,onThreadLoaded:f,onThreadCleared:h,children:l.jsx(vg,{enableFileAgentRouting:s,fileAgentId:i,onRegisterThreadCallbacks:d,children:e})})})})}function Z(...e){return yp.twMerge(bp.clsx(e))}const wg=Kr.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Fe=p.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Cn.Slot:"button";return l.jsx(i,{className:Z(wg({variant:t,size:n,className:e})),ref:s,...o})});Fe.displayName="Button";const Bl=p.forwardRef(({className:e,...t},n)=>l.jsx("textarea",{className:Z("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Bl.displayName="Textarea";function bg({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,onSend:i,onCancelEdit:a,onStop:c,className:u="",textareaClassName:d="",allowEmptySend:f=!1}){const[h,m]=y.useState(e),[w,v]=y.useTransition(),g=y.useRef(null);y.useEffect(()=>{m(e??""),g.current&&(g.current.style.height="auto",g.current.style.height=`${g.current.scrollHeight}px`)},[e,t]);const x=y.useCallback(()=>{const N=g.current;N&&(N.style.height="auto",N.style.height=`${N.scrollHeight}px`)},[]);y.useEffect(()=>{x()},[x]);const b=y.useCallback(async N=>{N&&N.preventDefault();const _=(h??"").trim();!_&&!f||v(()=>{try{const j=i(_);j&&typeof j.then=="function"?j.then(()=>{m(""),g.current&&(g.current.style.height="auto")}).catch(()=>{}):(m(""),g.current&&(g.current.style.height="auto"))}catch{}})},[h,i,f]),S=y.useCallback(N=>{m(N.target.value),g.current&&(g.current.style.height="auto",g.current.style.height=`${g.current.scrollHeight}px`)},[]),k=y.useCallback(N=>{N.key==="Enter"&&!N.shiftKey?(N.preventDefault(),b()):N.key==="Escape"&&t&&(N.preventDefault(),a==null||a())},[b,t,a]),I=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${d}`;return l.jsx("form",{onSubmit:N=>void b(N),className:`w-full ${u}`,children:l.jsxs("div",{className:"flex items-end gap-2",children:[l.jsx("div",{className:"flex-1",children:l.jsx(Bl,{ref:g,value:h,onChange:S,onKeyDown:k,placeholder:t?"Edit your message...":n,className:I,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),l.jsx("div",{children:r?l.jsx(Fe,{type:"button",onClick:()=>{c==null||c()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!c,children:l.jsx(te.Square,{size:16})}):l.jsx(Fe,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!h.trim()&&!f||w,children:l.jsx(te.Send,{size:16})})})]})})}const yg=y.memo(bg),ao=0,un=1,Kn=2,Hl=4;function Ul(e){return()=>e}function Sg(e){e()}function Wl(e,t){return n=>e(t(n))}function Vl(e,t){return()=>e(t)}function Cg(e,t){return n=>e(t,n)}function Gs(e){return e!==void 0}function Tg(...e){return()=>{e.map(Sg)}}function qn(){}function lo(e,t){return t(e),e}function Eg(e,t){return t(e)}function Xe(...e){return e}function He(e,t){return e(un,t)}function Ae(e,t){e(ao,t)}function Ys(e){e(Kn)}function nt(e){return e(Hl)}function fe(e,t){return He(e,Cg(t,ao))}function Ft(e,t){const n=e(un,r=>{n(),t(r)});return n}function Kl(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function ql(e,t){return e===t}function Je(e=ql){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function ye(e){return t=>n=>{e(n)&&t(n)}}function re(e){return t=>Wl(t,e)}function Kt(e){return t=>()=>{t(e)}}function F(e,...t){const n=kg(...t);return(r,o)=>{switch(r){case Kn:Ys(e);return;case un:return He(e,n(o))}}}function qt(e,t){return n=>r=>{n(t=e(t,r))}}function In(e){return t=>n=>{e>0?e--:t(n)}}function on(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Re(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);He(s,c=>{const u=n;n=n|a,t[i]=c,u!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function kg(...e){return t=>e.reduceRight(Eg,t)}function Ig(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case un:return s?n===s?void 0:(r(),n=s,t=He(e,s),t):(r(),qn);case Kn:r(),n=null;return}}}function G(e){let t=e;const n=De();return(r,o)=>{switch(r){case ao:t=o;break;case un:{o(t);break}case Hl:return t}return n(r,o)}}function ft(e,t){return lo(G(t),n=>fe(e,n))}function De(){const e=[];return(t,n)=>{switch(t){case ao:e.slice().forEach(r=>{r(n)});return;case Kn:e.splice(0,e.length);return;case un:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function Tt(e){return lo(De(),t=>fe(e,t))}function Be(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:Ng(),singleton:n}}const Ng=()=>Symbol();function Ag(e){const t=new Map,n=({constructor:r,dependencies:o,id:s,singleton:i})=>{if(i&&t.has(s))return t.get(s);const a=r(o.map(c=>n(c)));return i&&t.set(s,a),a};return n(e)}function ot(...e){const t=De(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);He(s,c=>{n[i]=c,r=r|a,r===o&&Ae(t,n)})}),function(s,i){switch(s){case Kn:{Ys(t);return}case un:return r===o&&i(n),He(t,i)}}}function we(e,t=ql){return F(e,Je(t))}function Xs(...e){return function(t,n){switch(t){case Kn:return;case un:return Tg(...e.map(r=>He(r,n)))}}}var bt=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(bt||{});const _g={0:"debug",3:"error",1:"log",2:"warn"},jg=()=>typeof globalThis>"u"?window:globalThis,dn=Be(()=>{const e=G(3);return{log:G((t,n,r=1)=>{var o;const s=(o=jg().VIRTUOSO_LOG_LEVEL)!=null?o:nt(e);r>=s&&console[_g[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function Nn(e,t,n){return Js(e,t,n).callbackRef}function Js(e,t,n){const r=y.useRef(null);let o=i=>{};const s=y.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const a=()=>{const c=i[0].target;c.offsetParent!==null&&e(c)};n?a():requestAnimationFrame(a)}):null,[e,n]);return o=i=>{i&&t?(s==null||s.observe(i),r.current=i):(r.current&&(s==null||s.unobserve(r.current)),r.current=null)},{callbackRef:o,ref:r}}function Rg(e,t,n,r,o,s,i,a,c){const u=y.useCallback(d=>{const f=Pg(d.children,t,a?"offsetWidth":"offsetHeight",o);let h=d.parentElement;for(;!h.dataset.virtuosoScroller;)h=h.parentElement;const m=h.lastElementChild.dataset.viewportType==="window";let w;m&&(w=h.ownerDocument.defaultView);const v=i?a?i.scrollLeft:i.scrollTop:m?a?w.scrollX||w.document.documentElement.scrollLeft:w.scrollY||w.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,g=i?a?i.scrollWidth:i.scrollHeight:m?a?w.document.documentElement.scrollWidth:w.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,x=i?a?i.offsetWidth:i.offsetHeight:m?a?w.innerWidth:w.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:g,scrollTop:Math.max(v,0),viewportHeight:x}),s==null||s(a?Gl("column-gap",getComputedStyle(d).columnGap,o):Gl("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return Js(u,n,c)}function Pg(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const c=parseInt(a.dataset.index),u=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},bt.ERROR),d===u)continue;const f=s[s.length-1];s.length===0||f.size!==d||f.endIndex!==c-1?s.push({endIndex:c,size:d,startIndex:c}):s[s.length-1].endIndex++}return s}function Gl(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,bt.WARN),t==="normal"?0:parseInt(t??"0",10)}function Yl(e,t,n){const r=y.useRef(null),o=y.useCallback(c=>{if(!(c!=null&&c.offsetParent))return;const u=c.getBoundingClientRect(),d=u.width;let f,h;if(t){const m=t.getBoundingClientRect(),w=u.top-m.top;h=m.height-Math.max(0,w),f=w+t.scrollTop}else{const m=i.current.ownerDocument.defaultView;h=m.innerHeight-Math.max(0,u.top),f=u.top+m.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=Js(o,!0,n),a=y.useCallback(()=>{o(i.current)},[o,i]);return y.useEffect(()=>{var c;if(t){t.addEventListener("scroll",a);const u=new ResizeObserver(()=>{requestAnimationFrame(a)});return u.observe(t),()=>{t.removeEventListener("scroll",a),u.unobserve(t)}}else{const u=(c=i.current)==null?void 0:c.ownerDocument.defaultView;return u==null||u.addEventListener("scroll",a),u==null||u.addEventListener("resize",a),()=>{u==null||u.removeEventListener("scroll",a),u==null||u.removeEventListener("resize",a)}}},[a,t,i]),s}const mt=Be(()=>{const e=De(),t=De(),n=G(0),r=De(),o=G(0),s=De(),i=De(),a=G(0),c=G(0),u=G(0),d=G(0),f=De(),h=De(),m=G(!1),w=G(!1),v=G(!1);return fe(F(e,re(({scrollTop:g})=>g)),t),fe(F(e,re(({scrollHeight:g})=>g)),i),fe(t,o),{deviation:n,fixedFooterHeight:u,fixedHeaderHeight:c,footerHeight:d,headerHeight:a,horizontalDirection:w,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:m,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:v,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),gr={lvl:0};function Xl(e,t){const n=e.length;if(n===0)return[];let{index:r,value:o}=t(e[0]);const s=[];for(let i=1;i<n;i++){const{index:a,value:c}=t(e[i]);s.push({end:a-1,start:r,value:o}),r=a,o=c}return s.push({end:1/0,start:r,value:o}),s}function We(e){return e===gr}function xr(e,t){if(!We(e))return t===e.k?e.v:t<e.k?xr(e.l,t):xr(e.r,t)}function zt(e,t,n="k"){if(We(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=zt(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return zt(e.l,t,n)}function Et(e,t,n){return We(e)?Ql(t,n,1):t===e.k?at(e,{k:t,v:n}):t<e.k?ec(at(e,{l:Et(e.l,t,n)})):ec(at(e,{r:Et(e.r,t,n)}))}function Gn(){return gr}function co(e,t,n){if(We(e))return[];const r=zt(e,t)[0];return Og(Qs(e,r,n))}function Zs(e,t){if(We(e))return gr;const{k:n,l:r,r:o}=e;if(t===n){if(We(r))return o;if(We(o))return r;{const[s,i]=Zl(r);return uo(at(e,{k:s,l:Jl(r),v:i}))}}else return t<n?uo(at(e,{l:Zs(r,t)})):uo(at(e,{r:Zs(o,t)}))}function An(e){return We(e)?[]:[...An(e.l),{k:e.k,v:e.v},...An(e.r)]}function Qs(e,t,n){if(We(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(Qs(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(Qs(s,t,n))),a}function uo(e){const{l:t,lvl:n,r}=e;if(r.lvl>=n-1&&t.lvl>=n-1)return e;if(n>r.lvl+1){if(ei(t))return tc(at(e,{lvl:n-1}));if(!We(t)&&!We(t.r))return at(t.r,{l:at(t,{r:t.r.l}),lvl:n,r:at(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(ei(e))return ti(at(e,{lvl:n-1}));if(!We(r)&&!We(r.l)){const o=r.l,s=ei(o)?r.lvl-1:r.lvl;return at(o,{l:at(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:ti(at(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function at(e,t){return Ql(t.k!==void 0?t.k:e.k,t.v!==void 0?t.v:e.v,t.lvl!==void 0?t.lvl:e.lvl,t.l!==void 0?t.l:e.l,t.r!==void 0?t.r:e.r)}function Jl(e){return We(e.r)?e.l:uo(at(e,{r:Jl(e.r)}))}function ei(e){return We(e)||e.lvl>e.r.lvl}function Zl(e){return We(e.r)?[e.k,e.v]:Zl(e.r)}function Ql(e,t,n,r=gr,o=gr){return{k:e,l:r,lvl:n,r:o,v:t}}function ec(e){return ti(tc(e))}function tc(e){const{l:t}=e;return!We(t)&&t.lvl===e.lvl?at(t,{r:at(e,{l:t.r})}):e}function ti(e){const{lvl:t,r:n}=e;return!We(n)&&!We(n.r)&&n.lvl===t&&n.r.lvl===t?at(n,{l:at(e,{r:n.l}),lvl:t+1}):e}function Og(e){return Xl(e,({k:t,v:n})=>({index:t,value:n}))}function nc(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function vr(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const ni=Be(()=>({recalcInProgress:G(!1)}),[],{singleton:!0});function rc(e,t,n){return e[fo(e,t,n)]}function fo(e,t,n,r=0){let o=e.length-1;for(;r<=o;){const s=Math.floor((r+o)/2),i=e[s],a=n(i,t);if(a===0)return s;if(a===-1){if(o-r<2)return s-1;o=s-1}else{if(o===r)return s;r=s+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function Mg(e,t,n,r){const o=fo(e,t,r),s=fo(e,n,r,o);return e.slice(o,s+1)}function fn(e,t){return Math.round(e.getBoundingClientRect()[t])}function ho(e){return!We(e.groupOffsetTree)}function ri({index:e},t){return t===e?0:t<e?-1:1}function Dg(){return{groupIndices:[],groupOffsetTree:Gn(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:Gn()}}function Lg(e,t){let n=We(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),We(e)){e=Et(e,0,s);continue}const a=co(e,i-1,o+1);if(a.some(Wg(r)))continue;let c=!1,u=!1;for(const{end:d,start:f,value:h}of a)c?(o>=f||s===h)&&(e=Zs(e,f)):(u=h!==s,c=!0),d>o&&o>=f&&h!==s&&(e=Et(e,o+1,h));u&&(e=Et(e,i,s))}return[e,n]}function $g(e){return typeof e.groupIndex<"u"}function Fg({offset:e},t){return t===e?0:t<e?-1:1}function wr(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=rc(t,e,ri),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function oc(e,t){if(!ho(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function sc(e,t,n){if($g(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=oc(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function zg(e,t,n,r=0){return r>0&&(t=Math.max(t,rc(e,r,ri).offset)),Xl(Mg(e,t,n,Fg),Ug)}function Bg(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,bt.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&We(s)&&t.length===2){const h=t[0].size,m=t[1].size;i=n.reduce((w,v)=>Et(Et(w,v,h),v+1,m),i)}else[i,a]=Lg(i,t);if(i===s)return e;const{lastIndex:c,lastOffset:u,lastSize:d,offsetTree:f}=oi(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,m)=>Et(h,m,wr(m,f,o)),Gn()),lastIndex:c,lastOffset:u,lastSize:d,offsetTree:f,sizeTree:i}}function Hg(e){return An(e).map(({k:t,v:n},r,o)=>{const s=o[r+1];return{endIndex:s?s.k-1:1/0,size:n,startIndex:t}})}function ic(e,t){let n=0,r=0;for(;n<e;)n+=t[r+1]-t[r]-1,r++;return r-(n===e?0:1)}function oi(e,t,n,r){let o=e,s=0,i=0,a=0,c=0;if(t!==0){c=fo(o,t-1,ri),a=o[c].offset;const u=zt(n,t-1);s=u[0],i=u[1],o.length&&o[c].size===zt(n,t)[1]&&(c-=1),o=o.slice(0,c+1)}else o=[];for(const{start:u,value:d}of co(n,t,1/0)){const f=u-s,h=f*i+a+f*r;o.push({index:u,offset:h,size:d}),s=u,a=h,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function Ug(e){return{index:e.index,value:e}}function Wg(e){const{endIndex:t,size:n,startIndex:r}=e;return o=>o.start===r&&(o.end===t||o.end===1/0)&&o.value===n}const Vg={offsetHeight:"height",offsetWidth:"width"},Gt=Be(([{log:e},{recalcInProgress:t}])=>{const n=De(),r=De(),o=ft(r,0),s=De(),i=De(),a=G(0),c=G([]),u=G(void 0),d=G(void 0),f=G((C,T)=>fn(C,Vg[T])),h=G(void 0),m=G(0),w=Dg(),v=ft(F(n,Re(c,e,m),qt(Bg,w),Je()),w),g=ft(F(c,Je(),qt((C,T)=>({current:T,prev:C.current}),{current:[],prev:[]}),re(({prev:C})=>C)),[]);fe(F(c,ye(C=>C.length>0),Re(v,m),re(([C,T,I])=>{const N=C.reduce((_,j,R)=>Et(_,j,wr(j,T.offsetTree,I)||R),Gn());return{...T,groupIndices:C,groupOffsetTree:N}})),v),fe(F(r,Re(v),ye(([C,{lastIndex:T}])=>C<T),re(([C,{lastIndex:T,lastSize:I}])=>[{endIndex:T,size:I,startIndex:C}])),n),fe(u,d);const x=ft(F(u,re(C=>C===void 0)),!0);fe(F(d,ye(C=>C!==void 0&&We(nt(v).sizeTree)),re(C=>[{endIndex:0,size:C,startIndex:0}])),n);const b=Tt(F(n,Re(v),qt(({sizes:C},[T,I])=>({changed:I!==C,sizes:I}),{changed:!1,sizes:w}),re(C=>C.changed)));He(F(a,qt((C,T)=>({diff:C.prev-T,prev:T}),{diff:0,prev:0}),re(C=>C.diff)),C=>{const{groupIndices:T}=nt(v);if(C>0)Ae(t,!0),Ae(s,C+ic(C,T));else if(C<0){const I=nt(g);I.length>0&&(C-=ic(-C,I)),Ae(i,C)}}),He(F(a,Re(e)),([C,T])=>{C<0&&T("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:a},bt.ERROR)});const S=Tt(s);fe(F(s,Re(v),re(([C,T])=>{const I=T.groupIndices.length>0,N=[],_=T.lastSize;if(I){const j=xr(T.sizeTree,0);let R=0,$=0;for(;R<C;){const O=T.groupIndices[$],W=T.groupIndices.length===$+1?1/0:T.groupIndices[$+1]-O-1;N.push({endIndex:O,size:j,startIndex:O}),N.push({endIndex:O+1+W-1,size:_,startIndex:O+1}),$++,R+=W+1}const z=An(T.sizeTree);return R!==C&&z.shift(),z.reduce((O,{k:W,v:B})=>{let q=O.ranges;return O.prevSize!==0&&(q=[...O.ranges,{endIndex:W+C-1,size:O.prevSize,startIndex:O.prevIndex}]),{prevIndex:W+C,prevSize:B,ranges:q}},{prevIndex:C,prevSize:0,ranges:N}).ranges}return An(T.sizeTree).reduce((j,{k:R,v:$})=>({prevIndex:R+C,prevSize:$,ranges:[...j.ranges,{endIndex:R+C-1,size:j.prevSize,startIndex:j.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const k=Tt(F(i,Re(v,m),re(([C,{offsetTree:T},I])=>{const N=-C;return wr(N,T,I)})));return fe(F(i,Re(v,m),re(([C,T,I])=>{if(T.groupIndices.length>0){if(We(T.sizeTree))return T;let N=Gn();const _=nt(g);let j=0,R=0,$=0;for(;j<-C;){$=_[R];const z=_[R+1]-$-1;R++,j+=z+1}if(N=An(T.sizeTree).reduce((z,{k:O,v:W})=>Et(z,Math.max(0,O+C),W),N),j!==-C){const z=xr(T.sizeTree,$);N=Et(N,0,z);const O=zt(T.sizeTree,-C+1)[1];N=Et(N,1,O)}return{...T,sizeTree:N,...oi(T.offsetTree,0,N,I)}}else{const N=An(T.sizeTree).reduce((_,{k:j,v:R})=>Et(_,Math.max(0,j+C),R),Gn());return{...T,sizeTree:N,...oi(T.offsetTree,0,N,I)}}})),v),{beforeUnshiftWith:S,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:u,gap:m,groupIndices:c,itemSize:f,listRefresh:b,shiftWith:i,shiftWithOffset:k,sizeRanges:n,sizes:v,statefulTotalCount:o,totalCount:r,trackItemSizes:x,unshiftWith:s}},Xe(dn,ni),{singleton:!0});function Kg(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const ac=Be(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=De(),i=De(),a=Tt(F(s,re(Kg)));return fe(F(a,re(c=>c.totalCount)),n),fe(F(a,re(c=>c.groupIndices)),e),fe(F(ot(o,t,r),ye(([c,u])=>ho(u)),re(([c,u,d])=>zt(u.groupOffsetTree,Math.max(c-d,0),"v")[0]),Je(),re(c=>[c])),i),{groupCounts:s,topItemsIndexes:i}},Xe(Gt,mt)),hn=Be(([{log:e}])=>{const t=G(!1),n=Tt(F(t,ye(r=>r),Je()));return He(t,r=>{r&&nt(e)("props updated",{},bt.DEBUG)}),{didMount:n,propsReady:t}},Xe(dn),{singleton:!0}),qg=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function lc(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!qg)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const br=Be(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:c,scrollTo:u,smoothScrollTargetReached:d,viewportHeight:f},{log:h}])=>{const m=De(),w=De(),v=G(0);let g=null,x=null,b=null;function S(){g&&(g(),g=null),b&&(b(),b=null),x&&(clearTimeout(x),x=null),Ae(c,!1)}return fe(F(m,Re(n,f,r,v,a,i,h),Re(e,s,o),re(([[k,C,T,I,N,_,j,R],$,z,O])=>{const W=lc(k),{align:B,behavior:q,offset:L}=W,A=I-1,D=sc(W,C,A);let H=wr(D,C.offsetTree,$)+_;B==="end"?(H+=z+zt(C.sizeTree,D)[1]-T+O,D===A&&(H+=j)):B==="center"?H+=(z+zt(C.sizeTree,D)[1]-T+O)/2:H-=N,L&&(H+=L);const J=Q=>{S(),Q?(R("retrying to scroll to",{location:k},bt.DEBUG),Ae(m,k)):(Ae(w,!0),R("list did not change, scroll successful",{},bt.DEBUG))};if(S(),q==="smooth"){let Q=!1;b=He(t,ue=>{Q=Q||ue}),g=Ft(d,()=>{J(Q)})}else g=Ft(F(t,Gg(150)),J);return x=setTimeout(()=>{S()},1200),Ae(c,!0),R("scrolling from index to",{behavior:q,index:D,top:H},bt.DEBUG),{behavior:q,top:H}})),u),{scrollTargetReached:w,scrollToIndex:m,topListHeight:v}},Xe(Gt,mt,dn),{singleton:!0});function Gg(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function si(e,t){e==0?t():requestAnimationFrame(()=>{si(e-1,t)})}function ii(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const yr=Be(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=G(!0),c=G(0),u=G(!0);return fe(F(i,Re(c),ye(([d,f])=>!!f),Kt(!1)),a),fe(F(i,Re(c),ye(([d,f])=>!!f),Kt(!1)),u),He(F(ot(t,i),Re(a,n,e,u),ye(([[,d],f,{sizeTree:h},m,w])=>d&&(!We(h)||Gs(m))&&!f&&!w),Re(c)),([,d])=>{Ft(o,()=>{Ae(u,!0)}),si(4,()=>{Ft(r,()=>{Ae(a,!0)}),Ae(s,d)})}),{initialItemFinalLocationReached:u,initialTopMostItemIndex:c,scrolledToInitialItem:a}},Xe(Gt,mt,br,hn),{singleton:!0});function cc(e,t){return Math.abs(e-t)<1.01}const Sr="up",Cr="down",Yg="none",Xg={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},Jg=0,Tr=Be(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=G(!1),a=G(!0),c=De(),u=De(),d=G(4),f=G(Jg),h=ft(F(Xs(F(we(o),In(1),Kt(!0)),F(we(o),In(1),Kt(!1),Kl(100))),Je()),!1),m=ft(F(Xs(F(n,Kt(!0)),F(n,Kt(!1),Kl(200))),Je()),!1);fe(F(ot(we(o),we(f)),re(([b,S])=>b<=S),Je()),a),fe(F(a,on(50)),u);const w=Tt(F(ot(r,we(s),we(t),we(e),we(d)),qt((b,[{scrollHeight:S,scrollTop:k},C,T,I,N])=>{const _=k+C-S>-N,j={scrollHeight:S,scrollTop:k,viewportHeight:C};if(_){let $,z;return k>b.state.scrollTop?($="SCROLLED_DOWN",z=b.state.scrollTop-k):($="SIZE_DECREASED",z=b.state.scrollTop-k||b.scrollTopDelta),{atBottom:!0,atBottomBecause:$,scrollTopDelta:z,state:j}}let R;return j.scrollHeight>b.state.scrollHeight?R="SIZE_INCREASED":C<b.state.viewportHeight?R="VIEWPORT_HEIGHT_DECREASING":k<b.state.scrollTop?R="SCROLLING_UPWARDS":R="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:R,state:j}},Xg),Je((b,S)=>b&&b.atBottom===S.atBottom))),v=ft(F(r,qt((b,{scrollHeight:S,scrollTop:k,viewportHeight:C})=>{if(cc(b.scrollHeight,S))return{changed:!1,jump:0,scrollHeight:S,scrollTop:k};{const T=S-(k+C)<1;return b.scrollTop!==k&&T?{changed:!0,jump:b.scrollTop-k,scrollHeight:S,scrollTop:k}:{changed:!0,jump:0,scrollHeight:S,scrollTop:k}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),ye(b=>b.changed),re(b=>b.jump)),0);fe(F(w,re(b=>b.atBottom)),i),fe(F(i,on(50)),c);const g=G(Cr);fe(F(r,re(({scrollTop:b})=>b),Je(),qt((b,S)=>nt(m)?{direction:b.direction,prevScrollTop:S}:{direction:S<b.prevScrollTop?Sr:Cr,prevScrollTop:S},{direction:Cr,prevScrollTop:0}),re(b=>b.direction)),g),fe(F(r,on(50),Kt(Yg)),g);const x=G(0);return fe(F(h,ye(b=>!b),Kt(0)),x),fe(F(o,on(100),Re(h),ye(([b,S])=>!!S),qt(([b,S],[k])=>[S,k],[0,0]),re(([b,S])=>S-b)),x),{atBottomState:w,atBottomStateChange:c,atBottomThreshold:d,atTopStateChange:u,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:v,scrollDirection:g,scrollVelocity:x}},Xe(mt)),po="top",mo="bottom",uc="none";function dc(e,t,n){return typeof e=="number"?n===Sr&&t===po||n===Cr&&t===mo?e:0:n===Sr?t===po?e.main:e.reverse:t===mo?e.main:e.reverse}function fc(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const ai=Be(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=De(),i=G(0),a=G(0),c=G(0),u=ft(F(ot(we(r),we(o),we(n),we(s,vr),we(c),we(i),we(t),we(e),we(a)),re(([d,f,h,[m,w],v,g,x,b,S])=>{const k=d-b,C=g+x,T=Math.max(h-k,0);let I=uc;const N=fc(S,po),_=fc(S,mo);return m-=b,m+=h+x,w+=h+x,w-=b,m>d+C-N&&(I=Sr),w<d-T+f+_&&(I=Cr),I!==uc?[Math.max(k-h-dc(v,po,I)-N,0),k-T-x+f+dc(v,mo,I)+_]:null}),ye(d=>d!=null),Je(vr)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:c,topListHeight:i,visibleRange:u}},Xe(mt),{singleton:!0});function Zg(e,t,n){if(ho(t)){const r=oc(e,t);return[{index:zt(t.groupOffsetTree,r)[0],offset:0,size:0},{data:n==null?void 0:n[0],index:r,offset:0,size:0}]}return[{data:n==null?void 0:n[0],index:e,offset:0,size:0}]}const li={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function go(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:c}=o;let u=0,d=0;if(e.length>0){u=e[0].offset;const v=e[e.length-1];d=v.offset+v.size}const f=n-i,h=a+f*c+(f-1)*r,m=u,w=h-d;return{bottom:d,firstItemIndex:s,items:pc(e,o,s),offsetBottom:w,offsetTop:u,top:m,topItems:pc(t,o,s),topListHeight:t.reduce((v,g)=>g.size+v,0),totalCount:n}}function hc(e,t,n,r,o,s){let i=0;if(n.groupIndices.length>0)for(const d of n.groupIndices){if(d-i>=e)break;i++}const a=e+i,c=ii(t,a),u=Array.from({length:a}).map((d,f)=>({data:s[f+c],index:f+c,offset:0,size:0}));return go(u,[],a,o,n,r)}function pc(e,t,n){if(e.length===0)return[];if(!ho(t))return e.map(u=>({...u,index:u.index+n,originalIndex:u.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=co(t.groupOffsetTree,r,o);let a,c=0;for(const u of e){(!a||a.end<u.index)&&(a=i.shift(),c=t.groupIndices.indexOf(a.start));let d;u.index===a.start?d={index:c,type:"group"}:d={groupIndex:c,index:u.index-(c+1)+n},s.push({...d,data:u.data,offset:u.offset,originalIndex:u.index,size:u.size})}return s}const _n=Be(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:c},{initialTopMostItemIndex:u,scrolledToInitialItem:d},{topListHeight:f},h,{didMount:m},{recalcInProgress:w}])=>{const v=G([]),g=G(0),x=De();fe(s.topItemsIndexes,v);const b=ft(F(ot(m,w,we(c,vr),we(o),we(r),we(u),d,we(v),we(t),we(n),e),ye(([T,I,,N,,,,,,,_])=>{const j=_&&_.length!==N;return T&&!I&&!j}),re(([,,[T,I],N,_,j,R,$,z,O,W])=>{const B=_,{offsetTree:q,sizeTree:L}=B,A=nt(g);if(N===0)return{...li,totalCount:N};if(T===0&&I===0)return A===0?{...li,totalCount:N}:hc(A,j,_,z,O,W||[]);if(We(L))return A>0?null:go(Zg(ii(j,N),B,W),[],N,O,B,z);const D=[];if($.length>0){const be=$[0],Ie=$[$.length-1];let K=0;for(const M of co(L,be,Ie)){const Y=M.value,ee=Math.max(M.start,be),de=Math.min(M.end,Ie);for(let ce=ee;ce<=de;ce++)D.push({data:W==null?void 0:W[ce],index:ce,offset:K,size:Y}),K+=Y}}if(!R)return go([],D,N,O,B,z);const H=$.length>0?$[$.length-1]+1:0,J=zg(q,T,I,H);if(J.length===0)return null;const Q=N-1,ue=lo([],be=>{for(const Ie of J){const K=Ie.value;let M=K.offset,Y=Ie.start;const ee=K.size;if(K.offset<T){Y+=Math.floor((T-K.offset+O)/(ee+O));const ce=Y-Ie.start;M+=ce*ee+ce*O}Y<H&&(M+=(H-Y)*ee,Y=H);const de=Math.min(Ie.end,Q);for(let ce=Y;ce<=de&&!(M>=I);ce++)be.push({data:W==null?void 0:W[ce],index:ce,offset:M,size:ee}),M+=ee+O}});return go(ue,D,N,O,B,z)}),ye(T=>T!==null),Je()),li);fe(F(e,ye(Gs),re(T=>T==null?void 0:T.length)),o),fe(F(b,re(T=>T.topListHeight)),f),fe(f,a),fe(F(b,re(T=>[T.top,T.bottom])),i),fe(F(b,re(T=>T.items)),x);const S=Tt(F(b,ye(({items:T})=>T.length>0),Re(o,e),ye(([{items:T},I])=>T[T.length-1].originalIndex===I-1),re(([,T,I])=>[T-1,I]),Je(vr),re(([T])=>T))),k=Tt(F(b,on(200),ye(({items:T,topItems:I})=>T.length>0&&T[0].originalIndex===I.length),re(({items:T})=>T[0].index),Je())),C=Tt(F(b,ye(({items:T})=>T.length>0),re(({items:T})=>{let I=0,N=T.length-1;for(;T[I].type==="group"&&I<N;)I++;for(;T[N].type==="group"&&N>I;)N--;return{endIndex:T[N].index,startIndex:T[I].index}}),Je(nc)));return{endReached:S,initialItemCount:g,itemsRendered:x,listState:b,rangeChanged:C,startReached:k,topItemsIndexes:v,...h}},Xe(Gt,ac,ai,yr,br,Tr,hn,ni),{singleton:!0}),mc=Be(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=De(),i=ft(F(ot(n,e,r,t,o),re(([a,c,u,d,f])=>a+c+u+d+f.offsetBottom+f.bottom)),0);return fe(we(i),s),{totalListHeight:i,totalListHeightChanged:s}},Xe(mt,_n),{singleton:!0}),Qg=Be(([{viewportHeight:e},{totalListHeight:t}])=>{const n=G(!1),r=ft(F(ot(n,e,t),ye(([o])=>o),re(([,o,s])=>Math.max(0,o-s)),on(0),Je()),0);return{alignToBottom:n,paddingTopAddition:r}},Xe(mt,mc),{singleton:!0}),gc=Be(()=>({context:G(null)})),ex=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:r,...o},viewportBottom:s,viewportTop:i})=>t<i?{...o,align:n??"start",behavior:r}:e>s?{...o,align:n??"end",behavior:r}:null,xc=Be(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:c},{scrollToIndex:u}])=>{const d=De();return fe(F(d,Re(t,c,n,s,o,r,a),Re(e),re(([[f,h,m,w,v,g,x,b],S])=>{const{align:k,behavior:C,calculateViewLocation:T=ex,done:I,...N}=f,_=sc(f,h,w-1),j=wr(_,h.offsetTree,S)+v+g,R=j+zt(h.sizeTree,_)[1],$=b+g,z=b+m-x,O=T({itemBottom:R,itemTop:j,locationParams:{align:k,behavior:C,...N},viewportBottom:z,viewportTop:$});return O?I&&Ft(F(i,ye(W=>!W),In(nt(i)?1:2)),I):I&&I(),O}),ye(f=>f!==null)),u),{scrollIntoView:d}},Xe(Gt,mt,br,_n,dn),{singleton:!0});function vc(e){return e?e==="smooth"?"smooth":"auto":!1}const tx=(e,t)=>typeof e=="function"?vc(e(t)):t&&vc(e),nx=Be(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:c,propsReady:u},{log:d},{scrollingInProgress:f},{context:h},{scrollIntoView:m}])=>{const w=G(!1),v=De();let g=null;function x(C){Ae(i,{align:"end",behavior:C,index:"LAST"})}He(F(ot(F(we(t),In(1)),c),Re(we(w),s,a,f),re(([[C,T],I,N,_,j])=>{let R=T&&_,$="auto";return R&&($=tx(I,N||j),R=R&&!!$),{followOutputBehavior:$,shouldFollow:R,totalCount:C}}),ye(({shouldFollow:C})=>C)),({followOutputBehavior:C,totalCount:T})=>{g&&(g(),g=null),nt(n)?requestAnimationFrame(()=>{nt(d)("following output to ",{totalCount:T},bt.DEBUG),x(C)}):g=Ft(e,()=>{nt(d)("following output to ",{totalCount:T},bt.DEBUG),x(C),g=null})});function b(C){const T=Ft(o,I=>{C&&!I.atBottom&&I.notAtBottomBecause==="SIZE_INCREASED"&&!g&&(nt(d)("scrolling to bottom due to increased size",{},bt.DEBUG),x("auto"))});setTimeout(T,100)}He(F(ot(we(w),t,u),ye(([C,,T])=>C&&T),qt(({value:C},[,T])=>({refreshed:C===T,value:T}),{refreshed:!1,value:0}),ye(({refreshed:C})=>C),Re(w,t)),([,C])=>{nt(a)&&b(C!==!1)}),He(v,()=>{b(nt(w)!==!1)}),He(ot(we(w),o),([C,T])=>{C&&!T.atBottom&&T.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&x("auto")});const S=G(null),k=De();return fe(Xs(F(we(r),re(C=>{var T;return(T=C==null?void 0:C.length)!=null?T:0})),F(we(t))),k),He(F(ot(F(k,In(1)),c),Re(we(S),a,f,h),re(([[C,T],I,N,_,j])=>T&&N&&(I==null?void 0:I({context:j,totalCount:C,scrollingInProgress:_}))),ye(C=>!!C),on(0)),C=>{g&&(g(),g=null),nt(n)?requestAnimationFrame(()=>{nt(d)("scrolling into view",{}),Ae(m,C)}):g=Ft(e,()=>{nt(d)("scrolling into view",{}),Ae(m,C),g=null})}),{autoscrollToBottom:v,followOutput:w,scrollIntoViewOnChange:S}},Xe(Gt,Tr,br,yr,hn,dn,mt,gc,xc)),rx=Be(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(fe(F(a,Re(s),ye(([,c])=>c!==0),Re(o,r,t,n,e),re(([[,c],u,d,f,h,m=[]])=>hc(c,u,d,f,h,m))),i),{}),Xe(Gt,yr,_n,hn),{singleton:!0}),ox=Be(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=G(0);return He(F(e,Re(r),ye(([,o])=>o!==0),re(([,o])=>({top:o}))),o=>{Ft(F(n,In(1),ye(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{Ae(t,o)})})}),{initialScrollTop:r}},Xe(hn,mt,_n),{singleton:!0}),wc=Be(([{scrollVelocity:e}])=>{const t=G(!1),n=De(),r=G(!1);return fe(F(e,Re(r,t,n),ye(([o,s])=>!!s),re(([o,s,i,a])=>{const{enter:c,exit:u}=s;if(i){if(u(o,a))return!1}else if(c(o,a))return!0;return i}),Je()),t),He(F(ot(t,e,n),Re(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},Xe(Tr),{singleton:!0}),ci=Be(([{scrollContainerState:e,scrollTo:t}])=>{const n=De(),r=De(),o=De(),s=G(!1),i=G(void 0);return fe(F(ot(n,r),re(([{scrollHeight:a,scrollTop:c,viewportHeight:u},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,c-d),viewportHeight:u}))),e),fe(F(t,Re(r),re(([a,{offsetTop:c}])=>({...a,top:a.top+c}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},Xe(mt)),sx=Be(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:c}])=>{const u=De(),d=G(void 0),f=G(null),h=G(null);return fe(a,f),fe(c,h),He(F(u,Re(t,r,i,f,h,n)),([m,w,v,g,x,b,S])=>{const k=Hg(w.sizeTree);g&&x!==null&&b!==null&&(v=x.scrollTop-b.offsetTop),v-=S,m({ranges:k,scrollTop:v})}),fe(F(d,ye(Gs),re(ix)),o),fe(F(s,Re(d),ye(([,m])=>m!==void 0),Je(),re(([,m])=>m.ranges)),e),{getState:u,restoreStateFrom:d}},Xe(Gt,mt,yr,hn,ci));function ix(e){return{align:"start",index:0,offset:e.scrollTop}}const ax=Be(([{topItemsIndexes:e}])=>{const t=G(0);return fe(F(t,ye(n=>n>=0),re(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},Xe(_n));function bc(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const lx=bc(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),cx=Be(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:c},{beforeUnshiftWith:u,gap:d,shiftWithOffset:f,sizes:h},{log:m},{recalcInProgress:w}])=>{const v=Tt(F(c,Re(i),qt(([,x,b,S],[{bottom:k,items:C,offsetBottom:T,totalCount:I},N])=>{const _=k+T;let j=0;return b===I&&x.length>0&&C.length>0&&(C[0].originalIndex===0&&x[0].originalIndex===0||(j=_-S,j!==0&&(j+=N))),[j,C,I,_]},[0,[],0,0]),ye(([x])=>x!==0),Re(r,a,n,o,m,w),ye(([,x,b,S,,,k])=>!k&&!S&&x!==0&&b===Sr),re(([[x],,,,,b])=>(b("Upward scrolling compensation",{amount:x},bt.DEBUG),x))));function g(x){x>0?(Ae(t,{behavior:"auto",top:-x}),Ae(e,0)):(Ae(e,0),Ae(t,{behavior:"auto",top:-x}))}return He(F(v,Re(e,s)),([x,b,S])=>{S&&lx()?Ae(e,b-x):g(-x)}),He(F(ot(ft(s,!1),e,w),ye(([x,b,S])=>!x&&!S&&b!==0),re(([x,b])=>b),on(1)),g),fe(F(f,re(x=>({top:-x}))),t),He(F(u,Re(h,d),re(([x,{groupIndices:b,lastSize:S,sizeTree:k},C])=>{function T(I){return I*(S+C)}if(b.length===0)return T(x);{let I=0;const N=xr(k,0);let _=0,j=0;for(;_<x;){_++,I+=N;let R=b.length===j+1?1/0:b[j+1]-b[j]-1;_+R>x&&(I-=N,R=x-_+1),_+=R,I+=T(R),j++}return I}})),x=>{Ae(e,x),requestAnimationFrame(()=>{Ae(t,{top:x}),requestAnimationFrame(()=>{Ae(e,0),Ae(w,!1)})})}),{deviation:e}},Xe(mt,Tr,_n,Gt,dn,ni)),ux=Be(([e,t,n,r,o,s,i,a,c,u,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...c,...u,...d}),Xe(ai,rx,hn,wc,mc,ox,Qg,ci,xc,dn,gc)),yc=Be(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:c,statefulTotalCount:u,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:m,scrolledToInitialItem:w},v,g,x,{listState:b,topItemsIndexes:S,...k},{scrollToIndex:C},T,{topItemCount:I},{groupCounts:N},_])=>(fe(k.rangeChanged,_.scrollSeekRangeChanged),fe(F(_.windowViewportRect,re(j=>j.visibleHeight)),v.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:N,initialItemFinalLocationReached:h,initialTopMostItemIndex:m,scrolledToInitialItem:w,sizeRanges:a,topItemCount:I,topItemsIndexes:S,totalCount:d,...x,groupIndices:s,itemSize:i,listState:b,scrollToIndex:C,statefulTotalCount:u,trackItemSizes:f,...k,..._,...v,sizes:c,...g}),Xe(Gt,yr,mt,sx,nx,_n,br,cx,ax,ac,ux));function dx(e,t){const n={},r={};let o=0;const s=e.length;for(;o<s;)r[e[o]]=1,o+=1;for(const i in t)Object.hasOwn(r,i)||(n[i]=t[i]);return n}const xo=typeof document<"u"?y.useLayoutEffect:y.useEffect;function Sc(e,t,n){const r=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),s=Object.keys(t.methods||{}),i=Object.keys(t.events||{}),a=y.createContext({});function c(g,x){g.propsReady&&Ae(g.propsReady,!1);for(const b of r){const S=g[t.required[b]];Ae(S,x[b])}for(const b of o)if(b in x){const S=g[t.optional[b]];Ae(S,x[b])}g.propsReady&&Ae(g.propsReady,!0)}function u(g){return s.reduce((x,b)=>(x[b]=S=>{const k=g[t.methods[b]];Ae(k,S)},x),{})}function d(g){return i.reduce((x,b)=>(x[b]=Ig(g[t.events[b]]),x),{})}const f=y.forwardRef((g,x)=>{const{children:b,...S}=g,[k]=y.useState(()=>lo(Ag(e),I=>{c(I,S)})),[C]=y.useState(Vl(d,k));xo(()=>{for(const I of i)I in S&&He(C[I],S[I]);return()=>{Object.values(C).map(Ys)}},[S,C,k]),xo(()=>{c(k,S)}),y.useImperativeHandle(x,Ul(u(k)));const T=n;return l.jsx(a.Provider,{value:k,children:n?l.jsx(T,{...dx([...r,...o,...i],S),children:b}):b})}),h=g=>{const x=y.useContext(a);return y.useCallback(b=>{Ae(x[g],b)},[x,g])},m=g=>{const x=y.useContext(a)[g],b=y.useCallback(S=>He(x,S),[x]);return y.useSyncExternalStore(b,()=>nt(x),()=>nt(x))},w=g=>{const x=y.useContext(a)[g],[b,S]=y.useState(Vl(nt,x));return xo(()=>He(x,k=>{k!==b&&S(Ul(k))}),[x,b]),b},v=y.version.startsWith("18")?m:w;return{Component:f,useEmitter:(g,x)=>{const b=y.useContext(a)[g];xo(()=>He(b,x),[x,b])},useEmitterValue:v,usePublisher:h}}const Cc=y.createContext(void 0),Tc=y.createContext(void 0),Ec=typeof document<"u"?y.useLayoutEffect:y.useEffect;function ui(e){return"self"in e}function fx(e){return"body"in e}function kc(e,t,n,r=qn,o,s){const i=y.useRef(null),a=y.useRef(null),c=y.useRef(null),u=y.useCallback(h=>{let m,w,v;const g=h.target;if(fx(g)||ui(g)){const b=ui(g)?g:g.defaultView;v=s?b.scrollX:b.scrollY,m=s?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,w=s?b.innerWidth:b.innerHeight}else v=s?g.scrollLeft:g.scrollTop,m=s?g.scrollWidth:g.scrollHeight,w=s?g.offsetWidth:g.offsetHeight;const x=()=>{e({scrollHeight:m,scrollTop:Math.max(v,0),viewportHeight:w})};h.suppressFlushSync?x():Is.flushSync(x),a.current!==null&&(v===a.current||v<=0||v===m-w)&&(a.current=null,t(!0),c.current&&(clearTimeout(c.current),c.current=null))},[e,t,s]);y.useEffect(()=>{const h=o||i.current;return r(o||i.current),u({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",u,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",u)}},[i,u,n,r,o]);function d(h){const m=i.current;if(!m||(s?"offsetWidth"in m&&m.offsetWidth===0:"offsetHeight"in m&&m.offsetHeight===0))return;const w=h.behavior==="smooth";let v,g,x;ui(m)?(g=Math.max(fn(m.document.documentElement,s?"width":"height"),s?m.document.documentElement.scrollWidth:m.document.documentElement.scrollHeight),v=s?m.innerWidth:m.innerHeight,x=s?window.scrollX:window.scrollY):(g=m[s?"scrollWidth":"scrollHeight"],v=fn(m,s?"width":"height"),x=m[s?"scrollLeft":"scrollTop"]);const b=g-v;if(h.top=Math.ceil(Math.max(Math.min(b,h.top),0)),cc(v,g)||h.top===x){e({scrollHeight:g,scrollTop:x,viewportHeight:v}),w&&t(!0);return}w?(a.current=h.top,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(h={behavior:h.behavior,left:h.top}),m.scrollTo(h)}function f(h){s&&(h={behavior:h.behavior,left:h.top}),i.current.scrollBy(h)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:d}}const di="-webkit-sticky",Ic="sticky",fi=bc(()=>{if(typeof document>"u")return Ic;const e=document.createElement("div");return e.style.position=di,e.style.position===di?di:Ic});function hi(e){return e}const hx=Be(()=>{const e=G(a=>`Item ${a}`),t=G(a=>`Group ${a}`),n=G({}),r=G(hi),o=G("div"),s=G(qn),i=(a,c=null)=>ft(F(n,re(u=>u[a]),Je()),c);return{components:n,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:t,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:e,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),px=Be(([e,t])=>({...e,...t}),Xe(yc,hx)),mx=({height:e})=>l.jsx("div",{style:{height:e}}),gx={overflowAnchor:"none",position:fi(),zIndex:1},Nc={overflowAnchor:"none"},xx={...Nc,display:"inline-block",height:"100%"},Ac=y.memo(function({showTopList:e=!1}){const t=Ee("listState"),n=jt("sizeRanges"),r=Ee("useWindowScroll"),o=Ee("customScrollParent"),s=jt("windowScrollContainerState"),i=jt("scrollContainerState"),a=o||r?s:i,c=Ee("itemContent"),u=Ee("context"),d=Ee("groupContent"),f=Ee("trackItemSizes"),h=Ee("itemSize"),m=Ee("log"),w=jt("gap"),v=Ee("horizontalDirection"),{callbackRef:g}=Rg(n,h,f,e?qn:a,m,w,o,v,Ee("skipAnimationFrameInResizeObserver")),[x,b]=y.useState(0);pi("deviation",O=>{x!==O&&b(O)});const S=Ee("EmptyPlaceholder"),k=Ee("ScrollSeekPlaceholder")||mx,C=Ee("ListComponent"),T=Ee("ItemComponent"),I=Ee("GroupComponent"),N=Ee("computeItemKey"),_=Ee("isSeeking"),j=Ee("groupIndices").length>0,R=Ee("alignToBottom"),$=Ee("initialItemFinalLocationReached"),z=e?{}:{boxSizing:"border-box",...v?{display:"inline-block",height:"100%",marginLeft:x!==0?x:R?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:x!==0?x:R?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...$?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&S?l.jsx(S,{...ht(S,u)}):l.jsx(C,{...ht(C,u),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:g,style:z,children:(e?t.topItems:t.items).map(O=>{const W=O.originalIndex,B=N(W+t.firstItemIndex,O.data,u);return _?y.createElement(k,{...ht(k,u),height:O.size,index:O.index,key:B,type:O.type||"item",...O.type==="group"?{}:{groupIndex:O.groupIndex}}):O.type==="group"?y.createElement(I,{...ht(I,u),"data-index":W,"data-item-index":O.index,"data-known-size":O.size,key:B,style:gx},d(O.index,u)):y.createElement(T,{...ht(T,u),...yx(T,O.data),"data-index":W,"data-item-group-index":O.groupIndex,"data-item-index":O.index,"data-known-size":O.size,key:B,style:v?xx:Nc},j?c(O.index,O.groupIndex,O.data,u):c(O.index,O.data,u))})})}),vx={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},wx={outline:"none",overflowX:"auto",position:"relative"},vo=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),bx={position:fi(),top:0,width:"100%",zIndex:1};function ht(e,t){if(typeof e!="string")return{context:t}}function yx(e,t){return{item:typeof e=="string"?void 0:t}}const Sx=y.memo(function(){const e=Ee("HeaderComponent"),t=jt("headerHeight"),n=Ee("HeaderFooterTag"),r=Nn(y.useMemo(()=>s=>{t(fn(s,"height"))},[t]),!0,Ee("skipAnimationFrameInResizeObserver")),o=Ee("context");return e?l.jsx(n,{ref:r,children:l.jsx(e,{...ht(e,o)})}):null}),Cx=y.memo(function(){const e=Ee("FooterComponent"),t=jt("footerHeight"),n=Ee("HeaderFooterTag"),r=Nn(y.useMemo(()=>s=>{t(fn(s,"height"))},[t]),!0,Ee("skipAnimationFrameInResizeObserver")),o=Ee("context");return e?l.jsx(n,{ref:r,children:l.jsx(e,{...ht(e,o)})}):null});function _c({useEmitter:e,useEmitterValue:t,usePublisher:n}){return y.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),c=t("ScrollerComponent"),u=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:m,scrollToCallback:w}=kc(a,u,c,d,void 0,f);return e("scrollTo",w),e("scrollBy",h),l.jsx(c,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:m,style:{...f?wx:vx,...o},tabIndex:0,...i,...ht(c,s),children:r})})}function jc({useEmitter:e,useEmitterValue:t,usePublisher:n}){return y.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),c=t("ScrollerComponent"),u=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),m=y.useRef(null),w=t("scrollerRef"),{scrollByCallback:v,scrollerRef:g,scrollToCallback:x}=kc(a,u,c,w,h);return Ec(()=>{var b;return g.current=h||((b=m.current)==null?void 0:b.ownerDocument.defaultView),()=>{g.current=null}},[g,h]),e("windowScrollTo",x),e("scrollBy",v),l.jsx(c,{ref:m,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...ht(c,s),children:r})})}const Tx=({children:e})=>{const t=y.useContext(Cc),n=jt("viewportHeight"),r=jt("fixedItemHeight"),o=Ee("alignToBottom"),s=Ee("horizontalDirection"),i=y.useMemo(()=>Wl(n,c=>fn(c,s?"width":"height")),[n,s]),a=Nn(i,!0,Ee("skipAnimationFrameInResizeObserver"));return y.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),l.jsx("div",{"data-viewport-type":"element",ref:a,style:vo(o),children:e})},Ex=({children:e})=>{const t=y.useContext(Cc),n=jt("windowViewportRect"),r=jt("fixedItemHeight"),o=Ee("customScrollParent"),s=Yl(n,o,Ee("skipAnimationFrameInResizeObserver")),i=Ee("alignToBottom");return y.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),l.jsx("div",{"data-viewport-type":"window",ref:s,style:vo(i),children:e})},kx=({children:e})=>{const t=Ee("TopItemListComponent")||"div",n=Ee("headerHeight"),r={...bx,marginTop:`${n}px`},o=Ee("context");return l.jsx(t,{style:r,...ht(t,o),children:e})},Ix=y.memo(function(e){const t=Ee("useWindowScroll"),n=Ee("topItemsIndexes").length>0,r=Ee("customScrollParent"),o=Ee("context");return l.jsxs(r||t?_x:Ax,{...e,context:o,children:[n&&l.jsx(kx,{children:l.jsx(Ac,{showTopList:!0})}),l.jsxs(r||t?Ex:Tx,{children:[l.jsx(Sx,{}),l.jsx(Ac,{}),l.jsx(Cx,{})]})]})}),{Component:Nx,useEmitter:pi,useEmitterValue:Ee,usePublisher:jt}=Sc(px,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedItemHeight:"fixedItemHeight",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},Ix),Ax=_c({useEmitter:pi,useEmitterValue:Ee,usePublisher:jt}),_x=jc({useEmitter:pi,useEmitterValue:Ee,usePublisher:jt}),jx=Nx;Xe(yc,Be(()=>{const e=G(u=>l.jsxs("td",{children:["Item $",u]})),t=G(null),n=G(u=>l.jsxs("td",{colSpan:1e3,children:["Group ",u]})),r=G(null),o=G(null),s=G({}),i=G(hi),a=G(qn),c=(u,d=null)=>ft(F(s,re(f=>f[u]),Je()),d);return{components:s,computeItemKey:i,context:t,EmptyPlaceholder:c("EmptyPlaceholder"),FillerRow:c("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:e,groupContent:n,ScrollerComponent:c("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder"),TableBodyComponent:c("TableBody","tbody"),TableComponent:c("Table","table"),TableFooterComponent:c("TableFoot","tfoot"),TableHeadComponent:c("TableHead","thead"),TableRowComponent:c("TableRow","tr"),GroupComponent:c("Group","tr")}})),fi();const Rc={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},Rx={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Pc,floor:wo,max:Er,min:mi,round:Oc}=Math;function Mc(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function Px(e){return{...Rx,items:e}}function bo(e,t){return e&&e.width===t.width&&e.height===t.height}function Ox(e,t){return e&&e.column===t.column&&e.row===t.row}const Mx=Be(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:c,scrollTop:u,smoothScrollTargetReached:d,viewportHeight:f},h,m,{didMount:w,propsReady:v},{customScrollParent:g,useWindowScroll:x,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:k},C])=>{const T=G(0),I=G(0),N=G(Rc),_=G({height:0,width:0}),j=G({height:0,width:0}),R=De(),$=De(),z=G(0),O=G(null),W=G({column:0,row:0}),B=De(),q=De(),L=G(!1),A=G(0),D=G(!0),H=G(!1),J=G(!1);He(F(w,Re(A),ye(([M,Y])=>!!Y)),()=>{Ae(D,!1)}),He(F(ot(w,D,j,_,A,H),ye(([M,Y,ee,de,,ce])=>M&&!Y&&ee.height!==0&&de.height!==0&&!ce)),([,,,,M])=>{Ae(H,!0),si(1,()=>{Ae(R,M)}),Ft(F(u),()=>{Ae(t,[0,0]),Ae(D,!0)})}),fe(F(q,ye(M=>M!=null&&M.scrollTop>0),Kt(0)),I),He(F(w,Re(q),ye(([,M])=>M!=null)),([,M])=>{M&&(Ae(_,M.viewport),Ae(j,M.item),Ae(W,M.gap),M.scrollTop>0&&(Ae(L,!0),Ft(F(u,In(1)),Y=>{Ae(L,!1)}),Ae(c,{top:M.scrollTop})))}),fe(F(_,re(({height:M})=>M)),f),fe(F(ot(we(_,bo),we(j,bo),we(W,(M,Y)=>M&&M.column===Y.column&&M.row===Y.row),we(u)),re(([M,Y,ee,de])=>({gap:ee,item:Y,scrollTop:de,viewport:M}))),B),fe(F(ot(we(T),r,we(W,Ox),we(j,bo),we(_,bo),we(O),we(I),we(L),we(D),we(A)),ye(([,,,,,,,M])=>!M),re(([M,[Y,ee],de,ce,ze,Ye,V,,X,xe])=>{const{column:Pe,row:_e}=de,{height:et,width:st}=ce,{width:ie}=ze;if(V===0&&(M===0||ie===0))return Rc;if(st===0){const Dt=ii(xe,M),ir=Dt+Math.max(V-1,0);return Px(Mc(Dt,ir,Ye))}const ae=Dc(ie,st,Pe);let me,ge;X?Y===0&&ee===0&&V>0?(me=0,ge=V-1):(me=ae*wo((Y+_e)/(et+_e)),ge=ae*Pc((ee+_e)/(et+_e))-1,ge=mi(M-1,Er(ge,ae-1)),me=mi(ge,Er(0,me))):(me=0,ge=-1);const ke=Mc(me,ge,Ye),{bottom:je,top:Ke}=Lc(ze,de,ce,ke),qe=Pc(M/ae),lt=qe*et+(qe-1)*_e-je;return{bottom:je,itemHeight:et,items:ke,itemWidth:st,offsetBottom:lt,offsetTop:Ke,top:Ke}})),N),fe(F(O,ye(M=>M!==null),re(M=>M.length)),T),fe(F(ot(_,j,N,W),ye(([M,Y,{items:ee}])=>ee.length>0&&Y.height!==0&&M.height!==0),re(([M,Y,{items:ee},de])=>{const{bottom:ce,top:ze}=Lc(M,de,Y,ee);return[ze,ce]}),Je(vr)),t);const Q=G(!1);fe(F(u,Re(Q),re(([M,Y])=>Y||M!==0)),Q);const ue=Tt(F(ot(N,T),ye(([{items:M}])=>M.length>0),Re(Q),ye(([[M,Y],ee])=>{const de=M.items[M.items.length-1].index===Y-1;return(ee||M.bottom>0&&M.itemHeight>0&&M.offsetBottom===0&&M.items.length===Y)&&de}),re(([[,M]])=>M-1),Je())),be=Tt(F(we(N),ye(({items:M})=>M.length>0&&M[0].index===0),Kt(0),Je())),Ie=Tt(F(we(N),Re(L),ye(([{items:M},Y])=>M.length>0&&!Y),re(([{items:M}])=>({endIndex:M[M.length-1].index,startIndex:M[0].index})),Je(nc),on(0)));fe(Ie,m.scrollSeekRangeChanged),fe(F(R,Re(_,j,T,W),re(([M,Y,ee,de,ce])=>{const ze=lc(M),{align:Ye,behavior:V,offset:X}=ze;let xe=ze.index;xe==="LAST"&&(xe=de-1),xe=Er(0,xe,mi(de-1,xe));let Pe=gi(Y,ce,ee,xe);return Ye==="end"?Pe=Oc(Pe-Y.height+ee.height):Ye==="center"&&(Pe=Oc(Pe-Y.height/2+ee.height/2)),X&&(Pe+=X),{behavior:V,top:Pe}})),c);const K=ft(F(N,re(M=>M.offsetBottom+M.bottom)),0);return fe(F(k,re(M=>({height:M.visibleHeight,width:M.visibleWidth}))),_),{customScrollParent:g,data:O,deviation:z,footerHeight:o,gap:W,headerHeight:s,increaseViewportBy:e,initialItemCount:I,itemDimensions:j,overscan:n,restoreStateFrom:q,scrollBy:i,scrollContainerState:a,scrollHeight:$,scrollTo:c,scrollToIndex:R,scrollTop:u,smoothScrollTargetReached:d,totalCount:T,useWindowScroll:x,viewportDimensions:_,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:k,...m,gridState:N,horizontalDirection:J,initialTopMostItemIndex:A,totalListHeight:K,...h,endReached:ue,propsReady:v,rangeChanged:Ie,startReached:be,stateChanged:B,stateRestoreInProgress:L,...C}},Xe(ai,mt,Tr,wc,hn,ci,dn));function Dc(e,t,n){return Er(1,wo((e+n)/(wo(t)+n)))}function Lc(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=gi(e,t,n,r[0].index);return{bottom:gi(e,t,n,r[r.length-1].index)+o,top:s}}function gi(e,t,n,r){const o=Dc(e.width,n.width,t.column),s=wo(r/o),i=s*n.height+Er(0,s-1)*t.row;return i>0?i+t.row:i}const Dx=Be(()=>{const e=G(f=>`Item ${f}`),t=G({}),n=G(null),r=G("virtuoso-grid-item"),o=G("virtuoso-grid-list"),s=G(hi),i=G("div"),a=G(qn),c=(f,h=null)=>ft(F(t,re(m=>m[f]),Je()),h),u=G(!1),d=G(!1);return fe(we(d),u),{components:t,computeItemKey:s,context:n,FooterComponent:c("Footer"),HeaderComponent:c("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:c("Item","div"),itemContent:e,listClassName:o,ListComponent:c("List","div"),readyStateChanged:u,reportReadyState:d,ScrollerComponent:c("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder","div")}}),Lx=Be(([e,t])=>({...e,...t}),Xe(Mx,Dx)),$x=y.memo(function(){const e=Ze("gridState"),t=Ze("listClassName"),n=Ze("itemClassName"),r=Ze("itemContent"),o=Ze("computeItemKey"),s=Ze("isSeeking"),i=Rt("scrollHeight"),a=Ze("ItemComponent"),c=Ze("ListComponent"),u=Ze("ScrollSeekPlaceholder"),d=Ze("context"),f=Rt("itemDimensions"),h=Rt("gap"),m=Ze("log"),w=Ze("stateRestoreInProgress"),v=Rt("reportReadyState"),g=Nn(y.useMemo(()=>x=>{const b=x.parentElement.parentElement.scrollHeight;i(b);const S=x.firstChild;if(S){const{height:k,width:C}=S.getBoundingClientRect();f({height:k,width:C})}h({column:Fc("column-gap",getComputedStyle(x).columnGap,m),row:Fc("row-gap",getComputedStyle(x).rowGap,m)})},[i,f,h,m]),!0,!1);return Ec(()=>{e.itemHeight>0&&e.itemWidth>0&&v(!0)},[e]),w?null:l.jsx(c,{className:t,ref:g,...ht(c,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(x=>{const b=o(x.index,x.data,d);return s?l.jsx(u,{...ht(u,d),height:e.itemHeight,index:x.index,width:e.itemWidth},b):y.createElement(a,{...ht(a,d),className:n,"data-index":x.index,key:b},r(x.index,x.data,d))})})}),Fx=y.memo(function(){const e=Ze("HeaderComponent"),t=Rt("headerHeight"),n=Ze("headerFooterTag"),r=Nn(y.useMemo(()=>s=>{t(fn(s,"height"))},[t]),!0,!1),o=Ze("context");return e?l.jsx(n,{ref:r,children:l.jsx(e,{...ht(e,o)})}):null}),zx=y.memo(function(){const e=Ze("FooterComponent"),t=Rt("footerHeight"),n=Ze("headerFooterTag"),r=Nn(y.useMemo(()=>s=>{t(fn(s,"height"))},[t]),!0,!1),o=Ze("context");return e?l.jsx(n,{ref:r,children:l.jsx(e,{...ht(e,o)})}):null}),Bx=({children:e})=>{const t=y.useContext(Tc),n=Rt("itemDimensions"),r=Rt("viewportDimensions"),o=Nn(y.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return y.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),l.jsx("div",{ref:o,style:vo(!1),children:e})},Hx=({children:e})=>{const t=y.useContext(Tc),n=Rt("windowViewportRect"),r=Rt("itemDimensions"),o=Ze("customScrollParent"),s=Yl(n,o,!1);return y.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),l.jsx("div",{ref:s,style:vo(!1),children:e})},Ux=y.memo(function({...e}){const t=Ze("useWindowScroll"),n=Ze("customScrollParent"),r=n||t?Vx:Wx,o=n||t?Hx:Bx,s=Ze("context");return l.jsx(r,{...e,...ht(r,s),children:l.jsxs(o,{children:[l.jsx(Fx,{}),l.jsx($x,{}),l.jsx(zx,{})]})})}),{useEmitter:$c,useEmitterValue:Ze,usePublisher:Rt}=Sc(Lx,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},Ux),Wx=_c({useEmitter:$c,useEmitterValue:Ze,usePublisher:Rt}),Vx=jc({useEmitter:$c,useEmitterValue:Ze,usePublisher:Rt});function Fc(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,bt.WARN),t==="normal"?0:parseInt(t??"0",10)}const Kx=Kr.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function xi({className:e,variant:t,...n}){return l.jsx("div",{className:Z(Kx({variant:t}),e),...n})}function se(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function qx(e,t){const n=p.createContext(t),r=s=>{const{children:i,...a}=s,c=p.useMemo(()=>a,Object.values(a));return l.jsx(n.Provider,{value:c,children:i})};r.displayName=e+"Provider";function o(s){const i=p.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Yt(e,t=[]){let n=[];function r(s,i){const a=p.createContext(i),c=n.length;n=[...n,i];const u=f=>{var x;const{scope:h,children:m,...w}=f,v=((x=h==null?void 0:h[e])==null?void 0:x[c])||a,g=p.useMemo(()=>w,Object.values(w));return l.jsx(v.Provider,{value:g,children:m})};u.displayName=s+"Provider";function d(f,h){var v;const m=((v=h==null?void 0:h[e])==null?void 0:v[c])||a,w=p.useContext(m);if(w)return w;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[u,d]}const o=()=>{const s=n.map(i=>p.createContext(i));return function(a){const c=(a==null?void 0:a[e])||s;return p.useMemo(()=>({[`__scope${e}`]:{...a,[e]:c}}),[a,c])}};return o.scopeName=e,[r,Gx(o,...t)]}function Gx(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:c,scopeName:u})=>{const f=c(s)[`__scope${u}`];return{...a,...f}},{});return p.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var ct=globalThis!=null&&globalThis.document?p.useLayoutEffect:()=>{},Yx=p[" useInsertionEffect ".trim().toString()]||ct;function jn({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=Xx({defaultProp:t,onChange:n}),a=e!==void 0,c=a?e:o;{const d=p.useRef(e!==void 0);p.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const u=p.useCallback(d=>{var f;if(a){const h=Jx(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[c,u]}function Xx({defaultProp:e,onChange:t}){const[n,r]=p.useState(e),o=p.useRef(n),s=p.useRef(t);return Yx(()=>{s.current=t},[t]),p.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function Jx(e){return typeof e=="function"}function zc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function vi(...e){return t=>{let n=!1;const r=e.map(o=>{const s=zc(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():zc(e[o],null)}}}}function Oe(...e){return p.useCallback(vi(...e),e)}var Zx=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Se=Zx.reduce((e,t)=>{const n=Cn.createSlot(`Primitive.${t}`),r=p.forwardRef((o,s)=>{const{asChild:i,...a}=o,c=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l.jsx(c,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Bc(e,t){e&&qr.flushSync(()=>e.dispatchEvent(t))}function Qx(e,t){return p.useReducer((n,r)=>t[n][r]??n,e)}var kt=e=>{const{present:t,children:n}=e,r=ev(t),o=typeof n=="function"?n({present:r.isPresent}):p.Children.only(n),s=Oe(r.ref,tv(o));return typeof n=="function"||r.isPresent?p.cloneElement(o,{ref:s}):null};kt.displayName="Presence";function ev(e){const[t,n]=p.useState(),r=p.useRef(null),o=p.useRef(e),s=p.useRef("none"),i=e?"mounted":"unmounted",[a,c]=Qx(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return p.useEffect(()=>{const u=yo(r.current);s.current=a==="mounted"?u:"none"},[a]),ct(()=>{const u=r.current,d=o.current;if(d!==e){const h=s.current,m=yo(u);e?c("MOUNT"):m==="none"||(u==null?void 0:u.display)==="none"?c("UNMOUNT"):c(d&&h!==m?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),ct(()=>{if(t){let u;const d=t.ownerDocument.defaultView??window,f=m=>{const v=yo(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&v&&(c("ANIMATION_END"),!o.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",u=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},h=m=>{m.target===t&&(s.current=yo(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(u),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:p.useCallback(u=>{r.current=u?getComputedStyle(u):null,n(u)},[])}}function yo(e){return(e==null?void 0:e.animationName)||"none"}function tv(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var nv=p[" useId ".trim().toString()]||(()=>{}),rv=0;function Xt(e){const[t,n]=p.useState(nv());return ct(()=>{n(r=>r??String(rv++))},[e]),e||(t?`radix-${t}`:"")}var So="Collapsible",[ov,UC]=Yt(So),[sv,wi]=ov(So),Hc=p.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:s,onOpenChange:i,...a}=e,[c,u]=jn({prop:r,defaultProp:o??!1,onChange:i,caller:So});return l.jsx(sv,{scope:n,disabled:s,contentId:Xt(),open:c,onOpenToggle:p.useCallback(()=>u(d=>!d),[u]),children:l.jsx(Se.div,{"data-state":yi(c),"data-disabled":s?"":void 0,...a,ref:t})})});Hc.displayName=So;var Uc="CollapsibleTrigger",Wc=p.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,o=wi(Uc,n);return l.jsx(Se.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":yi(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:t,onClick:se(e.onClick,o.onOpenToggle)})});Wc.displayName=Uc;var bi="CollapsibleContent",iv=p.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=wi(bi,e.__scopeCollapsible);return l.jsx(kt,{present:n||o.open,children:({present:s})=>l.jsx(av,{...r,ref:t,present:s})})});iv.displayName=bi;var av=p.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:o,...s}=e,i=wi(bi,n),[a,c]=p.useState(r),u=p.useRef(null),d=Oe(t,u),f=p.useRef(0),h=f.current,m=p.useRef(0),w=m.current,v=i.open||a,g=p.useRef(v),x=p.useRef(void 0);return p.useEffect(()=>{const b=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(b)},[]),ct(()=>{const b=u.current;if(b){x.current=x.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const S=b.getBoundingClientRect();f.current=S.height,m.current=S.width,g.current||(b.style.transitionDuration=x.current.transitionDuration,b.style.animationName=x.current.animationName),c(r)}},[i.open,r]),l.jsx(Se.div,{"data-state":yi(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!v,...s,ref:d,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":w?`${w}px`:void 0,...e.style},children:v&&o})});function yi(e){return e?"open":"closed"}var lv=Hc;const Vc=lv,Kc=Wc,kr=p.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:Z("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));kr.displayName="Card";const Ir=p.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:Z("flex flex-col space-y-1.5 p-6",e),...t}));Ir.displayName="CardHeader";const Nr=p.forwardRef(({className:e,...t},n)=>l.jsx("h3",{ref:n,className:Z("text-2xl font-semibold leading-none tracking-tight",e),...t}));Nr.displayName="CardTitle";const qc=p.forwardRef(({className:e,...t},n)=>l.jsx("p",{ref:n,className:Z("text-sm text-muted-foreground",e),...t}));qc.displayName="CardDescription";const Co=p.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:Z("p-6 pt-0",e),...t}));Co.displayName="CardContent";const Gc=p.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:Z("flex items-center p-6 pt-0",e),...t}));Gc.displayName="CardFooter";function Yc(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let Rn=Yc();function cv(e){Rn=e}const Xc=/[&<>"']/,uv=new RegExp(Xc.source,"g"),Jc=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,dv=new RegExp(Jc.source,"g"),fv={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Zc=e=>fv[e];function pt(e,t){if(t){if(Xc.test(e))return e.replace(uv,Zc)}else if(Jc.test(e))return e.replace(dv,Zc);return e}const hv=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Qc(e){return e.replace(hv,(t,n)=>(n=n.toLowerCase(),n==="colon"?":":n.charAt(0)==="#"?n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1)):""))}const pv=/(^|[^\[])\^/g;function Ve(e,t){e=typeof e=="string"?e:e.source,t=t||"";const n={replace:(r,o)=>(o=o.source||o,o=o.replace(pv,"$1"),e=e.replace(r,o),n),getRegex:()=>new RegExp(e,t)};return n}const mv=/[^\w:]/g,gv=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function eu(e,t,n){if(e){let r;try{r=decodeURIComponent(Qc(n)).replace(mv,"").toLowerCase()}catch{return null}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:")===0||r.indexOf("data:")===0)return null}t&&!gv.test(n)&&(n=bv(t,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch{return null}return n}const To={},xv=/^[^:]+:\/*[^/]*$/,vv=/^([^:]+:)[\s\S]*$/,wv=/^([^:]+:\/*[^/]*)[\s\S]*$/;function bv(e,t){To[" "+e]||(xv.test(e)?To[" "+e]=e+"/":To[" "+e]=ko(e,"/",!0)),e=To[" "+e];const n=e.indexOf(":")===-1;return t.substring(0,2)==="//"?n?t:e.replace(vv,"$1")+t:t.charAt(0)==="/"?n?t:e.replace(wv,"$1")+t:e+t}const Eo={exec:function(){}};function tu(e,t){const n=e.replace(/\|/g,(s,i,a)=>{let c=!1,u=i;for(;--u>=0&&a[u]==="\\";)c=!c;return c?"|":" |"}),r=n.split(/ \|/);let o=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(/\\\|/g,"|");return r}function ko(e,t,n){const r=e.length;if(r===0)return"";let o=0;for(;o<r;){const s=e.charAt(r-o-1);if(s===t&&!n)o++;else if(s!==t&&n)o++;else break}return e.slice(0,r-o)}function yv(e,t){if(e.indexOf(t[1])===-1)return-1;const n=e.length;let r=0,o=0;for(;o<n;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])r++;else if(e[o]===t[1]&&(r--,r<0))return o;return-1}function Sv(e){e&&e.sanitize&&!e.silent&&console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options")}function nu(e,t){if(t<1)return"";let n="";for(;t>1;)t&1&&(n+=e),t>>=1,e+=e;return n+e}function ru(e,t,n,r){const o=t.href,s=t.title?pt(t.title):null,i=e[1].replace(/\\([\[\]])/g,"$1");if(e[0].charAt(0)!=="!"){r.state.inLink=!0;const a={type:"link",raw:n,href:o,title:s,text:i,tokens:r.inlineTokens(i)};return r.state.inLink=!1,a}return{type:"image",raw:n,href:o,title:s,text:pt(i)}}function Cv(e,t){const n=e.match(/^(\s+)(?:```)/);if(n===null)return t;const r=n[1];return t.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teodor-new-chat-ui",
3
- "version": "4.0.19",
3
+ "version": "4.0.20",
4
4
  "description": "React chat UI components with streaming support, tool calls, and modern design",
5
5
  "main": "dist/index.umd.js",
6
6
  "module": "dist/index.esm.js",