db-studio 1.16.2 → 1.18.0
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.js +165 -102
- package/dist/index.js.map +1 -1
- package/dist/web-dist/assets/_pathlessLayout-D83hYFIC.js +1 -0
- package/dist/web-dist/assets/_pathlessLayout-DYRsUfs6.js +2 -0
- package/dist/web-dist/assets/_queryId-DmyRcSX-.js +1 -0
- package/dist/web-dist/assets/_table-CXzhHR9S.js +1 -0
- package/dist/web-dist/assets/_table-Cwy7lxKk.js +1 -0
- package/dist/web-dist/assets/_table-DaqO5XGq.js +1 -0
- package/dist/web-dist/assets/abap-Ds2wIDQc.js +1 -0
- package/dist/web-dist/assets/apex-DfqBN11z.js +1 -0
- package/dist/web-dist/assets/azcli-COqL1c-b.js +1 -0
- package/dist/web-dist/assets/badge-Ckwkbv_3.js +1 -0
- package/dist/web-dist/assets/bat-Nrlrgwbn.js +1 -0
- package/dist/web-dist/assets/bicep-DMqb4xTm.js +2 -0
- package/dist/web-dist/assets/browser-dcbfhXDu.js +1 -0
- package/dist/web-dist/assets/{bundle-mjs-g0oakdN9.js → bundle-mjs-DfrVkH8G.js} +1 -1
- package/dist/web-dist/assets/cameligo-DQX1RguE.js +1 -0
- package/dist/web-dist/assets/chat-sidebar-p9xpAAXQ.js +132 -0
- package/dist/web-dist/assets/clojure-CmnlCds-.js +1 -0
- package/dist/web-dist/assets/{code-editor-CTRHqZru.js → code-editor-DsRAUGQh.js} +2 -2
- package/dist/web-dist/assets/coffee-CgcM3HWm.js +1 -0
- package/dist/web-dist/assets/cpp-BnqpxZdA.js +1 -0
- package/dist/web-dist/assets/csharp-B8V_ECLX.js +1 -0
- package/dist/web-dist/assets/csp-Dzh7GjET.js +1 -0
- package/dist/web-dist/assets/css-BY0zxVqM.js +3 -0
- package/dist/web-dist/assets/cssMode-D_jEABO9.js +1 -0
- package/dist/web-dist/assets/cypher-D9AVJPko.js +1 -0
- package/dist/web-dist/assets/dart-vuJN5abD.js +1 -0
- package/dist/web-dist/assets/database.store-C0jTx_DA.js +57 -0
- package/dist/web-dist/assets/{dist-DlZR7Oow.js → dist-DmSgBrHs.js} +1 -1
- package/dist/web-dist/assets/dockerfile-Du-akT44.js +1 -0
- package/dist/web-dist/assets/ecl-C3XWQlLZ.js +1 -0
- package/dist/web-dist/assets/editor-1FQrmyyI.css +1 -0
- package/dist/web-dist/assets/editor.api-VeMVvGYa.js +865 -0
- package/dist/web-dist/assets/elixir-BzsCBGJ0.js +1 -0
- package/dist/web-dist/assets/esm-D_bQ4AdP.js +501 -0
- package/dist/web-dist/assets/flow9-z5gBTD0L.js +1 -0
- package/dist/web-dist/assets/freemarker2-B9XmkS8x.js +3 -0
- package/dist/web-dist/assets/fsharp-CMq6tChx.js +1 -0
- package/dist/web-dist/assets/go-ClPsEbRK.js +1 -0
- package/dist/web-dist/assets/graphql-7BvkEJ5O.js +1 -0
- package/dist/web-dist/assets/handlebars-sf8CVwlq.js +1 -0
- package/dist/web-dist/assets/hcl-DN6aCTHV.js +1 -0
- package/dist/web-dist/assets/highlighted-body-OFNGDK62-BU0nMuYA.js +1 -0
- package/dist/web-dist/assets/html-DI5TL_8H.js +1 -0
- package/dist/web-dist/assets/htmlMode-D_4DT2Lu.js +1 -0
- package/dist/web-dist/assets/{icons-wNdPUgHM.js → icons-BEkcNqUd.js} +1 -1
- package/dist/web-dist/assets/index-CK2sj4Xy.css +2 -0
- package/dist/web-dist/assets/index-b6Apx1z7.js +39 -0
- package/dist/web-dist/assets/indexes-Cv0o_HTj.js +1 -0
- package/dist/web-dist/assets/ini-Ba74TRs3.js +1 -0
- package/dist/web-dist/assets/java-B1OFDleH.js +1 -0
- package/dist/web-dist/assets/javascript-Cf3sZaZX.js +1 -0
- package/dist/web-dist/assets/json-editor-C9dFqjTV.js +1 -0
- package/dist/web-dist/assets/jsonMode-CQjwhzT5.js +7 -0
- package/dist/web-dist/assets/julia-CMywvhYA.js +1 -0
- package/dist/web-dist/assets/keys-o03XLuW4.js +1 -0
- package/dist/web-dist/assets/kotlin-BD6_sIY9.js +1 -0
- package/dist/web-dist/assets/less-BxdK-Aa1.js +2 -0
- package/dist/web-dist/assets/lexon-DCaYyeqi.js +1 -0
- package/dist/web-dist/assets/liquid-D7tk2apZ.js +1 -0
- package/dist/web-dist/assets/{logs-BnjjoFbl.js → logs-Ncb6EFEi.js} +1 -1
- package/dist/web-dist/assets/lspLanguageFeatures-DHxnBjVJ.js +4 -0
- package/dist/web-dist/assets/lua-DYwtBF6d.js +1 -0
- package/dist/web-dist/assets/m3-CogUFTfR.js +1 -0
- package/dist/web-dist/assets/markdown-COKMRj9K.js +1 -0
- package/dist/web-dist/assets/mdx-H6YCl9d8.js +1 -0
- package/dist/web-dist/assets/mermaid-GHXKKRXX-D3S70ynC.js +1 -0
- package/dist/web-dist/assets/{middleware-Bet3mw2T.js → middleware-CEqbkwLH.js} +1 -1
- package/dist/web-dist/assets/mips-BDOMMsh0.js +1 -0
- package/dist/web-dist/assets/module-CYndhtxW.js +2 -0
- package/dist/web-dist/assets/monaco-theme-BnSsSzUH.css +1 -0
- package/dist/web-dist/assets/monaco-theme-CyGd7xOU.js +64 -0
- package/dist/web-dist/assets/msdax-Bt2yooL5.js +1 -0
- package/dist/web-dist/assets/mysql-Bs8-d6RT.js +1 -0
- package/dist/web-dist/assets/objective-c-DZGYv99U.js +1 -0
- package/dist/web-dist/assets/pascal-FvUHIAld.js +1 -0
- package/dist/web-dist/assets/pascaligo-DEr9uXJO.js +1 -0
- package/dist/web-dist/assets/perl-DfX9jvgM.js +1 -0
- package/dist/web-dist/assets/personal-preferences.store-BIcu6qr5.js +1 -0
- package/dist/web-dist/assets/pgsql-B12f-wRt.js +1 -0
- package/dist/web-dist/assets/php-MynGtmh0.js +1 -0
- package/dist/web-dist/assets/pla-BSfIEgVT.js +1 -0
- package/dist/web-dist/assets/postiats-wriGJNMc.js +1 -0
- package/dist/web-dist/assets/powerquery-qTNF5irm.js +1 -0
- package/dist/web-dist/assets/powershell-Cr0AiP2J.js +1 -0
- package/dist/web-dist/assets/preload-helper-DICoZAvL.js +1 -0
- package/dist/web-dist/assets/protobuf-B5pCjOfx.js +2 -0
- package/dist/web-dist/assets/pug-BnGzsuEw.js +1 -0
- package/dist/web-dist/assets/python-Bd-J5HMt.js +1 -0
- package/dist/web-dist/assets/qsharp-C-Z8Szjm.js +1 -0
- package/dist/web-dist/assets/{queries.store-BlC7QGq6.js → queries.store-BbUkkWy1.js} +1 -1
- package/dist/web-dist/assets/{query-runner-CQWHEby5.js → query-runner-DBIufzsZ.js} +5 -5
- package/dist/web-dist/assets/r-lFEgLDol.js +1 -0
- package/dist/web-dist/assets/radix-ui-Bp71_UWp.js +51 -0
- package/dist/web-dist/assets/razor-BL-2JJuP.js +1 -0
- package/dist/web-dist/assets/react-BziCK5DU.js +1 -0
- package/dist/web-dist/assets/{react-dom-CnDfVSZQ.js → react-dom-ctQEFzyp.js} +5 -5
- package/dist/web-dist/assets/redis-CJPiZ1dc.js +1 -0
- package/dist/web-dist/assets/redis-value-rbj0L_ie.js +1 -0
- package/dist/web-dist/assets/redshift-D1FKNo6F.js +1 -0
- package/dist/web-dist/assets/restructuredtext-BdtNntNZ.js +1 -0
- package/dist/web-dist/assets/{rolldown-runtime-Y-txFyxk.js → rolldown-runtime-Ba77kUFP.js} +1 -1
- package/dist/web-dist/assets/ruby-C2uUAsPh.js +1 -0
- package/dist/web-dist/assets/runner-WhyDqbco.js +1 -0
- package/dist/web-dist/assets/rust-B22jVKPi.js +1 -0
- package/dist/web-dist/assets/sb-H5-MsoWu.js +1 -0
- package/dist/web-dist/assets/scala-JHuRLUuq.js +1 -0
- package/dist/web-dist/assets/{schema-C27u7buH.js → schema-DdnQO20v.js} +1 -1
- package/dist/web-dist/assets/scheme-CqKe-_5y.js +1 -0
- package/dist/web-dist/assets/scss-C9ckl5Lm.js +3 -0
- package/dist/web-dist/assets/select-Cg3fBZqb.js +1 -0
- package/dist/web-dist/assets/separator-B2Ii4cjw.js +1 -0
- package/dist/web-dist/assets/sheet-sidebar-D8BG4Pf9.js +1 -0
- package/dist/web-dist/assets/shell-C9lIrU5P.js +1 -0
- package/dist/web-dist/assets/solidity-BdsCByFb.js +1 -0
- package/dist/web-dist/assets/sophia-BiYQOR15.js +1 -0
- package/dist/web-dist/assets/sparql-CZhOhni4.js +1 -0
- package/dist/web-dist/assets/spinner-gvrX8mkL.js +1 -0
- package/dist/web-dist/assets/sql-DGoEI4nz.js +1 -0
- package/dist/web-dist/assets/st-DUBBkXkg.js +1 -0
- package/dist/web-dist/assets/swift-D_36y0eN.js +1 -0
- package/dist/web-dist/assets/systemverilog-BAtlR_WK.js +1 -0
- package/dist/web-dist/assets/{table-B1OYFDnr.js → table-Gq1Nd4WJ.js} +1 -1
- package/dist/web-dist/assets/tanstack-HxB2LyLp.js +8 -0
- package/dist/web-dist/assets/tcl-D05MO8B_.js +1 -0
- package/dist/web-dist/assets/tooltip-CIAbgIn7.js +12 -0
- package/dist/web-dist/assets/tsMode-4FmdP9_o.js +11 -0
- package/dist/web-dist/assets/twig-CPq3SV5E.js +1 -0
- package/dist/web-dist/assets/typescript-CEcdsK9n.js +1 -0
- package/dist/web-dist/assets/typespec-I6aAHcEc.js +1 -0
- package/dist/web-dist/assets/utils-CNXzeC6_.js +1 -0
- package/dist/web-dist/assets/vb-C6fWMOt8.js +1 -0
- package/dist/web-dist/assets/{visualizer-CITcnwJh.js → visualizer-Cxu0_nai.js} +1 -1
- package/dist/web-dist/assets/wgsl-CsswhpkD.js +298 -0
- package/dist/web-dist/assets/workers-CH8V5wKq.js +1 -0
- package/dist/web-dist/assets/xml-Clh3WxEv.js +1 -0
- package/dist/web-dist/assets/yaml--Kwp2ruw.js +1 -0
- package/dist/web-dist/index.html +22 -20
- package/package.json +8 -5
- package/dist/web-dist/assets/_pathlessLayout-C0MMCDcm.js +0 -1
- package/dist/web-dist/assets/_pathlessLayout-XjSpVK5x.js +0 -132
- package/dist/web-dist/assets/_queryId-OFkn9Oa-.js +0 -1
- package/dist/web-dist/assets/_table-DWUmdgY6.js +0 -1
- package/dist/web-dist/assets/_table-jJR4Ocv2.js +0 -1
- package/dist/web-dist/assets/badge-Bd7hbykP.js +0 -1
- package/dist/web-dist/assets/browser-B8_CLARX.js +0 -1
- package/dist/web-dist/assets/database.store-DJ10NZng.js +0 -57
- package/dist/web-dist/assets/format-cell-value-ClBO-Y4U.js +0 -1
- package/dist/web-dist/assets/highlighted-body-OFNGDK62-jkW4Egvm.js +0 -1
- package/dist/web-dist/assets/index-BANk_UGi.js +0 -36
- package/dist/web-dist/assets/index-Ir-8O5kw.css +0 -2
- package/dist/web-dist/assets/indexes-hgIGRB__.js +0 -1
- package/dist/web-dist/assets/mermaid-GHXKKRXX-BUBXMhKa.js +0 -1
- package/dist/web-dist/assets/monaco-editor-DxDiR4f3.js +0 -1252
- package/dist/web-dist/assets/monaco-editor-IL9D_L0g.css +0 -1
- package/dist/web-dist/assets/monitoring-DXY00d-N.js +0 -22
- package/dist/web-dist/assets/overlay.store-DzkuYBKd.js +0 -11
- package/dist/web-dist/assets/radix-ui-D3kd-zkB.js +0 -51
- package/dist/web-dist/assets/react-1w3eYWHr.js +0 -1
- package/dist/web-dist/assets/redis-value-D7lbyO7s.js +0 -1
- package/dist/web-dist/assets/runner-BqitD-mp.js +0 -1
- package/dist/web-dist/assets/schema-C8mAjJOp.js +0 -1
- package/dist/web-dist/assets/tanstack-BvmgSO8H.js +0 -11
- package/dist/web-dist/assets/use-database-engine-wK2YTpfJ.js +0 -1
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/json-editor-C9dFqjTV.js","assets/rolldown-runtime-Ba77kUFP.js","assets/icons-BEkcNqUd.js","assets/radix-ui-Bp71_UWp.js","assets/utils-CNXzeC6_.js","assets/bundle-mjs-DfrVkH8G.js","assets/personal-preferences.store-BIcu6qr5.js","assets/react-BziCK5DU.js","assets/middleware-CEqbkwLH.js","assets/editor.api-VeMVvGYa.js","assets/preload-helper-DICoZAvL.js","assets/editor-1FQrmyyI.css","assets/monaco-theme-CyGd7xOU.js","assets/monaco-theme-BnSsSzUH.css","assets/_table-CXzhHR9S.js","assets/_pathlessLayout-DYRsUfs6.js","assets/tanstack-HxB2LyLp.js","assets/dist-DmSgBrHs.js","assets/spinner-gvrX8mkL.js","assets/keys-o03XLuW4.js","assets/tooltip-CIAbgIn7.js","assets/database.store-C0jTx_DA.js","assets/sheet-sidebar-D8BG4Pf9.js","assets/badge-Ckwkbv_3.js","assets/select-Cg3fBZqb.js","assets/separator-B2Ii4cjw.js","assets/queries.store-BbUkkWy1.js","assets/redis-value-rbj0L_ie.js","assets/_pathlessLayout-D83hYFIC.js","assets/browser-dcbfhXDu.js","assets/logs-Ncb6EFEi.js","assets/visualizer-Cxu0_nai.js","assets/indexes-Cv0o_HTj.js","assets/_table-Cwy7lxKk.js","assets/runner-WhyDqbco.js","assets/query-runner-DBIufzsZ.js","assets/_queryId-DmyRcSX-.js","assets/schema-DdnQO20v.js","assets/_table-DaqO5XGq.js","assets/table-Gq1Nd4WJ.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{n as ti,r as ed,t as td}from"./rolldown-runtime-Ba77kUFP.js";import{C as St,S as Sm,T as Cm,_ as rd,a as ri,b as ht,c as wm,d as Nm,f as kt,h as jm,i as si,l as Im,m as Tm,n as Qn,o as Rm,p as At,r as rs,s as sd,t as Em,u as km,v as Am,w as Om,x as Rr}from"./tanstack-HxB2LyLp.js";import{$ as ni,A as Dm,C as Mm,Ct as _m,D as Pm,E as Fm,F as Lm,H as zm,I as nd,J as $m,L as Vm,M as Bm,N as ul,O as Um,P as Xn,R as qm,S as Ln,St as Wm,T as Km,U as ad,V as Hm,Y as fl,Z as ja,_ as ai,_t as Gm,a as Ym,at as Jm,b as Qm,bt as Xm,ct as Zm,d as ep,dt as oi,ft as us,g as tp,h as od,ht as rp,i as sp,lt as ii,m as np,mt as ap,n as As,nt as op,o as li,pt as Os,q as ip,r as lp,rt as Ia,tt as cp,u as bo,ut as ci,w as dp,wt as up,x as di,xt as zn,y as fp,yt as hp}from"./icons-BEkcNqUd.js";import{A as mp,Ct as id,D as pp,Dt as an,E as gp,Et as Ns,F as vp,I as yp,M as bp,N as xp,O as Sp,P as Cp,St as ui,T as wp,_ as ld,_t as fi,bt as hi,d as Np,f as jp,g as Ip,h as cd,ht as Or,j as Tp,k as Rp,kt as Ep,m as dd,u as kp,vt as mi,wt as Ap,xt as pi,yt as ud}from"./radix-ui-Bp71_UWp.js";import{t as Op}from"./react-dom-ctQEFzyp.js";import{n as we,t as Dp}from"./dist-DmSgBrHs.js";import{t as V}from"./utils-CNXzeC6_.js";import{t as dn}from"./spinner-gvrX8mkL.js";import{a as Ee,c as fd,n as $n,o as me,s as Ke}from"./keys-o03XLuW4.js";import{A as Mp,C as _p,F as Pp,G as B,H as hd,I as Fp,K as hl,L as md,M as Lp,N as pd,S as gd,U as zp,V as vd,_ as $p,a as ce,b as Vp,c as je,f as Bp,g as Up,i as ar,j as qp,l as Wp,m as Kp,n as or,o as Hp,p as Gp,q as yd,r as zs,t as ir,u as bd,v as Yp,x as Jp,z as Qp}from"./tooltip-CIAbgIn7.js";import{a as Xp,c as Zp,f as Sr,i as eg,l as tg,n as rg,o as sg,r as un,t as Ut}from"./sheet-sidebar-D8BG4Pf9.js";import{t as Dr}from"./react-BziCK5DU.js";import{C as ng,S as ag,_ as Cr,a as og,b as xd,c as ig,d as ml,f as pl,g as bt,h as xo,i as cr,l as gl,m as vl,n as lg,o as cg,r as Sd,t as Me,u as yl,v as dg,x as ug,y as Vt}from"./database.store-C0jTx_DA.js";import{t as Ct}from"./preload-helper-DICoZAvL.js";import{a as fs,c as Hr,d as Gr,f as Yr,i as ur,l as Jr,m as rt,n as Mr,o as Qr,p as Xr,r as fg,s as Zr,t as Is,u as es}from"./badge-Ckwkbv_3.js";import{a as it,i as lt,n as ct,r as ue,t as dt}from"./select-Cg3fBZqb.js";import{n as Zn,r as hg,t as Vn}from"./separator-B2Ii4cjw.js";import{t as Cd}from"./middleware-CEqbkwLH.js";import{i as wd,n as mg,r as fn,t as pg}from"./personal-preferences.store-BIcu6qr5.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};e.SENTRY_RELEASE={id:"db-studio@1.18.0"};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d4bfaac8-9e2b-4e3d-b320-30353fd7e24c",e._sentryDebugIdIdentifier="sentry-dbid-d4bfaac8-9e2b-4e3d-b320-30353fd7e24c")}catch{}})();(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))s(n);new MutationObserver(n=>{for(const o of n)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&s(l)}).observe(document,{childList:!0,subtree:!0});function r(n){const o={};return n.integrity&&(o.integrity=n.integrity),n.referrerPolicy&&(o.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?o.credentials="include":n.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(n){if(n.ep)return;n.ep=!0;const o=r(n);fetch(n.href,o)}})();var f=ed(up(),1),gg=ed(Op(),1),Ta,bl=()=>new Om({defaultOptions:{queries:{staleTime:3e4,gcTime:3e5,retry:0,retryDelay:e=>Math.min(1e3*2**e,3e4),refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!0},mutations:{retry:0,networkMode:"online"},dehydrate:{shouldDehydrateQuery:e=>Cm(e)||e.state.status==="pending"}}}),Nd=()=>typeof window>"u"?bl():(Ta||(Ta=bl()),Ta),vg=(e,t,r,s,n,o,l,i)=>{let c=document.documentElement,d=["light","dark"];function u(p){(Array.isArray(e)?e:[e]).forEach(b=>{let w=b==="class",x=w&&o?n.map(N=>o[N]||N):n;w?(c.classList.remove(...x),c.classList.add(o&&o[p]?o[p]:p)):c.setAttribute(b,p)}),h(p)}function h(p){i&&d.includes(p)&&(c.style.colorScheme=p)}function m(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(s)u(s);else try{let p=localStorage.getItem(t)||r;u(l&&p==="system"?m():p)}catch{}},yg=f.createContext(void 0),bg={setTheme:e=>{},themes:[]},xg=()=>{var e;return(e=f.useContext(yg))!=null?e:bg},QT=f.memo(({forcedTheme:e,storageKey:t,attribute:r,enableSystem:s,enableColorScheme:n,defaultTheme:o,value:l,themes:i,nonce:c,scriptProps:d})=>{let u=JSON.stringify([r,t,o,e,i,l,s,n]).slice(1,-1);return f.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${vg.toString()})(${u})`}})}),a=Ep(),Sg=({...e})=>{const{theme:t="system"}=xg();return(0,a.jsx)(Dp,{theme:t,className:"toaster group",icons:{success:(0,a.jsx)(Jm,{className:"size-4 text-emerald-500"}),info:(0,a.jsx)(qm,{className:"size-4 text-blue-500"}),warning:(0,a.jsx)(Ym,{className:"size-4 text-amber-500"}),error:(0,a.jsx)(Pm,{className:"size-4 text-red-500"}),loading:(0,a.jsx)(Bm,{className:"size-4 animate-spin text-blue-500"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius)"},toastOptions:{classNames:{toast:"cn-toast"}},...e})},gi=Ng();function Le(e,...t){if(!gi)return;const r=wg(e,...t);performance.mark(r);try{console.log(e,...t)}catch{console.log(r)}}function Cg(e,...t){gi&&console.warn(e,...t)}function wg(e,...t){return e.replace(/%[sfdO]/g,r=>{const s=t.shift();return r==="%O"&&s?JSON.stringify(s).replace(/"([^"]+)":/g,"$1:"):String(s)})}function Ng(){if(typeof window>"u")return({}.DEBUG||"").includes("nuqs");try{const e="nuqs-localStorage-test";if(typeof localStorage>"u")return!1;localStorage.setItem(e,e);const t=localStorage.getItem(e)===e;return localStorage.removeItem(e),t&&(localStorage.getItem("debug")||"").includes("nuqs")}catch{return!1}}var jg={303:"Multiple adapter contexts detected. This might happen in monorepos.",404:"nuqs requires an adapter to work with your framework.",409:"Multiple versions of the library are loaded. This may lead to unexpected behavior. Currently using `%s`, but `%s` (via the %s adapter) was about to load on top.",414:"Max safe URL length exceeded. Some browsers may not be able to accept this URL. Consider limiting the amount of state stored in the URL.",422:"Invalid options combination: `limitUrlUpdates: debounce` should be used in SSR scenarios, with `shallow: false`",429:"URL update rate-limited by the browser. Consider increasing `throttleMs` for key(s) `%s`. %O",500:"Empty search params cache. Search params can't be accessed in Layouts.",501:"Search params cache already populated. Have you called `parse` twice?"};function hn(e){return`[nuqs] ${jg[e]}
|
|
3
|
+
See https://nuqs.dev/NUQS-${e}`}function Ig(e){if(e.size===0)return"";const t=[];for(const[r,s]of e.entries()){const n=r.replace(/#/g,"%23").replace(/&/g,"%26").replace(/\+/g,"%2B").replace(/=/g,"%3D").replace(/\?/g,"%3F");t.push(`${n}=${Tg(s)}`)}return"?"+t.join("&")}function Tg(e){return e.replace(/%/g,"%25").replace(/\+/g,"%2B").replace(/ /g,"+").replace(/#/g,"%23").replace(/&/g,"%26").replace(/"/g,"%22").replace(/'/g,"%27").replace(/`/g,"%60").replace(/</g,"%3C").replace(/>/g,"%3E").replace(/[\x00-\x1F]/g,t=>encodeURIComponent(t))}var ss=(0,f.createContext)({useAdapter(){throw new Error(hn(404))}});ss.displayName="NuqsAdapterContext";gi&&typeof window<"u"&&(window.__NuqsAdapterContext&&window.__NuqsAdapterContext!==ss&&console.error(hn(303)),window.__NuqsAdapterContext=ss);function Rg(e){return({children:t,defaultOptions:r,processUrlSearchParams:s,...n})=>(0,f.createElement)(ss.Provider,{...n,value:{useAdapter:e,defaultOptions:r,processUrlSearchParams:s}},t)}function Eg(e){const t=(0,f.useContext)(ss);if(!("useAdapter"in t))throw new Error(hn(404));return t.useAdapter(e)}var kg=()=>(0,f.useContext)(ss).defaultOptions,Ag=()=>(0,f.useContext)(ss).processUrlSearchParams;function Og(){if(typeof window>"u"||!window.GestureEvent)return 50;try{const e=navigator.userAgent?.match(/version\/([\d\.]+) safari/i);return parseFloat(e[1])>=17?120:320}catch{return 320}}function Dg(e){return{method:"throttle",timeMs:e}}var sn=Dg(Og());function Mg(e){return e===null||Array.isArray(e)&&e.length===0}function _g(e,t,r){if(typeof e=="string")r.set(t,e);else{r.delete(t);for(const s of e)r.append(t,s);r.has(t)||r.set(t,"")}return r}function vi(){const e=new Map;return{on(t,r){const s=e.get(t)||[];return s.push(r),e.set(t,s),()=>this.off(t,r)},off(t,r){const s=e.get(t);s&&e.set(t,s.filter(n=>n!==r))},emit(t,r){e.get(t)?.forEach(s=>s(r))}}}function So(e,t,r){function s(){e(),r.removeEventListener("abort",o)}const n=setTimeout(s,t);function o(){clearTimeout(n),r.removeEventListener("abort",o)}r.addEventListener("abort",o)}function Co(){const e=Promise;if(Promise.hasOwnProperty("withResolvers"))return Promise.withResolvers();let t=()=>{},r=()=>{};return{promise:new e((s,n)=>{t=s,r=n}),resolve:t,reject:r}}function Pg(e,t){let r=t;for(let s=e.length-1;s>=0;s--){const n=e[s];if(!n)continue;const o=r;r=()=>n(o)}r()}function wo(){return new URLSearchParams(location.search)}var jd=class{updateMap=new Map;options={history:"replace",scroll:!1,shallow:!0};timeMs=sn.timeMs;transitions=new Set;resolvers=null;controller=null;lastFlushedAt=0;resetQueueOnNextPush=!1;push({key:e,query:t,options:r},s=sn.timeMs){this.resetQueueOnNextPush&&(this.reset(),this.resetQueueOnNextPush=!1),Le("[nuqs gtq] Enqueueing %s=%s %O",e,t,r),this.updateMap.set(e,t),r.history==="push"&&(this.options.history="push"),r.scroll&&(this.options.scroll=!0),r.shallow===!1&&(this.options.shallow=!1),r.startTransition&&this.transitions.add(r.startTransition),(!Number.isFinite(this.timeMs)||s>this.timeMs)&&(this.timeMs=s)}getQueuedQuery(e){return this.updateMap.get(e)}getPendingPromise({getSearchParamsSnapshot:e=wo}){return this.resolvers?.promise??Promise.resolve(e())}flush({getSearchParamsSnapshot:e=wo,rateLimitFactor:t=1,...r},s){if(this.controller??=new AbortController,!Number.isFinite(this.timeMs))return Le("[nuqs gtq] Skipping flush due to throttleMs=Infinity"),Promise.resolve(e());if(this.resolvers)return this.resolvers.promise;this.resolvers=Co();const n=()=>{this.lastFlushedAt=performance.now();const[l,i]=this.applyPendingUpdates({...r,autoResetQueueOnUpdate:r.autoResetQueueOnUpdate??!0,getSearchParamsSnapshot:e},s);i===null?(this.resolvers.resolve(l),this.resetQueueOnNextPush=!0):this.resolvers.reject(l),this.resolvers=null};return So(()=>{const l=performance.now()-this.lastFlushedAt,i=this.timeMs,c=t*Math.max(0,i-l);Le("[nuqs gtq] Scheduling flush in %f ms. Throttled at %f ms (x%f)",c,i,t),c===0?n():So(n,c,this.controller.signal)},0,this.controller.signal),this.resolvers.promise}abort(){return this.controller?.abort(),this.controller=new AbortController,this.resolvers?.resolve(new URLSearchParams),this.resolvers=null,this.reset()}reset(){const e=Array.from(this.updateMap.keys());return Le("[nuqs gtq] Resetting queue %s",JSON.stringify(Object.fromEntries(this.updateMap))),this.updateMap.clear(),this.transitions.clear(),this.options={history:"replace",scroll:!1,shallow:!0},this.timeMs=sn.timeMs,e}applyPendingUpdates(e,t){const{updateUrl:r,getSearchParamsSnapshot:s}=e;let n=s();if(Le("[nuqs gtq] Applying %d pending update(s) on top of %s",this.updateMap.size,n.toString()),this.updateMap.size===0)return[n,null];const o=Array.from(this.updateMap.entries()),l={...this.options},i=Array.from(this.transitions);e.autoResetQueueOnUpdate&&this.reset(),Le("[nuqs gtq] Flushing queue %O with options %O",o,l);for(const[c,d]of o)d===null?n.delete(c):n=_g(d,c,n);t&&(n=t(n));try{return Pg(i,()=>{r(n,l)}),[n,null]}catch(c){return console.error(hn(429),o.map(([d])=>d).join(),c),[n,c]}}},Pn=new jd;function Fg(e,t,r){const s=(0,f.useCallback)(()=>{const o=Object.fromEntries(e.map(l=>[l,r(l)]));return[JSON.stringify(o),o]},[e.join(","),r]),n=(0,f.useRef)(null);return n.current===null&&(n.current=s()),(0,f.useSyncExternalStore)((0,f.useCallback)(o=>{const l=e.map(i=>t(i,o));return()=>l.forEach(i=>i())},[e.join(","),t]),()=>{const[o,l]=s();return n.current[0]===o?n.current[1]:(n.current=[o,l],l)},()=>n.current[1])}var Lg=class{callback;resolvers=Co();controller=new AbortController;queuedValue=void 0;constructor(e){this.callback=e}abort(){this.controller.abort(),this.queuedValue=void 0}push(e,t){return this.queuedValue=e,this.controller.abort(),this.controller=new AbortController,So(()=>{const r=this.resolvers;try{Le("[nuqs dq] Flushing debounce queue",e);const s=this.callback(e);Le("[nuqs dq] Reset debounce queue %O",this.queuedValue),this.queuedValue=void 0,this.resolvers=Co(),s.then(n=>r.resolve(n)).catch(n=>r.reject(n))}catch(s){this.queuedValue=void 0,r.reject(s)}},t,this.controller.signal),this.resolvers.promise}},zg=class{throttleQueue;queues=new Map;queuedQuerySync=vi();constructor(e=new jd){this.throttleQueue=e}useQueuedQueries(e){return Fg(e,(t,r)=>this.queuedQuerySync.on(t,r),t=>this.getQueuedQuery(t))}push(e,t,r,s){if(!Number.isFinite(t)){const l=r.getSearchParamsSnapshot??wo;return Promise.resolve(l())}const n=e.key;if(!this.queues.has(n)){Le("[nuqs dqc] Creating debounce queue for `%s`",n);const l=new Lg(i=>(this.throttleQueue.push(i),this.throttleQueue.flush(r,s).finally(()=>{this.queues.get(i.key)?.queuedValue===void 0&&(Le("[nuqs dqc] Cleaning up empty queue for `%s`",i.key),this.queues.delete(i.key)),this.queuedQuerySync.emit(i.key)})));this.queues.set(n,l)}Le("[nuqs dqc] Enqueueing debounce update %O",e);const o=this.queues.get(n).push(e,t);return this.queuedQuerySync.emit(n),o}abort(e){const t=this.queues.get(e);return t?(Le("[nuqs dqc] Aborting debounce queue %s=%s",e,t.queuedValue?.query),this.queues.delete(e),t.abort(),this.queuedQuerySync.emit(e),r=>(r.then(t.resolvers.resolve,t.resolvers.reject),r)):r=>r}abortAll(){for(const[e,t]of this.queues.entries())Le("[nuqs dqc] Aborting debounce queue %s=%s",e,t.queuedValue?.query),t.abort(),t.resolvers.resolve(new URLSearchParams),this.queuedQuerySync.emit(e);this.queues.clear()}getQueuedQuery(e){const t=this.queues.get(e)?.queuedValue?.query;return t!==void 0?t:this.throttleQueue.getQueuedQuery(e)}},Ra=new zg(Pn);function Id(e,t){return e===t?!0:e===null||t===null||typeof e=="string"||typeof t=="string"||e.length!==t.length?!1:e.every((r,s)=>r===t[s])}function xl(e,t,r){return s=>{if(!(t.length===0||t.some(o=>!Id(s.getAll(o),e.getAll(o)))))return Le("[nuqs `%s`] no change, returning previous",t.join(","),s),s;const n=Td(e,t,r);return Le("[nuqs `%s`] subbed search params change\n from %O\n to %O",t.join(","),s,n),n}}function Td(e,t,r){if(t.length===0)return e;const s=r?new URLSearchParams(e):e;for(const n of e.keys())t.includes(n)||s.delete(n);return s}var $g="__nuqs__",No=vi();function Vg(e){return function(r,s){const n=new URL(location.href);n.search=Ig(r),Le("[nuqs react] Updating url: %s",n),e&&s.shallow===!1?(s.history==="push"?location.assign:location.replace).call(location,n):(s.history==="push"?history.pushState:history.replaceState).call(history,history.state,$g,n),No.emit("update",r),s.scroll===!0&&window.scrollTo({top:0})}}var Rd=(0,f.createContext)({fullPageNavigationOnShallowFalseUpdates:!1});function Bg(e){const{fullPageNavigationOnShallowFalseUpdates:t}=(0,f.useContext)(Rd),[r,s]=(0,f.useState)(()=>typeof location>"u"?new URLSearchParams:Td(new URLSearchParams(location.search),e,!1));return(0,f.useEffect)(()=>{const n=()=>{s(xl(new URLSearchParams(location.search),e,!1))},o=l=>{s(xl(l,e,!0))};return No.on("update",o),window.addEventListener("popstate",n),()=>{No.off("update",o),window.removeEventListener("popstate",n)}},[e.join("&")]),{searchParams:r,updateUrl:(0,f.useMemo)(()=>Vg(t),[t])}}var Ug=Rg(Bg);function qg({children:e,fullPageNavigationOnShallowFalseUpdates:t=!1,...r}){return(0,f.createElement)(Rd.Provider,{value:{fullPageNavigationOnShallowFalseUpdates:t}},(0,f.createElement)(Ug,{...r,children:e}))}var Sl=1,Wg=.9,Kg=.8,Hg=.17,Ea=.1,ka=.999,Gg=.9999,Yg=.99,Jg=/[\\\/_+.#"@\[\(\{&]/,Qg=/[\\\/_+.#"@\[\(\{&]/g,Xg=/[\s-]/,Ed=/[\s-]/g;function jo(e,t,r,s,n,o,l){if(o===t.length)return n===e.length?Sl:Yg;var i=`${n},${o}`;if(l[i]!==void 0)return l[i];for(var c=s.charAt(o),d=r.indexOf(c,n),u=0,h,m,p,b;d>=0;)h=jo(e,t,r,s,d+1,o+1,l),h>u&&(d===n?h*=Sl:Jg.test(e.charAt(d-1))?(h*=Kg,p=e.slice(n,d-1).match(Qg),p&&n>0&&(h*=Math.pow(ka,p.length))):Xg.test(e.charAt(d-1))?(h*=Wg,b=e.slice(n,d-1).match(Ed),b&&n>0&&(h*=Math.pow(ka,b.length))):(h*=Hg,n>0&&(h*=Math.pow(ka,d-n))),e.charAt(d)!==t.charAt(o)&&(h*=Gg)),(h<Ea&&r.charAt(d-1)===s.charAt(o+1)||s.charAt(o+1)===s.charAt(o)&&r.charAt(d-1)!==s.charAt(o))&&(m=jo(e,t,r,s,d+1,o+2,l),m*Ea>h&&(h=m*Ea)),h>u&&(u=h),d=r.indexOf(c,d+1);return l[i]=u,u}function Cl(e){return e.toLowerCase().replace(Ed," ")}function Zg(e,t,r){return e=r&&r.length>0?`${e+" "+r.join(" ")}`:e,jo(e,t,Cl(e),Cl(t),0,0,{})}var $s='[cmdk-group=""]',Aa='[cmdk-group-items=""]',ev='[cmdk-group-heading=""]',kd='[cmdk-item=""]',wl=`${kd}:not([aria-disabled="true"])`,Io="cmdk-item-select",xs="data-value",tv=(e,t,r)=>Zg(e,t,r),Ad=f.createContext(void 0),mn=()=>f.useContext(Ad),Od=f.createContext(void 0),yi=()=>f.useContext(Od),Dd=f.createContext(void 0),Md=f.forwardRef((e,t)=>{let r=Ss(()=>{var L,$;return{search:"",value:($=(L=e.value)!=null?L:e.defaultValue)!=null?$:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),s=Ss(()=>new Set),n=Ss(()=>new Map),o=Ss(()=>new Map),l=Ss(()=>new Set),i=_d(e),{label:c,children:d,value:u,onValueChange:h,filter:m,shouldFilter:p,loop:b,disablePointerSelection:w=!1,vimBindings:x=!0,...N}=e,C=Ns(),S=Ns(),g=Ns(),v=f.useRef(null),y=fv();ns(()=>{if(u!==void 0){let L=u.trim();r.current.value=L,R.emit()}},[u]),ns(()=>{y(6,O)},[]);let R=f.useMemo(()=>({subscribe:L=>(l.current.add(L),()=>l.current.delete(L)),snapshot:()=>r.current,setState:(L,$,ne)=>{var ee,pe,K,Ie;if(!Object.is(r.current[L],$)){if(r.current[L]=$,L==="search")_(),T(),y(1,D);else if(L==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Pe=document.getElementById(g);Pe?Pe.focus():(ee=document.getElementById(C))==null||ee.focus()}if(y(7,()=>{var Pe;r.current.selectedItemId=(Pe=F())==null?void 0:Pe.id,R.emit()}),ne||y(5,O),((pe=i.current)==null?void 0:pe.value)!==void 0){let Pe=$??"";(Ie=(K=i.current).onValueChange)==null||Ie.call(K,Pe);return}}R.emit()}},emit:()=>{l.current.forEach(L=>L())}}),[]),I=f.useMemo(()=>({value:(L,$,ne)=>{var ee;$!==((ee=o.current.get(L))==null?void 0:ee.value)&&(o.current.set(L,{value:$,keywords:ne}),r.current.filtered.items.set(L,k($,ne)),y(2,()=>{T(),R.emit()}))},item:(L,$)=>(s.current.add(L),$&&(n.current.has($)?n.current.get($).add(L):n.current.set($,new Set([L]))),y(3,()=>{_(),T(),r.current.value||D(),R.emit()}),()=>{o.current.delete(L),s.current.delete(L),r.current.filtered.items.delete(L);let ne=F();y(4,()=>{_(),ne?.getAttribute("id")===L&&D(),R.emit()})}),group:L=>(n.current.has(L)||n.current.set(L,new Set),()=>{o.current.delete(L),n.current.delete(L)}),filter:()=>i.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>i.current.disablePointerSelection,listId:C,inputId:g,labelId:S,listInnerRef:v}),[]);function k(L,$){var ne,ee;let pe=(ee=(ne=i.current)==null?void 0:ne.filter)!=null?ee:tv;return L?pe(L,r.current.search,$):0}function T(){if(!r.current.search||i.current.shouldFilter===!1)return;let L=r.current.filtered.items,$=[];r.current.filtered.groups.forEach(ee=>{let pe=n.current.get(ee),K=0;pe.forEach(Ie=>{let Pe=L.get(Ie);K=Math.max(Pe,K)}),$.push([ee,K])});let ne=v.current;E().sort((ee,pe)=>{var K,Ie;let Pe=ee.getAttribute("id"),pt=pe.getAttribute("id");return((K=L.get(pt))!=null?K:0)-((Ie=L.get(Pe))!=null?Ie:0)}).forEach(ee=>{let pe=ee.closest(Aa);pe?pe.appendChild(ee.parentElement===pe?ee:ee.closest(`${Aa} > *`)):ne.appendChild(ee.parentElement===ne?ee:ee.closest(`${Aa} > *`))}),$.sort((ee,pe)=>pe[1]-ee[1]).forEach(ee=>{var pe;let K=(pe=v.current)==null?void 0:pe.querySelector(`${$s}[${xs}="${encodeURIComponent(ee[0])}"]`);K?.parentElement.appendChild(K)})}function D(){let L=E().find(ne=>ne.getAttribute("aria-disabled")!=="true"),$=L?.getAttribute(xs);R.setState("value",$||void 0)}function _(){var L,$,ne,ee;if(!r.current.search||i.current.shouldFilter===!1){r.current.filtered.count=s.current.size;return}r.current.filtered.groups=new Set;let pe=0;for(let K of s.current){let Ie=k(($=(L=o.current.get(K))==null?void 0:L.value)!=null?$:"",(ee=(ne=o.current.get(K))==null?void 0:ne.keywords)!=null?ee:[]);r.current.filtered.items.set(K,Ie),Ie>0&&pe++}for(let[K,Ie]of n.current)for(let Pe of Ie)if(r.current.filtered.items.get(Pe)>0){r.current.filtered.groups.add(K);break}r.current.filtered.count=pe}function O(){var L,$,ne;let ee=F();ee&&(((L=ee.parentElement)==null?void 0:L.firstChild)===ee&&((ne=($=ee.closest($s))==null?void 0:$.querySelector(ev))==null||ne.scrollIntoView({block:"nearest"})),ee.scrollIntoView({block:"nearest"}))}function F(){var L;return(L=v.current)==null?void 0:L.querySelector(`${kd}[aria-selected="true"]`)}function E(){var L;return Array.from(((L=v.current)==null?void 0:L.querySelectorAll(wl))||[])}function z(L){let $=E()[L];$&&R.setState("value",$.getAttribute(xs))}function G(L){var $;let ne=F(),ee=E(),pe=ee.findIndex(Ie=>Ie===ne),K=ee[pe+L];($=i.current)!=null&&$.loop&&(K=pe+L<0?ee[ee.length-1]:pe+L===ee.length?ee[0]:ee[pe+L]),K&&R.setState("value",K.getAttribute(xs))}function fe(L){let $=F(),ne=$?.closest($s),ee;for(;ne&&!ee;)ne=L>0?dv(ne,$s):uv(ne,$s),ee=ne?.querySelector(wl);ee?R.setState("value",ee.getAttribute(xs)):G(L)}let Z=()=>z(E().length-1),re=L=>{L.preventDefault(),L.metaKey?Z():L.altKey?fe(1):G(1)},Ne=L=>{L.preventDefault(),L.metaKey?z(0):L.altKey?fe(-1):G(-1)};return f.createElement(Or.div,{ref:t,tabIndex:-1,...N,"cmdk-root":"",onKeyDown:L=>{var $;($=N.onKeyDown)==null||$.call(N,L);let ne=L.nativeEvent.isComposing||L.keyCode===229;if(!(L.defaultPrevented||ne))switch(L.key){case"n":case"j":x&&L.ctrlKey&&re(L);break;case"ArrowDown":re(L);break;case"p":case"k":x&&L.ctrlKey&&Ne(L);break;case"ArrowUp":Ne(L);break;case"Home":L.preventDefault(),z(0);break;case"End":L.preventDefault(),Z();break;case"Enter":{L.preventDefault();let ee=F();if(ee){let pe=new Event(Io);ee.dispatchEvent(pe)}}}}},f.createElement("label",{"cmdk-label":"",htmlFor:I.inputId,id:I.labelId,style:mv},c),ea(e,L=>f.createElement(Od.Provider,{value:R},f.createElement(Ad.Provider,{value:I},L))))}),rv=f.forwardRef((e,t)=>{var r,s;let n=Ns(),o=f.useRef(null),l=f.useContext(Dd),i=mn(),c=_d(e),d=(s=(r=c.current)==null?void 0:r.forceMount)!=null?s:l?.forceMount;ns(()=>{if(!d)return i.item(n,l?.id)},[d]);let u=Pd(n,o,[e.value,e.children,o],e.keywords),h=yi(),m=Er(y=>y.value&&y.value===u.current),p=Er(y=>d||i.filter()===!1?!0:y.search?y.filtered.items.get(n)>0:!0);f.useEffect(()=>{let y=o.current;if(!(!y||e.disabled))return y.addEventListener(Io,b),()=>y.removeEventListener(Io,b)},[p,e.onSelect,e.disabled]);function b(){var y,R;w(),(R=(y=c.current).onSelect)==null||R.call(y,u.current)}function w(){h.setState("value",u.current,!0)}if(!p)return null;let{disabled:x,value:N,onSelect:C,forceMount:S,keywords:g,...v}=e;return f.createElement(Or.div,{ref:an(o,t),...v,id:n,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!m,"data-disabled":!!x,"data-selected":!!m,onPointerMove:x||i.getDisablePointerSelection()?void 0:w,onClick:x?void 0:b},e.children)}),sv=f.forwardRef((e,t)=>{let{heading:r,children:s,forceMount:n,...o}=e,l=Ns(),i=f.useRef(null),c=f.useRef(null),d=Ns(),u=mn(),h=Er(p=>n||u.filter()===!1?!0:p.search?p.filtered.groups.has(l):!0);ns(()=>u.group(l),[]),Pd(l,i,[e.value,e.heading,c]);let m=f.useMemo(()=>({id:l,forceMount:n}),[n]);return f.createElement(Or.div,{ref:an(i,t),...o,"cmdk-group":"",role:"presentation",hidden:h?void 0:!0},r&&f.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},r),ea(e,p=>f.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?d:void 0},f.createElement(Dd.Provider,{value:m},p))))}),nv=f.forwardRef((e,t)=>{let{alwaysRender:r,...s}=e,n=f.useRef(null),o=Er(l=>!l.search);return!r&&!o?null:f.createElement(Or.div,{ref:an(n,t),...s,"cmdk-separator":"",role:"separator"})}),av=f.forwardRef((e,t)=>{let{onValueChange:r,...s}=e,n=e.value!=null,o=yi(),l=Er(d=>d.search),i=Er(d=>d.selectedItemId),c=mn();return f.useEffect(()=>{e.value!=null&&o.setState("search",e.value)},[e.value]),f.createElement(Or.input,{ref:t,...s,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":i,id:c.inputId,type:"text",value:n?e.value:l,onChange:d=>{n||o.setState("search",d.target.value),r?.(d.target.value)}})}),ov=f.forwardRef((e,t)=>{let{children:r,label:s="Suggestions",...n}=e,o=f.useRef(null),l=f.useRef(null),i=Er(d=>d.selectedItemId),c=mn();return f.useEffect(()=>{if(l.current&&o.current){let d=l.current,u=o.current,h,m=new ResizeObserver(()=>{h=requestAnimationFrame(()=>{let p=d.offsetHeight;u.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return m.observe(d),()=>{cancelAnimationFrame(h),m.unobserve(d)}}},[]),f.createElement(Or.div,{ref:an(o,t),...n,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":i,"aria-label":s,id:c.listId},ea(e,d=>f.createElement("div",{ref:an(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),iv=f.forwardRef((e,t)=>{let{open:r,onOpenChange:s,overlayClassName:n,contentClassName:o,container:l,...i}=e;return f.createElement(ui,{open:r,onOpenChange:s},f.createElement(pi,{container:l},f.createElement(hi,{"cmdk-overlay":"",className:n}),f.createElement(mi,{"aria-label":e.label,"cmdk-dialog":"",className:o},f.createElement(Md,{ref:t,...i}))))}),lv=f.forwardRef((e,t)=>Er(r=>r.filtered.count===0)?f.createElement(Or.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),cv=f.forwardRef((e,t)=>{let{progress:r,children:s,label:n="Loading...",...o}=e;return f.createElement(Or.div,{ref:t,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":n},ea(e,l=>f.createElement("div",{"aria-hidden":!0},l)))}),hs=Object.assign(Md,{List:ov,Item:rv,Input:av,Group:sv,Separator:nv,Dialog:iv,Empty:lv,Loading:cv});function dv(e,t){let r=e.nextElementSibling;for(;r;){if(r.matches(t))return r;r=r.nextElementSibling}}function uv(e,t){let r=e.previousElementSibling;for(;r;){if(r.matches(t))return r;r=r.previousElementSibling}}function _d(e){let t=f.useRef(e);return ns(()=>{t.current=e}),t}var ns=typeof window>"u"?f.useEffect:f.useLayoutEffect;function Ss(e){let t=f.useRef();return t.current===void 0&&(t.current=e()),t}function Er(e){let t=yi(),r=()=>e(t.snapshot());return f.useSyncExternalStore(t.subscribe,r,r)}function Pd(e,t,r,s=[]){let n=f.useRef(),o=mn();return ns(()=>{var l;let i=(()=>{var d;for(let u of r){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(d=u.current.textContent)==null?void 0:d.trim():n.current}})(),c=s.map(d=>d.trim());o.value(e,i,c),(l=t.current)==null||l.setAttribute(xs,i),n.current=i}),n}var fv=()=>{let[e,t]=f.useState(),r=Ss(()=>new Map);return ns(()=>{r.current.forEach(s=>s()),r.current=new Map},[e]),(s,n)=>{r.current.set(s,n),t({})}};function hv(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function ea({asChild:e,children:t},r){return e&&f.isValidElement(t)?f.cloneElement(hv(t),{ref:t.ref},r(t.props.children)):r(t)}var mv={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function ta({...e}){return(0,a.jsx)(ui,{"data-slot":"dialog",...e})}function pv({...e}){return(0,a.jsx)(pi,{"data-slot":"dialog-portal",...e})}function gv({className:e,...t}){return(0,a.jsx)(hi,{"data-slot":"dialog-overlay",className:V("data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 bg-black/80 duration-100 supports-backdrop-filter:backdrop-blur-xs fixed inset-0 isolate z-50",e),...t})}function ra({className:e,children:t,showCloseButton:r=!0,...s}){return(0,a.jsxs)(pv,{children:[(0,a.jsx)(gv,{}),(0,a.jsxs)(mi,{"data-slot":"dialog-content",className:V("bg-background data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 ring-foreground/10 grid max-w-[calc(100%-2rem)] gap-4 rounded-xl p-4 text-xs/relaxed ring-1 duration-100 sm:max-w-sm fixed top-1/2 left-1/2 z-50 w-full -translate-x-1/2 -translate-y-1/2",e),...s,children:[(0,a.jsx)(fd.Provider,{value:!0,children:t}),r&&(0,a.jsx)(fi,{"data-slot":"dialog-close",asChild:!0,children:(0,a.jsxs)(B,{variant:"ghost",className:"absolute top-2 right-2",size:"icon-sm",children:[(0,a.jsx)(As,{}),(0,a.jsx)("span",{className:"sr-only",children:"Close"})]})})]})]})}function sa({className:e,...t}){return(0,a.jsx)("div",{"data-slot":"dialog-header",className:V("gap-1 flex flex-col",e),...t})}function bi({className:e,showCloseButton:t=!1,children:r,...s}){return(0,a.jsxs)("div",{"data-slot":"dialog-footer",className:V("gap-2 flex flex-col-reverse sm:flex-row sm:justify-end",e),...s,children:[r,t&&(0,a.jsx)(fi,{asChild:!0,children:(0,a.jsx)(B,{variant:"outline",children:"Close"})})]})}function na({className:e,...t}){return(0,a.jsx)(id,{"data-slot":"dialog-title",className:V("text-sm font-medium",e),...t})}function aa({className:e,...t}){return(0,a.jsx)(ud,{"data-slot":"dialog-description",className:V("text-muted-foreground *:[a]:hover:text-foreground text-xs/relaxed *:[a]:underline *:[a]:underline-offset-3",e),...t})}function xi({className:e,...t}){return(0,a.jsx)(hs,{"data-slot":"command",className:V("bg-popover text-popover-foreground rounded-xl flex size-full flex-col overflow-hidden",e),...t})}function vv({title:e="Command Palette",description:t="Search for a command to run...",children:r,className:s,showCloseButton:n=!1,...o}){return(0,a.jsxs)(ta,{...o,children:[(0,a.jsxs)(sa,{className:"sr-only",children:[(0,a.jsx)(na,{children:e}),(0,a.jsx)(aa,{children:t})]}),(0,a.jsx)(ra,{className:V("rounded-xl! p-0 overflow-hidden",s),showCloseButton:n,children:(0,a.jsx)(xi,{className:"[&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-2 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:r})})]})}function Si({className:e,...t}){return(0,a.jsx)("div",{"data-slot":"command-input-wrapper",className:"p-2 w-full",children:(0,a.jsxs)(Zp,{className:"bg-input/20 dark:bg-input/30 h-8!",children:[(0,a.jsx)(hs.Input,{"data-slot":"command-input",className:V("w-full text-xs/relaxed outline-hidden disabled:cursor-not-allowed disabled:opacity-50",e),...t}),(0,a.jsx)(tg,{children:(0,a.jsx)(ai,{className:"size-3.5 shrink-0 opacity-50"})})]})})}function Ci({className:e,...t}){return(0,a.jsx)(hs.List,{"data-slot":"command-list",className:V("max-h-72 scroll-py-1 outline-none overflow-x-hidden overflow-y-auto",e),...t})}function wi({className:e,...t}){return(0,a.jsx)(hs.Empty,{"data-slot":"command-empty",className:V("py-6 text-center text-xs/relaxed",e),...t})}function vr({className:e,...t}){return(0,a.jsx)(hs.Group,{"data-slot":"command-group",className:V("text-foreground **:[[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",e),...t})}function Vs({className:e,...t}){return(0,a.jsx)(hs.Separator,{"data-slot":"command-separator",className:V("bg-border/50 -mx-1 my-1 h-px",e),...t})}function Ae({className:e,children:t,...r}){return(0,a.jsxs)(hs.Item,{"data-slot":"command-item",className:V("data-selected:bg-muted data-selected:text-foreground data-selected:*:[svg]:text-foreground relative flex min-h-3 cursor-default items-center gap-2 rounded-md px-2.5 py-1.5 text-xs/relaxed outline-hidden select-none [&_svg:not([class*='size-'])]:size-3.5 [[data-slot=dialog-content]_&]:rounded-md group/command-item data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",e),...r,children:[t,(0,a.jsx)(Os,{className:"ml-auto opacity-0 group-has-[[data-slot=command-shortcut]]/command-item:hidden group-data-[checked=true]/command-item:opacity-100"})]})}function yv({className:e,...t}){return(0,a.jsx)("span",{"data-slot":"command-shortcut",className:V("text-muted-foreground group-data-selected/command-item:text-foreground ml-auto text-[0.625rem] tracking-widest",e),...t})}function et({className:e,...t}){return(0,a.jsx)("kbd",{"data-slot":"kbd",className:V("bg-muted text-muted-foreground border [[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10 h-5 w-fit min-w-5 gap-1 rounded-xs px-1 font-sans text-[0.625rem] font-medium [&_svg:not([class*='size-'])]:size-3 pointer-events-none inline-flex items-center justify-center select-none",e),...t})}var bv=Dr()(e=>({pendingPrompt:null,requestAssistant:t=>e({pendingPrompt:t}),consumePrompt:()=>e({pendingPrompt:null})})),xv=()=>{const{selectedDatabase:e}=Me(),{mutateAsync:t,isPending:r}=ht({mutationFn:async n=>{const o=(await Vp(n,e)).data.data.schema;return await navigator.clipboard.writeText(o),o}});return{copyTableSchema:async n=>we.promise(t(n),{loading:"Copying table schema...",success:"Table schema copied to clipboard",error:o=>o.message||"Failed to copy table schema"}),isCopyingSchema:r}},pn=e=>e.type==="checkbox",Wr=e=>e instanceof Date,ft=e=>e==null,Fd=e=>typeof e=="object",Be=e=>!ft(e)&&!Array.isArray(e)&&Fd(e)&&!Wr(e),Ld=e=>Be(e)&&e.target?pn(e.target)?e.target.checked:e.target.value:e,zd=(e,t)=>t.split(".").some((r,s,n)=>!isNaN(Number(r))&&e.has(n.slice(0,s).join("."))),Sv=e=>{const t=e.constructor&&e.constructor.prototype;return Be(t)&&t.hasOwnProperty("isPrototypeOf")},Ni=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Oe(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(Ni&&(e instanceof Blob||t))return e;const r=Array.isArray(e);if(!r&&!(Be(e)&&Sv(e)))return e;const s=r?[]:Object.create(Object.getPrototypeOf(e));for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(s[n]=Oe(e[n]));return s}var oa=e=>/^\w*$/.test(e),Re=e=>e===void 0,ia=e=>Array.isArray(e)?e.filter(Boolean):[],ji=e=>ia(e.replace(/["|']|\]/g,"").split(/\.|\[/)),q=(e,t,r)=>{if(!t||!Be(e))return r;const s=(oa(t)?[t]:ji(t)).reduce((n,o)=>ft(n)?void 0:n[o],e);return Re(s)||s===e?Re(e[t])?r:e[t]:s},Tt=e=>typeof e=="boolean",at=e=>typeof e=="function",Ce=(e,t,r)=>{let s=-1;const n=oa(t)?[t]:ji(t),o=n.length,l=o-1;for(;++s<o;){const i=n[s];let c=r;if(s!==l){const d=e[i];c=Be(d)||Array.isArray(d)?d:isNaN(+n[s+1])?{}:[]}if(i==="__proto__"||i==="constructor"||i==="prototype")return;e[i]=c,e=e[i]}},Ir={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Lt={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Gt={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},Oa="form",$d="root",Ii=f.createContext(null);Ii.displayName="HookFormControlContext";var la=()=>f.useContext(Ii),Vd=(e,t,r,s=!0)=>{const n={};for(const o in e)Object.defineProperty(n,o,{get:()=>{const l=o;return t._proxyFormState[l]!==Lt.all&&(t._proxyFormState[l]=!s||Lt.all),r&&(r[l]=!0),e[l]}});return n},ca=typeof window<"u"?f.useLayoutEffect:f.useEffect;function Cv(e){const t=la(),{control:r=t,disabled:s,name:n,exact:o}=e||{},[l,i]=f.useState(()=>({...r._formState,defaultValues:r._defaultValues})),c=f.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return ca(()=>r._subscribe({name:n,formState:c.current,exact:o,callback:d=>{!s&&i({...r._formState,...d,defaultValues:r._defaultValues})}}),[n,s,o]),f.useEffect(()=>{c.current.isValid&&r._setValid(!0)},[r]),f.useMemo(()=>Vd(l,r,c.current,!1),[l,r])}var ot=e=>typeof e=="string",To=(e,t,r,s,n)=>ot(e)?(s&&t.watch.add(e),q(r,e,n)):Array.isArray(e)?e.map(o=>(s&&t.watch.add(o),q(r,o))):(s&&(t.watchAll=!0),r),Ro=e=>ft(e)||!Fd(e);function Rt(e,t,r=new WeakSet){if(e===t)return!0;if(Ro(e)||Ro(t))return Object.is(e,t);if(Wr(e)&&Wr(t))return Object.is(e.getTime(),t.getTime());const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;if(r.has(e)||r.has(t))return!0;r.add(e),r.add(t);for(const o of s){const l=e[o];if(!(o in t))return!1;if(o!=="ref"){const i=t[o];if(Wr(l)&&Wr(i)||(Be(l)||Array.isArray(l))&&(Be(i)||Array.isArray(i))?!Rt(l,i,r):!Object.is(l,i))return!1}}return!0}function Ft(e){const t=la(),{control:r=t,name:s,defaultValue:n,disabled:o,exact:l,compute:i}=e||{},c=f.useRef(n),d=f.useRef(i),u=f.useRef(void 0),h=f.useRef(r),m=f.useRef(s);d.current=i;const[p,b]=f.useState(()=>{const g=r._getWatch(s,c.current);return d.current?d.current(g):g}),w=f.useCallback(g=>{const v=To(s,r._names,g||r._formValues,!1,c.current);return d.current?d.current(v):v},[r._formValues,r._names,s]),x=f.useCallback(g=>{if(!o){const v=To(s,r._names,g||r._formValues,!1,c.current);if(d.current){const y=d.current(v);Rt(y,u.current)||(b(y),u.current=y)}else b(v)}},[r._formValues,r._names,o,s]);ca(()=>((h.current!==r||!Rt(m.current,s))&&(h.current=r,m.current=s,x()),r._subscribe({name:s,formState:{values:!0},exact:l,callback:g=>{x(g.values)}})),[r,l,s,x]),f.useEffect(()=>r._removeUnmounted());const N=h.current!==r,C=m.current,S=f.useMemo(()=>{if(o)return null;const g=!N&&!Rt(C,s);return N||g?w():null},[o,N,s,C,w]);return S!==null?S:p}function wv(e){const t=la(),{name:r,disabled:s,control:n=t,shouldUnregister:o,defaultValue:l,exact:i=!0}=e,c=zd(n._names.array,r),d=Ft({control:n,name:r,defaultValue:f.useMemo(()=>q(n._formValues,r,q(n._defaultValues,r,l)),[n,r,l]),exact:i}),u=Cv({control:n,name:r,exact:i}),h=f.useRef(e),m=f.useRef(n.register(r,{...e.rules,value:d,...Tt(e.disabled)?{disabled:e.disabled}:{}}));h.current=e;const p=f.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!q(u.errors,r)},isDirty:{enumerable:!0,get:()=>!!q(u.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!q(u.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!q(u.validatingFields,r)},error:{enumerable:!0,get:()=>q(u.errors,r)}}),[u,r]),b=f.useCallback(C=>m.current.onChange({target:{value:Ld(C),name:r},type:Ir.CHANGE}),[r]),w=f.useCallback(()=>m.current.onBlur({target:{value:q(n._formValues,r),name:r},type:Ir.BLUR}),[r,n._formValues]),x=f.useCallback(C=>{const S=q(n._fields,r);S&&S._f&&C&&(S._f.ref={focus:()=>at(C.focus)&&C.focus(),select:()=>at(C.select)&&C.select(),setCustomValidity:g=>at(C.setCustomValidity)&&C.setCustomValidity(g),reportValidity:()=>at(C.reportValidity)&&C.reportValidity()})},[n._fields,r]),N=f.useMemo(()=>({name:r,value:d,...Tt(s)||u.disabled?{disabled:u.disabled||s}:{},onChange:b,onBlur:w,ref:x}),[r,s,u.disabled,b,w,x,d]);return f.useEffect(()=>{const C=n._options.shouldUnregister||o;n.register(r,{...h.current.rules,...Tt(h.current.disabled)?{disabled:h.current.disabled}:{}});const S=(g,v)=>{const y=q(n._fields,g);y&&y._f&&(y._f.mount=v)};if(S(r,!0),C){const g=Oe(q(n._options.defaultValues,r,h.current.defaultValue));Ce(n._defaultValues,r,g),Re(q(n._formValues,r))&&Ce(n._formValues,r,g)}return!c&&n.register(r),()=>{(c?C&&!n._state.action:C)?n.unregister(r):S(r,!1)}},[r,n,c,o]),f.useEffect(()=>{n._setDisabledField({disabled:s,name:r})},[s,r,n]),f.useMemo(()=>({field:N,formState:u,fieldState:p}),[N,u,p])}var Ot=e=>e.render(wv(e)),Ti=f.createContext(null);Ti.displayName="HookFormContext";var Ge=()=>f.useContext(Ti),Ds=e=>{const{children:t,watch:r,getValues:s,getFieldState:n,setError:o,clearErrors:l,setValue:i,setValues:c,trigger:d,formState:u,resetField:h,reset:m,handleSubmit:p,unregister:b,control:w,register:x,setFocus:N,subscribe:C}=e,S=f.useMemo(()=>({watch:r,getValues:s,getFieldState:n,setError:o,clearErrors:l,setValue:i,setValues:c,trigger:d,formState:u,resetField:h,reset:m,handleSubmit:p,unregister:b,control:w,register:x,setFocus:N,subscribe:C}),[l,w,u,n,s,p,x,m,h,o,N,i,c,C,d,b,r]);return f.createElement(Ti.Provider,{value:S},f.createElement(Ii.Provider,{value:S.control},t))},Ri=(e,t,r,s,n)=>t?{...r[e],types:{...r[e]&&r[e].types?r[e].types:{},[s]:n||!0}}:{},xt=e=>Array.isArray(e)?e:[e],Nl=()=>{let e=[];return{get observers(){return e},next:n=>{for(const o of e)o.next&&o.next(n)},subscribe:n=>(e.push(n),{unsubscribe:()=>{e=e.filter(o=>o!==n)}}),unsubscribe:()=>{e=[]}}};function Bd(e,t){const r={};for(const s in e)if(e.hasOwnProperty(s)){const n=e[s],o=t[s];if(n&&Be(n)&&o){const l=Bd(n,o);Be(l)&&(r[s]=l)}else e[s]&&(r[s]=o)}return r}var tt=e=>Be(e)&&!Object.keys(e).length,Ei=e=>e.type==="file",Bn=e=>{if(!Ni)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Ud=e=>e.type==="select-multiple",ki=e=>e.type==="radio",Nv=e=>ki(e)||pn(e),Da=e=>Bn(e)&&e.isConnected;function jv(e,t){const r=t.slice(0,-1).length;let s=0;for(;s<r;){if(ft(e)){e=void 0;break}e=e[t[s]],s++}return e}function Iv(e){for(const t in e)if(e.hasOwnProperty(t)&&!Re(e[t]))return!1;return!0}function qe(e,t){if(ot(t)&&Object.prototype.hasOwnProperty.call(e,t))return delete e[t],e;const r=Array.isArray(t)?t:oa(t)?[t]:ji(t),s=r.length===1?e:jv(e,r),n=r.length-1,o=r[n];return s&&delete s[o],n!==0&&(Be(s)&&tt(s)||Array.isArray(s)&&Iv(s))&&qe(e,r.slice(0,-1)),e}var Tv=e=>{for(const t in e)if(at(e[t]))return!0;return!1};function qd(e){return Array.isArray(e)||Be(e)&&!Tv(e)}function Eo(e,t={}){for(const r in e){const s=e[r];qd(s)?(t[r]=Array.isArray(s)?[]:{},Eo(s,t[r])):Re(s)||(t[r]=!0)}return t}function ko(e){if(e!==!1){if(e===!0)return!0;if(Array.isArray(e)){const t=e.map(r=>ko(r));return t.some(r=>r!==void 0)?t:void 0}if(Be(e)){const t={};for(const r in e){const s=ko(e[r]);Re(s)||(t[r]=s)}return Object.keys(t).length?t:void 0}}}function Ys(e,t,r){r||(r=Eo(t));for(const s in e){const n=e[s];if(qd(n))Re(t)||Ro(r[s])?r[s]=Eo(n,Array.isArray(n)?[]:{}):Ys(n,ft(t)?{}:t[s],r[s]);else{const o=t[s];r[s]=!Rt(n,o)}}return ko(r)||{}}var jl={value:!1,isValid:!1},Il={value:!0,isValid:!0},Wd=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Re(e[0].attributes.value)?Re(e[0].value)||e[0].value===""?Il:{value:e[0].value,isValid:!0}:Il:jl}return jl},Kd=(e,{valueAsNumber:t,valueAsDate:r,setValueAs:s})=>Re(e)?e:t?e===""?NaN:e&&+e:r&&ot(e)?new Date(e):s?s(e):e,Tl={isValid:!1,value:null},Hd=e=>Array.isArray(e)?e.reduce((t,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:t,Tl):Tl;function Rl(e){const t=e.ref;return Ei(t)?t.files:ki(t)?Hd(e.refs).value:Ud(t)?[...t.selectedOptions].map(({value:r})=>r):pn(t)?Wd(e.refs).value:Kd(Re(t.value)?e.ref.value:t.value,e)}var Rv=(e,t,r,s)=>{const n={};for(const o of e){const l=q(t,o);l&&Ce(n,o,l._f)}return{criteriaMode:r,names:[...e],fields:n,shouldUseNativeValidation:s}},Un=e=>e instanceof RegExp,Bs=e=>Re(e)?e:Un(e)?e.source:Be(e)?Un(e.value)?e.value.source:e.value:e,ws=e=>({isOnSubmit:!e||e===Lt.onSubmit,isOnBlur:e===Lt.onBlur,isOnChange:e===Lt.onChange,isOnAll:e===Lt.all,isOnTouch:e===Lt.onTouched}),El="AsyncFunction",Ev=e=>!!e&&!!e.validate&&!!(at(e.validate)&&e.validate.constructor.name===El||Be(e.validate)&&Object.values(e.validate).find(t=>t.constructor.name===El)),kv=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate),Ao=(e,t,r)=>!r&&(t.watchAll||t.watch.has(e)||[...t.watch].some(s=>e.startsWith(s)&&/^\.\w+/.test(e.slice(s.length)))),js=(e,t,r,s)=>{for(const n of r||Object.keys(e)){const o=q(e,n);if(o){const{_f:l,...i}=o;if(l){if(l.refs&&l.refs[0]&&t(l.refs[0],n)&&!s)return!0;if(l.ref&&t(l.ref,l.name)&&!s)return!0;if(js(i,t))break}else if(Be(i)&&js(i,t))break}}};function kl(e,t,r){const s=q(e,r);if(s||oa(r))return{error:s,name:r};const n=r.split(".");for(;n.length;){const o=n.join("."),l=q(t,o),i=q(e,o);if(l&&!Array.isArray(l)&&r!==o)return{name:r};if(i&&i.type)return{name:o,error:i};if(i&&i.root&&i.root.type)return{name:`${o}.root`,error:i.root};n.pop()}return{name:r}}var Av=(e,t,r,s)=>{r(e);const{name:n,...o}=e;return tt(o)||s&&Object.keys(o).length>=Object.keys(t).length||Object.keys(o).find(l=>t[l]===(!s||Lt.all))},Ov=(e,t,r)=>!e||!t||e===t||xt(e).some(s=>s&&(r?s===t:s.startsWith(t)||t.startsWith(s))),Dv=(e,t,r,s,n)=>n.isOnAll?!1:!r&&n.isOnTouch?!(t||e):(r?s.isOnBlur:n.isOnBlur)?!e:(r?s.isOnChange:n.isOnChange)?e:!0,Mv=(e,t)=>!ia(q(e,t)).length&&qe(e,t),Gd=(e,t,r)=>{const s=xt(q(e,r));return Ce(s,$d,t[r]),Ce(e,r,s),e};function Al(e,t,r="validate"){if(ot(e)||Array.isArray(e)&&e.every(ot)||Tt(e)&&!e)return{type:r,message:ot(e)?e:"",ref:t}}var vs=e=>Be(e)&&!Un(e)?e:{value:e,message:""},Oo=async(e,t,r,s,n,o)=>{const{ref:l,refs:i,required:c,maxLength:d,minLength:u,min:h,max:m,pattern:p,validate:b,name:w,valueAsNumber:x,mount:N}=e._f,C=q(r,w);if(!N||t.has(w))return{};const S=i?i[0]:l,g=_=>{n&&S.reportValidity&&(S.setCustomValidity(Tt(_)?"":_||""),S.reportValidity())},v={},y=ki(l),R=pn(l),I=y||R,k=(x||Ei(l))&&Re(l.value)&&Re(C)||Bn(l)&&l.value===""||C===""||Array.isArray(C)&&!C.length||x&&typeof C=="number"&&isNaN(C),T=Ri.bind(null,w,s,v),D=(_,O,F,E=Gt.maxLength,z=Gt.minLength)=>{const G=_?O:F;v[w]={type:_?E:z,message:G,ref:l,...T(_?E:z,G)}};if(o?!Array.isArray(C)||!C.length:c&&(!I&&(k||ft(C))||Tt(C)&&!C||R&&!Wd(i).isValid||y&&!Hd(i).isValid)){const{value:_,message:O}=ot(c)?{value:!!c,message:c}:vs(c);if(_&&(v[w]={type:Gt.required,message:O,ref:S,...T(Gt.required,O)},!s))return g(O),v}if(!k&&(!ft(h)||!ft(m))){let _,O;const F=vs(m),E=vs(h);if(!ft(C)&&!isNaN(C)){const z=l.valueAsNumber||C&&+C;ft(F.value)||(_=z>F.value),ft(E.value)||(O=z<E.value)}else{const z=l.valueAsDate||new Date(C),G=re=>new Date(new Date().toDateString()+" "+re),fe=l.type=="time",Z=l.type=="week";ot(F.value)&&C&&(_=fe?G(C)>G(F.value):Z?C>F.value:z>new Date(F.value)),ot(E.value)&&C&&(O=fe?G(C)<G(E.value):Z?C<E.value:z<new Date(E.value))}if((_||O)&&(D(!!_,F.message,E.message,Gt.max,Gt.min),!s))return g(v[w].message),v}if((d||u)&&!k&&(ot(C)||o&&Array.isArray(C))){const _=vs(d),O=vs(u),F=!ft(_.value)&&C.length>+_.value,E=!ft(O.value)&&C.length<+O.value;if((F||E)&&(D(F,_.message,O.message),!s))return g(v[w].message),v}if(p&&!k&&ot(C)){const{value:_,message:O}=vs(p);if(Un(_)&&!C.match(_)&&(v[w]={type:Gt.pattern,message:O,ref:l,...T(Gt.pattern,O)},!s))return g(O),v}if(b){if(at(b)){const _=Al(await b(C,r),S);if(_&&(v[w]={..._,...T(Gt.validate,_.message)},!s))return g(_.message),v}else if(Be(b)){let _={};for(const O in b){if(!tt(_)&&!s)break;const F=Al(await b[O](C,r),S,O);F&&(_={...F,...T(O,F.message)},g(F.message),s&&(v[w]=_))}if(!tt(_)&&(v[w]={ref:S,..._},!s))return v}}return g(!0),v},_v={mode:Lt.onSubmit,reValidateMode:Lt.onChange,shouldFocusError:!0},Yd={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function Pv(e={}){let t={..._v,...e},r={...Oe(Yd),isLoading:at(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},s={},n=Be(t.defaultValues)||Be(t.values)?Oe(t.defaultValues||t.values)||{}:{},o=t.shouldUnregister?{}:Oe(n),l={action:!1,mount:!1,watch:!1,keepIsValid:!1},i={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set},c,d=0;const u={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},h={...u};let m={...h};const p={array:Nl(),state:Nl()},b=t.criteriaMode===Lt.all,w=j=>A=>{clearTimeout(d),d=setTimeout(j,A)},x=async j=>{if(!l.keepIsValid&&!t.disabled&&(h.isValid||m.isValid||j)){let A;t.resolver?(A=tt((await k()).errors),N()):A=await _({fields:s,onlyCheckValid:!0,eventType:Ir.VALID}),A!==r.isValid&&p.state.next({isValid:A})}},N=(j,A)=>{!t.disabled&&(h.isValidating||h.validatingFields||m.isValidating||m.validatingFields)&&((j||Array.from(i.mount)).forEach(M=>{M&&(A?Ce(r.validatingFields,M,A):qe(r.validatingFields,M))}),p.state.next({validatingFields:r.validatingFields,isValidating:!tt(r.validatingFields)}))},C=()=>{r.dirtyFields=Ys(n,o)},S=(j,A=[],M,W,H=!0,U=!0)=>{if(W&&M&&!t.disabled){if(l.action=!0,U&&Array.isArray(q(s,j))){const J=M(q(s,j),W.argA,W.argB);H&&Ce(s,j,J)}if(U&&Array.isArray(q(r.errors,j))){const J=M(q(r.errors,j),W.argA,W.argB);H&&Ce(r.errors,j,J),Mv(r.errors,j)}if((h.touchedFields||m.touchedFields)&&U&&Array.isArray(q(r.touchedFields,j))){const J=M(q(r.touchedFields,j),W.argA,W.argB);H&&Ce(r.touchedFields,j,J)}(h.dirtyFields||m.dirtyFields)&&C(),p.state.next({name:j,isDirty:F(j,A),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else Ce(o,j,A)},g=(j,A)=>{Ce(r.errors,j,A),p.state.next({errors:r.errors})},v=j=>{r.errors=j,p.state.next({errors:r.errors,isValid:!1})},y=(j,A,M,W)=>{const H=q(s,j);if(H){const U=Re(q(o,j)),J=q(o,j,Re(M)?q(n,j):M);Re(J)||W&&W.defaultChecked||A?Ce(o,j,A?J:Rl(H._f)):G(j,J),l.mount&&!l.action&&(x(),U&&r.isDirty&&(h.isDirty||m.isDirty)&&(F()||(r.isDirty=!1,p.state.next({...r}))))}},R=(j,A,M,W,H)=>{let U=!1,J=!1;const ae={name:j};if(!t.disabled){if(!M||W){(h.isDirty||m.isDirty)&&(J=r.isDirty,r.isDirty=ae.isDirty=F(),U=J!==ae.isDirty);const xe=Rt(q(n,j),A);J=!!q(r.dirtyFields,j),xe?qe(r.dirtyFields,j):Ce(r.dirtyFields,j,!0),ae.dirtyFields=r.dirtyFields,U=U||(h.dirtyFields||m.dirtyFields)&&J!==!xe}if(M){const xe=q(r.touchedFields,j);xe||(Ce(r.touchedFields,j,M),ae.touchedFields=r.touchedFields,U=U||(h.touchedFields||m.touchedFields)&&xe!==M)}U&&H&&p.state.next(ae)}return U?ae:{}},I=(j,A,M,W)=>{const H=q(r.errors,j),U=(h.isValid||m.isValid)&&Tt(A)&&r.isValid!==A;if(t.delayError&&M?(c=w(()=>g(j,M)),c(t.delayError)):(clearTimeout(d),c=null,M?Ce(r.errors,j,M):qe(r.errors,j)),(M?!Rt(H,M):H)||!tt(W)||U){const J={...W,...U&&Tt(A)?{isValid:A}:{},errors:r.errors,name:j};r={...r,...J},p.state.next(J)}},k=async j=>(N(j,!0),await t.resolver(o,t.context,Rv(j||i.mount,s,t.criteriaMode,t.shouldUseNativeValidation))),T=async j=>{const{errors:A}=await k(j);if(N(j),j)for(const M of j){const W=q(A,M);W?Ce(r.errors,M,W):qe(r.errors,M)}else r.errors=A;return A},D=async({name:j,eventType:A})=>{if(e.validate){const M=await e.validate({formValues:o,formState:r,name:j,eventType:A});if(Be(M))for(const W in M)M[W]&&K(`${Oa}.${W}`,{message:ot(M.message)?M.message:"",type:Gt.validate});else ot(M)||!M?K(Oa,{message:M||"",type:Gt.validate}):pe(Oa);return M}return!0},_=async({fields:j,onlyCheckValid:A,name:M,eventType:W,context:H={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(H.runRootValidation=!0,!await D({name:M,eventType:W})&&(H.valid=!1,A)))return H.valid;for(const U in j){const J=j[U];if(J){const{_f:ae,...xe}=J;if(ae){const Je=i.array.has(ae.name),vt=J._f&&Ev(J._f);vt&&h.validatingFields&&N([ae.name],!0);const Ze=await Oo(J,i.disabled,o,b,t.shouldUseNativeValidation&&!A,Je);if(vt&&h.validatingFields&&N([ae.name]),Ze[ae.name]&&(H.valid=!1,A)||(!A&&(q(Ze,ae.name)?Je?Gd(r.errors,Ze,ae.name):Ce(r.errors,ae.name,Ze[ae.name]):qe(r.errors,ae.name)),e.shouldUseNativeValidation&&Ze[ae.name]))break}!tt(xe)&&await _({context:H,onlyCheckValid:A,fields:xe,name:U,eventType:W})}}return H.valid},O=()=>{for(const j of i.unMount){const A=q(s,j);A&&(A._f.refs?A._f.refs.every(M=>!Da(M)):!Da(A._f.ref))&&Ye(j)}i.unMount=new Set},F=(j,A)=>!t.disabled&&(j&&A&&Ce(o,j,A),!Rt(ne(),n)),E=(j,A,M)=>To(j,i,{...l.mount?o:Re(A)?n:ot(j)?{[j]:A}:A},M,A),z=j=>ia(q(l.mount?o:n,j,t.shouldUnregister?q(n,j,[]):[])),G=(j,A,M={})=>{const W=q(s,j);let H=A;if(W){const U=W._f;U&&(!U.disabled&&Ce(o,j,Kd(A,U)),H=Bn(U.ref)&&ft(A)?"":A,Ud(U.ref)?[...U.ref.options].forEach(J=>J.selected=H.includes(J.value)):U.refs?pn(U.ref)?U.refs.forEach(J=>{(!J.defaultChecked||!J.disabled)&&(Array.isArray(H)?J.checked=!!H.find(ae=>ae===J.value):J.checked=H===J.value||!!H)}):U.refs.forEach(J=>J.checked=J.value===H):Ei(U.ref)?U.ref.value="":(U.ref.value=H,U.ref.type||p.state.next({name:j,values:Oe(o)})))}(M.shouldDirty||M.shouldTouch)&&R(j,H,M.shouldTouch,M.shouldDirty,!0),M.shouldValidate&&$(j)},fe=(j,A,M)=>{for(const W in A){if(!A.hasOwnProperty(W))return;const H=A[W],U=j+"."+W,J=q(s,U);(i.array.has(j)||Be(H)||J&&!J._f)&&!Wr(H)?fe(U,H,M):G(U,H,M)}},Z=(j,A,M={})=>{const W=q(s,j),H=i.array.has(j),U=Oe(A),J=Rt(q(o,j),U);if(Ce(o,j,U),H)p.array.next({name:j,values:Oe(o)}),(h.isDirty||h.dirtyFields||m.isDirty||m.dirtyFields)&&M.shouldDirty&&(C(),p.state.next({name:j,dirtyFields:r.dirtyFields,isDirty:F(j,U)}));else{const ae=Array.isArray(U)&&!U.length||tt(U);!W||W._f||ft(U)||ae?G(j,U,M):fe(j,U,M)}if(!J){const ae=Ao(j,i);p.state.next({...ae&&r,name:l.mount||ae?j:void 0,values:Oe(o)})}},re=j=>{const A=at(j)?j(o):j;Rt(o,A)||(o={...o,...A},p.state.next({...r,values:o}))},Ne=async j=>{l.mount=!0;const A=j.target;let M=A.name,W=!0;const H=q(s,M),U=xe=>{W=Number.isNaN(xe)||Wr(xe)&&isNaN(xe.getTime())||Rt(xe,q(o,M,xe))},J=ws(t.mode),ae=ws(t.reValidateMode);if(H){let xe,Je;const vt=A.type?Rl(H._f):Ld(j),Ze=j.type===Ir.BLUR||j.type===Ir.FOCUS_OUT,Ls=!kv(H._f)&&!e.validate&&!t.resolver&&!q(r.errors,M)&&!H._f.deps||Dv(Ze,q(r.touchedFields,M),r.isSubmitted,ae,J),wr=Ao(M,i,Ze);Ce(o,M,vt),Ze?(!A||!A.readOnly)&&(H._f.onBlur&&H._f.onBlur(j),c&&c(0)):H._f.onChange&&H._f.onChange(j);const se=R(M,vt,Ze),Se=!tt(se)||wr;if(!Ze&&p.state.next({name:M,type:j.type,values:Oe(o)}),Ls)return(h.isValid||m.isValid)&&(t.mode==="onBlur"?Ze&&x():Ze||x()),Se&&p.state.next({name:M,...wr?{}:se});if(!t.resolver&&e.validate&&await D({name:M,eventType:j.type}),!Ze&&wr&&p.state.next({...r}),t.resolver){const{errors:Y}=await k([M]);if(N([M]),U(vt),W){const Q=kl(r.errors,s,M),te=kl(Y,s,Q.name||M);xe=te.error,M=te.name,Je=tt(Y)}}else N([M],!0),xe=(await Oo(H,i.disabled,o,b,t.shouldUseNativeValidation))[M],N([M]),U(vt),W&&(xe?Je=!1:(h.isValid||m.isValid)&&(Je=await _({fields:s,onlyCheckValid:!0,name:M,eventType:j.type})));W&&(H._f.deps&&(!Array.isArray(H._f.deps)||H._f.deps.length>0)&&$(H._f.deps),I(M,Je,xe,se))}},L=(j,A)=>{if(q(r.errors,A)&&j.focus)return j.focus(),1},$=async(j,A={})=>{let M,W;const H=xt(j);if(t.resolver){const U=await T(Re(j)?j:H);M=tt(U),W=j?!H.some(J=>q(U,J)):M}else j?(W=(await Promise.all(H.map(async U=>{const J=q(s,U);return await _({fields:J&&J._f?{[U]:J}:J,eventType:Ir.TRIGGER})}))).every(Boolean),!(!W&&!r.isValid)&&x()):W=M=await _({fields:s,name:j,eventType:Ir.TRIGGER});return p.state.next({...!ot(j)||(h.isValid||m.isValid)&&M!==r.isValid?{}:{name:j},...t.resolver||!j?{isValid:M}:{},errors:r.errors}),A.shouldFocus&&!W&&js(s,L,j?H:i.mount),W},ne=(j,A)=>{let M={...l.mount?o:n};return A&&(M=Bd(A.dirtyFields?r.dirtyFields:r.touchedFields,M)),Re(j)?M:ot(j)?q(M,j):j.map(W=>q(M,W))},ee=(j,A)=>({invalid:!!q((A||r).errors,j),isDirty:!!q((A||r).dirtyFields,j),error:q((A||r).errors,j),isValidating:!!q(r.validatingFields,j),isTouched:!!q((A||r).touchedFields,j)}),pe=j=>{const A=j?xt(j):void 0;A?.forEach(M=>qe(r.errors,M)),A?A.forEach(M=>{p.state.next({name:M,errors:r.errors})}):p.state.next({errors:{}})},K=(j,A,M)=>{const W=(q(s,j,{_f:{}})._f||{}).ref,{ref:H,message:U,type:J,...ae}=q(r.errors,j)||{};Ce(r.errors,j,{...ae,...A,ref:W}),p.state.next({name:j,errors:r.errors,isValid:!1}),M&&M.shouldFocus&&W&&W.focus&&W.focus()},Ie=(j,A)=>at(j)?p.state.subscribe({next:M=>"values"in M&&j(M.values||E(void 0,A),M)}):E(j,A,!0),Pe=j=>p.state.subscribe({next:A=>{if(Ov(j.name,A.name,j.exact)&&Av(A,j.formState||h,Ue,j.reRenderRoot)){const M={...o};j.callback({values:M,...r,...A,defaultValues:n})}}}).unsubscribe,pt=j=>(l.mount=!0,m={...m,...j.formState},Pe({...j,formState:{...u,...j.formState}})),Ye=(j,A={})=>{for(const M of j?xt(j):i.mount)i.mount.delete(M),i.array.delete(M),A.keepValue||(qe(s,M),qe(o,M)),!A.keepError&&qe(r.errors,M),!A.keepDirty&&qe(r.dirtyFields,M),!A.keepTouched&&qe(r.touchedFields,M),!A.keepIsValidating&&qe(r.validatingFields,M),!t.shouldUnregister&&!A.keepDefaultValue&&qe(n,M);p.state.next({values:Oe(o)}),p.state.next({...r,...A.keepDirty?{isDirty:F()}:{}}),!A.keepIsValid&&x()},st=({disabled:j,name:A})=>{if(Tt(j)&&l.mount||j||i.disabled.has(A)){const M=i.disabled.has(A)!==!!j;j?i.disabled.add(A):i.disabled.delete(A),M&&l.mount&&!l.action&&x()}},Zt=(j,A={})=>{let M=q(s,j);const W=Tt(A.disabled)||Tt(t.disabled),H=!i.registerName.has(j)&&M&&M._f&&!M._f.mount;return Ce(s,j,{...M||{},_f:{...M&&M._f?M._f:{ref:{name:j}},name:j,mount:!0,...A}}),i.mount.add(j),M&&!H?st({disabled:Tt(A.disabled)?A.disabled:t.disabled,name:j}):y(j,!0,A.value),{...W?{disabled:A.disabled||t.disabled}:{},...t.progressive?{required:!!A.required,min:Bs(A.min),max:Bs(A.max),minLength:Bs(A.minLength),maxLength:Bs(A.maxLength),pattern:Bs(A.pattern)}:{},name:j,onChange:Ne,onBlur:Ne,ref:U=>{if(U){i.registerName.add(j),Zt(j,A),i.registerName.delete(j),M=q(s,j);const J=Re(U.value)&&U.querySelectorAll&&U.querySelectorAll("input,select,textarea")[0]||U,ae=Nv(J),xe=M._f.refs||[];if(ae?xe.find(Je=>Je===J):J===M._f.ref)return;Ce(s,j,{_f:{...M._f,...ae?{refs:[...xe.filter(Da),J,...Array.isArray(q(n,j))?[{}]:[]],ref:{type:J.type,name:j}}:{ref:J}}}),y(j,!1,void 0,J)}else M=q(s,j,{}),M._f&&(M._f.mount=!1),(t.shouldUnregister||A.shouldUnregister)&&!(zd(i.array,j)&&l.action)&&i.unMount.add(j)}}},oe=()=>t.shouldFocusError&&js(s,L,i.mount),he=j=>{Tt(j)&&(p.state.next({disabled:j}),js(s,(A,M)=>{const W=q(s,M);W&&(A.disabled=W._f.disabled||j,Array.isArray(W._f.refs)&&W._f.refs.forEach(H=>{H.disabled=W._f.disabled||j}))},0,!1))},ie=(j,A)=>async M=>{let W;M&&(M.preventDefault&&M.preventDefault(),M.persist&&M.persist());let H=Oe(o);if(p.state.next({isSubmitting:!0}),t.resolver){const{errors:U,values:J}=await k();N(),r.errors=U,H=Oe(J)}else await _({fields:s,eventType:Ir.SUBMIT});if(i.disabled.size)for(const U of i.disabled)qe(H,U);if(qe(r.errors,$d),tt(r.errors)){p.state.next({errors:{}});try{await j(H,M)}catch(U){W=U}}else A&&await A({...r.errors},M),oe(),setTimeout(oe);if(p.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:tt(r.errors)&&!W,submitCount:r.submitCount+1,errors:r.errors}),W)throw W},gt=(j,A={})=>{q(s,j)&&(Re(A.defaultValue)?Z(j,Oe(q(n,j))):(Z(j,A.defaultValue),Ce(n,j,Oe(A.defaultValue))),A.keepTouched||qe(r.touchedFields,j),A.keepDirty||(qe(r.dirtyFields,j),r.isDirty=A.defaultValue?F(j,Oe(q(n,j))):F()),A.keepError||(qe(r.errors,j),h.isValid&&x()),p.state.next({...r}))},Nt=(j,A={})=>{const M=j?Oe(j):n,W=Oe(M),H=tt(j),U=H?n:W;if(A.keepDefaultValues||(n=M),!A.keepValues){if(A.keepDirtyValues){const J=new Set([...i.mount,...Object.keys(Ys(n,o))]);for(const ae of Array.from(J)){const xe=q(r.dirtyFields,ae),Je=q(o,ae),vt=q(U,ae);xe&&!Re(Je)?Ce(U,ae,Je):!xe&&!Re(vt)&&Z(ae,vt)}}else{if(Ni&&Re(j))for(const J of i.mount){const ae=q(s,J);if(ae&&ae._f){const xe=Array.isArray(ae._f.refs)?ae._f.refs[0]:ae._f.ref;if(Bn(xe)){const Je=xe.closest("form");if(Je){Je.reset();break}}}}if(A.keepFieldsRef)for(const J of i.mount)Z(J,q(U,J));else s={}}o=t.shouldUnregister?A.keepDefaultValues?Oe(n):{}:Oe(U),p.array.next({values:{...U}}),p.state.next({values:{...U}})}i={mount:A.keepDirtyValues?i.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!h.isValid||!!A.keepIsValid||!!A.keepDirtyValues||!t.shouldUnregister&&!tt(U),l.watch=!!t.shouldUnregister,l.keepIsValid=!!A.keepIsValid,l.action=!1,A.keepErrors||(r.errors={}),p.state.next({submitCount:A.keepSubmitCount?r.submitCount:0,isDirty:H?!1:A.keepDirty?r.isDirty:!!(A.keepDefaultValues&&!Rt(j,n)),isSubmitted:A.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:H?{}:A.keepDirtyValues?A.keepDefaultValues&&o?Ys(n,o):r.dirtyFields:A.keepDefaultValues&&j?Ys(n,j):A.keepDirty?r.dirtyFields:{},touchedFields:A.keepTouched?r.touchedFields:{},errors:A.keepErrors?r.errors:{},isSubmitSuccessful:A.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:n})},nt=(j,A)=>Nt(at(j)?j(o):j,{...t.resetOptions,...A}),er=(j,A={})=>{const M=q(s,j),W=M&&M._f;if(W){const H=W.refs?W.refs[0]:W.ref;H.focus&&setTimeout(()=>{H.focus(),A.shouldSelect&&at(H.select)&&H.select()})}},Ue=j=>{r={...r,...j}},de={control:{register:Zt,unregister:Ye,getFieldState:ee,handleSubmit:ie,setError:K,_subscribe:Pe,_runSchema:k,_updateIsValidating:N,_focusError:oe,_getWatch:E,_getDirty:F,_setValid:x,_setFieldArray:S,_setDisabledField:st,_setErrors:v,_getFieldArray:z,_reset:Nt,_resetDefaultValues:()=>at(t.defaultValues)&&t.defaultValues().then(j=>{nt(j,t.resetOptions),p.state.next({isLoading:!1})}),_removeUnmounted:O,_disableForm:he,_subjects:p,_proxyFormState:h,get _fields(){return s},get _formValues(){return o},get _state(){return l},set _state(j){l=j},get _defaultValues(){return n},get _names(){return i},set _names(j){i=j},get _formState(){return r},get _options(){return t},set _options(j){t={...t,...j}}},subscribe:pt,trigger:$,register:Zt,handleSubmit:ie,watch:Ie,setValue:Z,setValues:re,getValues:ne,reset:nt,resetField:gt,clearErrors:pe,unregister:Ye,setError:K,setFocus:er,getFieldState:ee};return{...de,formControl:de}}var Nr=()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();const e=typeof performance>"u"?Date.now():performance.now()*1e3;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const r=(Math.random()*16+e)%16|0;return(t=="x"?r:r&3|8).toString(16)})},Ma=(e,t,r={})=>r.shouldFocus||Re(r.shouldFocus)?r.focusName||`${e}.${Re(r.focusIndex)?t:r.focusIndex}.`:"",_a=(e,t)=>[...e,...xt(t)],Pa=e=>Array.isArray(e)?e.map(()=>{}):void 0;function Fa(e,t,r){return[...e.slice(0,t),...xt(r),...e.slice(t)]}var La=(e,t,r)=>Array.isArray(e)?(Re(e[r])&&(e[r]=void 0),e.splice(r,0,e.splice(t,1)[0]),e):[],za=(e,t)=>[...xt(t),...xt(e)];function Fv(e,t){let r=0;const s=[...e];for(const n of t)s.splice(n-r,1),r++;return ia(s).length?s:[]}var $a=(e,t)=>Re(t)?[]:Fv(e,xt(t).sort((r,s)=>r-s)),Va=(e,t,r)=>{[e[t],e[r]]=[e[r],e[t]]},Ol=(e,t,r)=>(e[t]=r,e);function Do(e){const t=la(),{control:r=t,name:s,keyName:n="id",shouldUnregister:o,rules:l}=e,[i,c]=f.useState(r._getFieldArray(s)),d=f.useRef(r._getFieldArray(s).map(Nr)),u=f.useRef(!1);r._names.array.add(s),f.useMemo(()=>l&&i.length>=0&&r.register(s,l),[r,s,i.length,l]),ca(()=>r._subjects.array.subscribe({next:({values:g,name:v})=>{if(v===s||!v){const y=q(g,s);Array.isArray(y)&&(c(y),d.current=y.map(Nr))}}}).unsubscribe,[r,s]);const h=f.useCallback(g=>{u.current=!0,r._setFieldArray(s,g)},[r,s]),m=(g,v)=>{const y=xt(Oe(g)),R=_a(r._getFieldArray(s),y);r._names.focus=Ma(s,R.length-1,v),d.current=_a(d.current,y.map(Nr)),h(R),c(R),r._setFieldArray(s,R,_a,{argA:Pa(g)})},p=(g,v)=>{const y=xt(Oe(g)),R=za(r._getFieldArray(s),y);r._names.focus=Ma(s,0,v),d.current=za(d.current,y.map(Nr)),h(R),c(R),r._setFieldArray(s,R,za,{argA:Pa(g)})},b=g=>{const v=$a(r._getFieldArray(s),g);d.current=$a(d.current,g),h(v),c(v),!Array.isArray(q(r._fields,s))&&Ce(r._fields,s,void 0),r._setFieldArray(s,v,$a,{argA:g})},w=(g,v,y)=>{const R=xt(Oe(v)),I=Fa(r._getFieldArray(s),g,R);r._names.focus=Ma(s,g,y),d.current=Fa(d.current,g,R.map(Nr)),h(I),c(I),r._setFieldArray(s,I,Fa,{argA:g,argB:Pa(v)})},x=(g,v)=>{const y=r._getFieldArray(s);Va(y,g,v),Va(d.current,g,v),h(y),c(y),r._setFieldArray(s,y,Va,{argA:g,argB:v},!1)},N=(g,v)=>{const y=r._getFieldArray(s);La(y,g,v),La(d.current,g,v),h(y),c(y),r._setFieldArray(s,y,La,{argA:g,argB:v},!1)},C=(g,v)=>{const y=Oe(v),R=Ol(r._getFieldArray(s),g,y);d.current=[...R].map((I,k)=>!I||k===g?Nr():d.current[k]),h(R),c([...R]),r._setFieldArray(s,R,Ol,{argA:g,argB:y},!0,!1)},S=g=>{const v=xt(Oe(g));d.current=v.map(Nr),h([...v]),c([...v]),r._setFieldArray(s,[...v],y=>y,{},!0,!1)};return f.useEffect(()=>{r._state.action=!1,Ao(s,r._names)&&r._subjects.state.next({...r._formState});const g=ws(r._options.mode);if(u.current&&(!g.isOnSubmit||r._formState.isSubmitted)&&!ws(r._options.reValidateMode).isOnSubmit&&!g.isOnBlur)if(r._options.resolver)r._runSchema([s]).then(v=>{r._updateIsValidating([s]);const y=q(v.errors,s),R=q(r._formState.errors,s);(R?!y&&R.type||y&&(R.type!==y.type||R.message!==y.message):y&&y.type)&&(y?Ce(r._formState.errors,s,y):qe(r._formState.errors,s),r._subjects.state.next({errors:r._formState.errors}))});else{const v=q(r._fields,s);v&&v._f&&!(ws(r._options.reValidateMode).isOnSubmit&&ws(r._options.mode).isOnSubmit)&&Oo(v,r._names.disabled,r._formValues,r._options.criteriaMode===Lt.all,r._options.shouldUseNativeValidation,!0).then(y=>!tt(y)&&r._subjects.state.next({errors:Gd(r._formState.errors,y,s)}))}r._subjects.state.next({name:s,values:Oe(r._formValues)}),r._names.focus&&js(r._fields,(v,y)=>{if(r._names.focus&&y.startsWith(r._names.focus)&&v.focus)return v.focus(),1}),r._names.focus="",r._setValid(),u.current=!1},[i,s,r]),f.useEffect(()=>(!q(r._formValues,s)&&r._setFieldArray(s),()=>{const g=!(r._options.shouldUnregister||o),v=(y,R)=>{const I=q(r._fields,y);I&&I._f&&(I._f.mount=R)};u.current&&g&&r._subjects.state.next({name:s,values:Oe(r._formValues)}),g?v(s,!1):r.unregister(s)}),[s,r,n,o]),{swap:f.useCallback(x,[h,s,r]),move:f.useCallback(N,[h,s,r]),prepend:f.useCallback(p,[h,s,r]),append:f.useCallback(m,[h,s,r]),remove:f.useCallback(b,[h,s,r]),insert:f.useCallback(w,[h,s,r]),update:f.useCallback(C,[h,s,r]),replace:f.useCallback(S,[h,s,r]),fields:f.useMemo(()=>i.map((g,v)=>({...g,[n]:d.current[v]||Nr()})),[i,n])}}function Ms(e={}){const t=f.useRef(void 0),r=f.useRef(void 0),[s,n]=f.useState(()=>({...Oe(Yd),isLoading:at(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:at(e.defaultValues)?void 0:e.defaultValues}));if(!t.current)if(e.formControl)t.current={...e.formControl,formState:s},e.defaultValues&&!at(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:l,...i}=Pv(e);t.current={...i,formState:s}}const o=t.current.control;return o._options=e,ca(()=>{const l=o._subscribe({formState:o._proxyFormState,callback:()=>n({...o._formState}),reRenderRoot:!0});return n(i=>({...i,isReady:!0})),o._formState.isReady=!0,l},[o]),f.useEffect(()=>o._disableForm(e.disabled),[o,e.disabled]),f.useEffect(()=>{e.mode&&(o._options.mode=e.mode),e.reValidateMode&&(o._options.reValidateMode=e.reValidateMode)},[o,e.mode,e.reValidateMode]),f.useEffect(()=>{e.errors&&(o._setErrors(e.errors),o._focusError())},[o,e.errors]),f.useEffect(()=>{e.shouldUnregister&&o._subjects.state.next({values:o._getWatch()})},[o,e.shouldUnregister]),f.useEffect(()=>{if(o._proxyFormState.isDirty){const l=o._getDirty();l!==s.isDirty&&o._subjects.state.next({isDirty:l})}},[o,s.isDirty]),f.useEffect(()=>{var l;e.values&&!Rt(e.values,r.current)?(o._reset(e.values,{keepFieldsRef:!0,...o._options.resetOptions}),!((l=o._options.resetOptions)===null||l===void 0)&&l.keepIsValid||o._setValid(),r.current=e.values,n(i=>({...i}))):o._resetDefaultValues()},[o,e.values]),f.useEffect(()=>{o._state.mount||(o._setValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),t.current.formState=f.useMemo(()=>Vd(s,o),[o,s]),t.current}var Dl=(e,t,r)=>{if(e&&"reportValidity"in e){const s=q(r,t);e.setCustomValidity(s&&s.message||""),e.reportValidity()}},Mo=(e,t)=>{for(const r in t.fields){const s=t.fields[r];s&&s.ref&&"reportValidity"in s.ref?Dl(s.ref,r,e):s&&s.refs&&s.refs.forEach(n=>Dl(n,r,e))}},Ml=(e,t)=>{t.shouldUseNativeValidation&&Mo(e,t);const r={};for(const s in e){const n=q(t.fields,s),o=Object.assign(e[s]||{},{ref:n&&n.ref});if(Lv(t.names||Object.keys(e),s)){const l=Object.assign({},q(r,s));Ce(l,"root",o),Ce(r,s,l)}else Ce(r,s,o)}return r},Lv=(e,t)=>{const r=_l(t);return e.some(s=>_l(s).match(`^${r}\\.\\d+`))};function _l(e){return e.replace(/\]|\[/g,"")}function Pl(e,t){try{var r=e()}catch(s){return t(s)}return r&&r.then?r.then(void 0,t):r}function zv(e,t){for(var r={};e.length;){var s=e[0],n=s.code,o=s.message,l=s.path.join(".");if(!r[l])if("unionErrors"in s){var i=s.unionErrors[0].errors[0];r[l]={message:i.message,type:i.code}}else r[l]={message:o,type:n};if("unionErrors"in s&&s.unionErrors.forEach(function(u){return u.errors.forEach(function(h){return e.push(h)})}),t){var c=r[l].types,d=c&&c[s.code];r[l]=Ri(l,t,r,n,d?[].concat(d,s.message):s.message)}e.shift()}return r}function $v(e,t){for(var r={};e.length;){var s=e[0],n=s.code,o=s.message,l=s.path.join(".");if(!r[l])if(s.code==="invalid_union"&&s.errors.length>0){var i=s.errors[0][0];r[l]={message:i.message,type:i.code}}else r[l]={message:o,type:n};if(s.code==="invalid_union"&&s.errors.forEach(function(u){return u.forEach(function(h){return e.push(h)})}),t){var c=r[l].types,d=c&&c[s.code];r[l]=Ri(l,t,r,n,d?[].concat(d,s.message):s.message)}e.shift()}return r}function da(e,t,r){if(r===void 0&&(r={}),(function(s){return"_def"in s&&typeof s._def=="object"&&"typeName"in s._def})(e))return function(s,n,o){try{return Promise.resolve(Pl(function(){return Promise.resolve(e[r.mode==="sync"?"parse":"parseAsync"](s,t)).then(function(l){return o.shouldUseNativeValidation&&Mo({},o),{errors:{},values:r.raw?Object.assign({},s):l}})},function(l){if((function(i){return Array.isArray(i?.issues)})(l))return{values:{},errors:Ml(zv(l.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw l}))}catch(l){return Promise.reject(l)}};if((function(s){return"_zod"in s&&typeof s._zod=="object"})(e))return function(s,n,o){try{return Promise.resolve(Pl(function(){return Promise.resolve((r.mode==="sync"?ug:ag)(e,s,t)).then(function(l){return o.shouldUseNativeValidation&&Mo({},o),{errors:{},values:r.raw?Object.assign({},s):l}})},function(l){if((function(i){return i instanceof ng})(l))return{values:{},errors:Ml($v(l.issues,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw l}))}catch(l){return Promise.reject(l)}};throw new Error("Invalid input: not a Zod schema")}var Ai=({onCancel:e,isLoading:t})=>(0,a.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,a.jsx)(B,{type:"button",variant:"outline",size:"lg",onClick:e,disabled:t,children:"Cancel"}),(0,a.jsx)(B,{type:"submit",variant:"default",size:"lg",disabled:t,children:"Save"})]}),Vv=({index:e})=>{const{control:t,watch:r}=Ge(),s=r("fields")?.filter(o=>o.columnName?.trim()),n=r(`fields.${e}.columnName`);return(0,a.jsx)(Ot,{control:t,name:`foreignKeys.${e}`,render:({field:o})=>(0,a.jsx)("div",{className:"flex flex-col gap-2 flex-1",children:(0,a.jsxs)(dt,{defaultValue:n||"none",value:o.value?.columnName,onValueChange:l=>o.onChange({...o.value,columnName:l}),children:[(0,a.jsx)(lt,{className:"w-full flex-1",children:(0,a.jsx)(it,{placeholder:s?.length?"Select a column":"No columns found"})}),(0,a.jsx)(ct,{children:s?.length>0?s.map(l=>(0,a.jsx)(ue,{value:l.columnName,children:l.columnName},l.columnName)):(0,a.jsx)(ue,{value:"none",disabled:!0,children:"No columns found"})})]})})})},_r=()=>{const{dbType:e}=Me();return e?ig[e]:void 0},Bv={numeric:[{value:"int2",label:"int2",description:"Signed two-byte integer"},{value:"int4",label:"int4",description:"Signed four-byte integer"},{value:"int8",label:"int8",description:"Signed eight-byte integer"},{value:"float4",label:"float4",description:"Single precision floating-point number (4 bytes)"},{value:"float8",label:"float8",description:"Double precision floating-point number (8 bytes)"},{value:"numeric",label:"numeric",description:"Exact numeric of selectable precision"},{value:"serial",label:"serial",description:"Auto-incrementing four-byte integer"},{value:"bigserial",label:"bigserial",description:"Auto-incrementing eight-byte integer"}],text:[{value:"text",label:"text",description:"Variable-length character string"},{value:"varchar",label:"varchar",description:"Variable-length character string"},{value:"char",label:"char",description:"Fixed-length character string"},{value:"uuid",label:"uuid",description:"Universally unique identifier"}],boolean:[{value:"boolean",label:"boolean",description:"Logical boolean (true/false)"}],datetime:[{value:"date",label:"date",description:"Calendar date (year, month, day)"},{value:"time",label:"time",description:"Time of day (no time zone)"},{value:"timestamp",label:"timestamp",description:"Date and time (no time zone)"},{value:"timestamptz",label:"timestamptz",description:"Date and time with time zone"},{value:"interval",label:"interval",description:"Time span"}],json:[{value:"json",label:"json",description:"Textual JSON data"},{value:"jsonb",label:"jsonb",description:"Binary JSON data, decomposed"}],binary:[{value:"bytea",label:"bytea",description:'Binary data ("byte array")'}],network:[{value:"inet",label:"inet",description:"IPv4 or IPv6 host address"},{value:"cidr",label:"cidr",description:"IPv4 or IPv6 network address"},{value:"macaddr",label:"macaddr",description:"MAC (Media Access Control) address"},{value:"macaddr8",label:"macaddr8",description:"MAC address (EUI-64 format)"}],geometric:[{value:"point",label:"point",description:"Geometric point on a plane"},{value:"line",label:"line",description:"Infinite line on a plane"},{value:"polygon",label:"polygon",description:"Closed geometric path on a plane"}],other:[{value:"xml",label:"xml",description:"XML data"}]},Uv={numeric:[{value:"double",label:"double",description:"64-bit floating point number"},{value:"int",label:"int",description:"32-bit signed integer"},{value:"long",label:"long",description:"64-bit signed integer"},{value:"decimal",label:"decimal",description:"128-bit decimal value"}],text:[{value:"string",label:"string",description:"UTF-8 string"},{value:"javascript",label:"javascript",description:"JavaScript code"},{value:"javascriptWithScope",label:"javascriptWithScope",description:"JavaScript code with scope"},{value:"symbol",label:"symbol",description:"Symbol (deprecated)"}],boolean:[{value:"bool",label:"bool",description:"Boolean true/false"}],datetime:[{value:"date",label:"date",description:"UTC datetime"},{value:"timestamp",label:"timestamp",description:"MongoDB timestamp"}],document:[{value:"object",label:"object",description:"Embedded document"},{value:"array",label:"array",description:"Array value"},{value:"objectId",label:"objectId",description:"ObjectId value"}],binary:[{value:"binData",label:"binData",description:"Binary data"},{value:"regex",label:"regex",description:"Regular expression"}],legacy:[{value:"undefined",label:"undefined",description:"Undefined (deprecated)"},{value:"dbPointer",label:"dbPointer",description:"DB pointer (deprecated)"}],special:[{value:"null",label:"null",description:"Null value"},{value:"minKey",label:"minKey",description:"Minimum BSON value"},{value:"maxKey",label:"maxKey",description:"Maximum BSON value"}]},Jd=["serial","bigserial"],Qd=["int2","int4","int8","float4","float8","numeric","text","varchar","char","uuid","boolean","date","time","timestamp","timestamptz","interval","json","jsonb","bytea","inet","cidr","macaddr","macaddr8"],Fl=[{name:"isNullable",label:"Is Nullable",description:"Specify if the column can assume a NULL value if no value is provided"},{name:"isUnique",label:"Is Unique",description:"Enforce if values in the column should be unique across rows"},{name:"isIdentity",label:"Is Identity",description:"Automatically assign a sequential unique number to the column"},{name:"isArray",label:"Define as Array",description:"Define your column as a variable-length multidimensional array"}],Xd=[{value:"NO ACTION",label:"No action"},{value:"RESTRICT",label:"Restrict"},{value:"CASCADE",label:"Cascade"},{value:"SET NULL",label:"Set null"},{value:"SET DEFAULT",label:"Set default"}],ua=({index:e})=>{const[t,r]=(0,f.useState)(!1),s=_r()?.dataModel==="document",n=s?Uv:Bv,{control:o,setValue:l,formState:{errors:i}}=Ge();return(0,a.jsx)(Ot,{control:o,name:`fields.${e}.columnType`,render:({field:c})=>(0,a.jsxs)(Mr,{modal:!0,open:t,onOpenChange:r,children:[(0,a.jsx)(fs,{asChild:!0,children:(0,a.jsxs)(B,{id:`columnType-${e}`,role:"combobox","aria-expanded":t,"aria-controls":`columnType-${e}-listbox`,variant:"outline",className:V("w-full justify-between border-input bg-background px-3 font-normal hover:bg-background",i?.fields?.[e]?.columnType?"border-destructive ring-destructive ring-1":""),children:[c.value||"Select type",(0,a.jsx)(us,{"aria-hidden":"true",className:"-me-1 opacity-60",size:16})]})}),(0,a.jsx)(ur,{id:`columnType-${e}-listbox`,align:"start",className:"w-full min-w-[--radix-popper-anchor-width] border-input p-0",children:(0,a.jsxs)(xi,{children:[(0,a.jsx)(Si,{placeholder:"Search type..."}),(0,a.jsxs)(Ci,{children:[(0,a.jsx)(wi,{children:"No type found."}),Object.entries(n).map(([d,u])=>(0,a.jsx)(vr,{heading:d,children:u.map(h=>(0,a.jsxs)(Ae,{value:`${h.label} ${h.description}`,onSelect:()=>{c.onChange(h.value),!s&&Jd.includes(h.value)&&l(`fields.${e}.isIdentity`,!1),!s&&h.value&&!Qd.includes(h.value)&&l(`fields.${e}.isArray`,!1),r(!1)},children:[(0,a.jsxs)("div",{className:"flex flex-col gap-1 items-start flex-1",children:[(0,a.jsx)("p",{className:"font-medium",children:h.label}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:h.description})]}),c.value===h.value&&(0,a.jsx)(Os,{className:"ml-auto shrink-0",size:16})]},h.value))},d))]})]})})]})})},Ll=(e,t)=>e.flatMap((r,s)=>{const n=t.fields[s];if(!n)return[];const o=n.columnType!==r.dataTypeLabel?{columnType:n.columnType,isNullable:r.isNullable,defaultValue:r.columnDefault}:void 0,l=n.columnName.trim(),i=l!==r.columnName?l:void 0;return o||i!==void 0?[{columnName:r.columnName,alter:o,newColumnName:i}]:[]}),qv=({tableName:e})=>{const t=St(),{selectedDatabase:r}=Me(),{mutateAsync:s,isPending:n}=ht({mutationFn:async l=>{for(const{columnName:i,alter:c,newColumnName:d}of l)c&&await bd({tableName:e,columnName:i,data:c,db:r}),d!==void 0&&await gd({tableName:e,columnName:i,data:{newColumnName:d},db:r});return l.length},onSettled:async()=>{await Promise.all([t.invalidateQueries({queryKey:Ee.columnsByTable(e),exact:!1}),t.invalidateQueries({queryKey:Ee.dataByTable(e),exact:!1})])}});return{editTable:l=>we.promise(s(l),{loading:"Saving table changes...",success:i=>`Updated ${i} ${i===1?"column":"columns"}`,error:i=>typeof i.details=="string"&&i.details||i.message||"Failed to update table"}).unwrap(),isEditingTable:n}},mt=({tableName:e})=>{const{selectedDatabase:t}=Me(),{data:r,isLoading:s,isRefetching:n,error:o,refetch:l}=Rr({queryKey:Ee.columns(e,t),queryFn:()=>$p(e,t),select:i=>i.data.data,enabled:!!e&&!!t});return{tableCols:r,isLoadingTableCols:s,isRefetchingTableCols:n,errorTableCols:o,refetchTableCols:l}},fa=Dr()(e=>({editingColumn:null,setEditingColumn:t=>e({editingColumn:t}),editingTable:null,setEditingTable:t=>e({editingTable:t})})),Wv=Cr({fields:xo(Cr({columnName:Vt().trim().min(1,"Column name is required"),columnType:Vt()})).superRefine((e,t)=>{const r=new Set;e.forEach((s,n)=>{const o=s.columnName.toLowerCase();r.has(o)&&t.addIssue({code:"custom",message:"Column name must be unique",path:[n,"columnName"]}),r.add(o)})})}),Ba=e=>({fields:e.map(t=>({columnName:t.columnName,columnType:t.dataTypeLabel}))}),XT=()=>{const{editingTable:e}=fa();return(0,a.jsx)(Kv,{tableName:e??""},e??"")},Kv=({tableName:e})=>{const{openOverlay:t,closeOverlay:r,isOverlayOpen:s}=je(),{tableCols:n,isLoadingTableCols:o}=mt({tableName:e}),{editTable:l,isEditingTable:i}=qv({tableName:e}),c=Ms({mode:"onSubmit",defaultValues:Ba(n??[]),resolver:da(Wv)}),{handleSubmit:d,watch:u,reset:h}=c;(0,f.useEffect)(()=>{n&&h(Ba(n),{keepDirtyValues:!0})},[n,h]);const m=u("fields"),p=n!==void 0&&m.length===n.length,b=p?Ll(n,{fields:m}):[],w=b.length>0,x=new Map(b.map(v=>[v.columnName,v])),N=()=>r("schema.edit-table"),C=()=>{i||(w?t("schema.edit-table-discard-changes"):N())},S=()=>{h(Ba(n??[])),r("schema.edit-table-discard-changes"),N()},g=async v=>{if(!n)return;const y=Ll(n,v);if(y.length!==0)try{await l(y),h(v),N()}catch{}};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(Ut,{title:"Edit table",description:e,open:s("schema.edit-table"),onOpenChange:v=>{v||C()},children:n&&n.length>0&&p?(0,a.jsx)(Ds,{...c,children:(0,a.jsxs)("form",{onSubmit:d(g),className:"flex flex-col h-full",children:[(0,a.jsx)("div",{className:"-mx-5 -mt-6 divide-y divide-border",children:n.map((v,y)=>(0,a.jsx)(Hv,{col:v,index:y,change:x.get(v.columnName),newColumnName:m[y]?.columnName.trim()??""},v.columnName))}),(0,a.jsxs)("div",{className:"sticky -bottom-6 -mx-5 -mb-6 flex items-center justify-between gap-2 border-t border-border bg-background px-5 py-4",children:[(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:w?`${b.length} ${b.length===1?"column":"columns"} changed`:"No changes"}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(B,{type:"button",variant:"outline",size:"lg",disabled:i,onClick:C,children:"Close"}),(0,a.jsx)(B,{type:"submit",size:"lg",disabled:i||!w,children:"Save changes"})]})]})]})}):(0,a.jsx)("div",{className:"flex flex-col h-full",children:(0,a.jsx)("div",{className:"space-y-6",children:o||n&&n.length>0?(0,a.jsx)("p",{className:"text-sm text-muted-foreground",children:"Loading columns..."}):(0,a.jsx)(rt,{variant:"info",title:"No columns found",message:"This table has no columns to edit."})})})}),(0,a.jsx)(Qr,{open:s("schema.edit-table-discard-changes"),onOpenChange:v=>{v||r("schema.edit-table-discard-changes")},children:(0,a.jsxs)(Jr,{children:[(0,a.jsxs)(Yr,{children:[(0,a.jsx)(Xr,{children:"Discard unsaved changes?"}),(0,a.jsx)(es,{children:"This table has unsaved column changes. Discard them and close?"})]}),(0,a.jsxs)(Gr,{children:[(0,a.jsx)(Hr,{children:"Keep editing"}),(0,a.jsx)(Zr,{onClick:S,children:"Discard changes"})]})]})})]})},Us=({children:e,className:t,title:r})=>(0,a.jsx)("span",{title:r,className:V("truncate rounded border border-border bg-muted/40 px-1.5 font-mono text-[10px] leading-4 text-muted-foreground",t),children:e}),Hv=({col:e,index:t,change:r,newColumnName:s})=>{const{register:n,formState:o}=Ge(),l=o.errors.fields?.[t]?.columnName?.message;return(0,a.jsxs)("div",{className:V("grid grid-cols-3 gap-4 px-5 py-3",r&&"bg-primary/5"),children:[(0,a.jsxs)("div",{className:"col-span-1 flex min-w-0 flex-col gap-1.5",children:[(0,a.jsxs)("span",{className:"flex items-center gap-1.5",children:[e.isPrimaryKey?(0,a.jsx)(nd,{"aria-label":"Primary key",className:"size-3.5 shrink-0 text-amber-500"}):e.isForeignKey?(0,a.jsx)(Lm,{"aria-label":`References ${e.referencedTable}.${e.referencedColumn}`,className:"size-3.5 shrink-0 text-sky-500"}):(0,a.jsx)("span",{className:"size-3.5 shrink-0"}),(0,a.jsx)("span",{className:"truncate font-mono text-sm font-medium",children:e.columnName})]}),(0,a.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-1 pl-5",children:[r?.alter?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(Us,{className:"line-through",children:e.dataTypeLabel}),(0,a.jsx)(zn,{className:"size-3 text-muted-foreground"}),(0,a.jsx)(Us,{className:"border-primary/40 text-primary",children:r.alter.columnType})]}):(0,a.jsx)(Us,{children:e.dataTypeLabel}),!e.isNullable&&(0,a.jsx)(Us,{children:"not null"}),e.columnDefault&&(0,a.jsxs)(Us,{title:e.columnDefault,className:"max-w-full",children:["default ",e.columnDefault]})]}),r?.newColumnName!==void 0&&(0,a.jsxs)("span",{className:"flex min-w-0 items-center gap-1 pl-5 font-mono text-[11px] text-primary",children:[(0,a.jsx)(zn,{className:"size-3 shrink-0"}),(0,a.jsx)("span",{className:"truncate",children:s})]})]}),(0,a.jsxs)("div",{className:"col-span-2 grid grid-cols-2 items-start gap-2",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,a.jsx)(Ke,{"aria-label":`Name of ${e.columnName}`,"aria-invalid":l?!0:void 0,className:"font-mono",...n(`fields.${t}.columnName`)}),l&&(0,a.jsx)("span",{className:"text-xs text-destructive",children:l})]}),(0,a.jsx)(ua,{index:t})]})]})},Zd=()=>{const e=St(),{selectedDatabase:t}=Me(),{mutateAsync:r,isPending:s}=ht({mutationFn:async({tableName:o,columnName:l,cascade:i})=>(await Gp({tableName:o,columnName:l,cascade:i,db:t??""})).data.data,onSuccess:async(o,l)=>{await Promise.all([e.invalidateQueries({queryKey:Ee.columnsByTable(l.tableName),exact:!1}),e.invalidateQueries({queryKey:Ee.dataByTable(l.tableName),exact:!1}),e.invalidateQueries({queryKey:Ee.lists(),exact:!1})])}});return{deleteColumn:async({tableName:o,columnName:l,cascade:i})=>we.promise(r({tableName:o,columnName:l,cascade:i,db:""}),{loading:"Deleting column...",success:c=>c||"Column deleted successfully",error:c=>c.message||"Failed to delete column"}),isDeletingColumn:s}},Gv=({columnVirtualizer:e,renderCellAccessory:t,row:r,rowVirtualizer:s,virtualPaddingLeft:n,virtualPaddingRight:o,virtualRow:l})=>{const i=r.getVisibleCells(),c=e.getVirtualItems();return(0,a.jsxs)("tr",{"data-index":l.index,ref:d=>s.measureElement(d),className:"flex absolute w-fit border-b items-center text-sm hover:bg-accent/20 data-[state=open]:bg-accent/40 [&_svg]:size-4",style:{transform:`translateY(${l.start}px)`},children:[n?(0,a.jsx)("td",{style:{display:"flex",width:n}}):null,c.map(d=>{const u=i[d.index];return(0,a.jsxs)("td",{className:"group relative flex border-r border-border h-8 items-center px-3 truncate",style:{width:u.column.getSize()},children:[rs(u.column.columnDef.cell,u.getContext()),t?.(u.getValue())]},u.id)}),o?(0,a.jsx)("td",{style:{display:"flex",width:o}}):null]},r.id)},Yv=({columnVirtualizer:e,renderCellAccessory:t,table:r,tableContainerRef:s,virtualPaddingLeft:n,virtualPaddingRight:o})=>{const{rows:l}=r.getRowModel(),i=Qn({count:l.length,estimateSize:()=>33,getScrollElement:()=>s.current,measureElement:typeof window<"u"&&navigator.userAgent.indexOf("Firefox")===-1?d=>d?.getBoundingClientRect().height:void 0,overscan:5}),c=i.getVirtualItems();return(0,a.jsx)("tbody",{style:{display:"grid",height:`${i.getTotalSize()}px`,position:"relative"},children:c.map(d=>{const u=l[d.index];return(0,a.jsx)(Gv,{columnVirtualizer:e,renderCellAccessory:t,row:u,rowVirtualizer:i,virtualPaddingLeft:n,virtualPaddingRight:o,virtualRow:d},u.id)})})};function Jv({header:e,table:t,label:r}){const s=t._getDefaultColumnDef(),n=(0,f.useCallback)(()=>{t.setColumnSizing(o=>{const l={...o};return delete l[e.column.id],l})},[e.column.id,t]);return(0,a.jsx)("div",{role:"separator","aria-orientation":"vertical","aria-label":`Resize ${r} column`,"aria-valuenow":e.column.getSize(),"aria-valuemin":s.minSize,"aria-valuemax":s.maxSize,tabIndex:0,className:V("after:-translate-x-1/2 -right-px absolute top-0 z-50 h-full w-0.5 cursor-ew-resize touch-none select-none bg-border transition-opacity after:absolute after:inset-y-0 after:left-1/2 after:h-full after:w-[18px] after:content-[''] hover:bg-primary focus:bg-primary focus:outline-none",e.column.getIsResizing()?"bg-primary":"opacity-0 hover:opacity-100"),onDoubleClick:n,onMouseDown:e.getResizeHandler(),onTouchStart:e.getResizeHandler()})}var Qv=(0,f.memo)(Jv,(e,t)=>{const r=e.header.column,s=t.header.column;return!(r.getIsResizing()!==s.getIsResizing()||r.getSize()!==s.getSize()||e.label!==t.label)}),Xv=({columnVirtualizer:e,table:t,virtualPaddingLeft:r,virtualPaddingRight:s})=>{const n=e.getVirtualItems(),o=t.getState().columnSizingInfo.isResizingColumn;return(0,a.jsx)("thead",{className:"h-9 grid sticky top-0 z-10 supports-backdrop-filter:backdrop-blur-sm",children:t.getHeaderGroups().map(l=>(0,a.jsxs)("tr",{className:V("flex w-fit bg-muted/40 border-b border-border items-center text-sm [&_svg]:size-4",o&&"pointer-events-none"),children:[r?(0,a.jsx)("th",{style:{display:"flex",width:r}}):null,n.map(i=>{const c=l.headers[i.index];return(0,a.jsxs)("th",{className:"relative h-full flex items-center border-r border-border text-xs font-medium text-muted-foreground",style:{width:c.getSize()},children:[(0,a.jsx)("div",{className:"flex w-full h-full items-center px-3",children:rs(c.column.columnDef.header,c.getContext())}),c.column.getCanResize()&&(0,a.jsx)(Qv,{header:c,table:t,label:c.column.id})]},c.id)}),s?(0,a.jsx)("th",{style:{display:"flex",width:s}}):null]},l.id))})},Zv=({table:e,renderCellAccessory:t})=>{const r=e.getVisibleLeafColumns(),s=(0,f.useRef)(null),n=Qn({count:r.length,estimateSize:c=>r[c].getSize(),getScrollElement:()=>s.current,horizontal:!0,overscan:3}),o=n.getVirtualItems();let l,i;return n&&o?.length&&(l=o[0]?.start??0,i=n.getTotalSize()-(o[o.length-1]?.end??0)),(0,a.jsx)("div",{className:"w-full flex-1 overflow-auto",ref:s,style:{position:"relative"},children:(0,a.jsxs)("table",{style:{display:"grid"},children:[(0,a.jsx)(Xv,{columnVirtualizer:n,table:e,virtualPaddingLeft:l,virtualPaddingRight:i}),(0,a.jsx)(Yv,{columnVirtualizer:n,renderCellAccessory:t,table:e,tableContainerRef:s,virtualPaddingLeft:l,virtualPaddingRight:i})]})})},eu=({columns:e,data:t,renderCellAccessory:r})=>{const s=si({data:t,columns:e,getCoreRowModel:ri(),enableColumnResizing:!0,columnResizeMode:"onChange"});return(0,a.jsx)(Zv,{table:s,renderCellAccessory:r})},dr=e=>{if(e==null)return"";if(typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e)},Oi=({value:e,className:t})=>{const[r,s]=(0,f.useState)(!1),n=(0,f.useRef)(null);(0,f.useEffect)(()=>()=>{n.current&&window.clearTimeout(n.current)},[]);const o=dr(e),l=(0,f.useCallback)(async i=>{i.stopPropagation();try{await navigator.clipboard.writeText(o),s(!0)}catch(c){console.error("Failed to copy cell value:",c);return}n.current&&window.clearTimeout(n.current),n.current=window.setTimeout(()=>{s(!1)},1200)},[o]);return o?(0,a.jsx)("button",{type:"button",className:V("absolute right-0.5 top-1/2 inline-flex size-5 -translate-y-1/2 items-center justify-center","text-muted-foreground opacity-0 transition-opacity","hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none","group-hover:opacity-100",t),onClick:l,"aria-label":r?"Copied":"Copy",children:r?(0,a.jsx)(Os,{className:"size-3.5"}):(0,a.jsx)(ni,{className:"size-3.5"})}):null};function kr({className:e,...t}){return(0,a.jsx)(vp,{"data-slot":"checkbox",className:V("border-input dark:bg-input/20 dark:bg-input/30 data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary data-checked:border-primary aria-invalid:aria-checked:border-primary aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 focus-visible:border-ring focus-visible:ring-ring/30 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 flex size-4 items-center justify-center rounded-[4px] border transition-shadow group-has-disabled/field:opacity-50 focus-visible:ring-[2px] aria-invalid:ring-[2px] peer relative shrink-0 outline-none after:absolute after:-inset-x-3 after:-inset-y-2 disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:(0,a.jsx)(yp,{"data-slot":"checkbox-indicator",className:"[&>svg]:size-3.5 grid place-content-center text-current transition-none",children:(0,a.jsx)(Os,{})})})}function gn({...e}){return(0,a.jsx)(Rp,{"data-slot":"dropdown-menu",...e})}function vn({...e}){return(0,a.jsx)(Cp,{"data-slot":"dropdown-menu-trigger",...e})}function yn({className:e,align:t="start",sideOffset:r=4,...s}){return(0,a.jsx)(Sp,{children:(0,a.jsx)(wp,{"data-slot":"dropdown-menu-content",sideOffset:r,align:t,className:V("data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-32 rounded-lg p-1 shadow-md ring-1 duration-100 z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto data-[state=closed]:overflow-hidden",e),...s})})}function tu({...e}){return(0,a.jsx)(gp,{"data-slot":"dropdown-menu-group",...e})}function $t({className:e,inset:t,variant:r="default",...s}){return(0,a.jsx)(pp,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":r,className:V("focus:bg-accent cursor-pointer focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive not-data-[variant=destructive]:focus:**:text-accent-foreground min-h-7 gap-2 rounded-sm px-2 py-1 text-xs/relaxed [&_svg:not([class*='size-'])]:size-3.5 group/dropdown-menu-item relative flex items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0",e),...s})}function ru({className:e,...t}){return(0,a.jsx)(mp,{"data-slot":"dropdown-menu-separator",className:V("bg-border/50 -mx-1 my-1 h-px",e),...t})}function ZT({...e}){return(0,a.jsx)(Tp,{"data-slot":"dropdown-menu-sub",...e})}function eR({className:e,inset:t,children:r,...s}){return(0,a.jsxs)(xp,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:V("focus:bg-accent focus:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground min-h-7 gap-2 rounded-sm px-2 py-1 text-xs [&_svg:not([class*='size-'])]:size-3.5 flex cursor-default items-center outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0",e),...s,children:[r,(0,a.jsx)(ci,{className:"ml-auto"})]})}function tR({className:e,...t}){return(0,a.jsx)(bp,{"data-slot":"dropdown-menu-sub-content",className:V("data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-32 rounded-lg p-1 shadow-md ring-1 duration-100 z-50 origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden",e),...t})}var su=({index:e,isDisabled:t})=>{const{control:r}=Ge(),s=_r()?.dataModel==="document",n=Ft({control:r,name:`fields.${e}.columnType`}),o=Ft({control:r,name:`fields.${e}.isPrimaryKey`}),l=Ft({control:r,name:`fields.${e}.isNullable`}),i=Ft({control:r,name:`fields.${e}.isUnique`}),c=Ft({control:r,name:`fields.${e}.isIdentity`}),d=Ft({control:r,name:`fields.${e}.isArray`}),u=(0,f.useCallback)(m=>{if(s)switch(m){case"isIdentity":return!1;case"isArray":return!!n&&n!=="array";default:return!0}switch(m){case"isNullable":return!o;case"isIdentity":return!Jd.includes(n);case"isArray":return Qd.includes(n);default:return!0}},[s,o,n]),h=(0,f.useMemo)(()=>{const m={isNullable:l,isUnique:i,isIdentity:c,isArray:d};return Fl.filter(p=>u(p.name)?!!m[p.name]:!1).length},[l,i,c,d,u]);return(0,a.jsx)("div",{className:"flex items-end justify-end",children:(0,a.jsxs)(gn,{children:[(0,a.jsx)(vn,{asChild:!0,children:(0,a.jsxs)(B,{"aria-label":"Advanced options",type:"button",variant:"ghost",size:"icon",disabled:t,className:"size-9 relative",children:[(0,a.jsx)(od,{className:"size-4"}),h>0&&(0,a.jsx)(Is,{className:"absolute -top-2 leading-0! left-full -translate-x-1/2 size-5 flex items-center justify-center text-xs",children:h>99?"99+":h})]})}),(0,a.jsx)(yn,{className:"w-96 space-y-1",side:"bottom",align:"end",children:Fl.map(m=>u(m.name)?(0,a.jsx)(Ot,{control:r,name:`fields.${e}.${m.name}`,render:({field:p})=>(0,a.jsxs)(me,{htmlFor:`${m.name}-${e}`,className:"flex items-start gap-3 rounded-lg p-3 cursor-pointer hover:bg-accent/50 has-checked:bg-primary-foreground has-checked:border-blue-600",children:[(0,a.jsx)(kr,{id:`${m.name}-${e}`,checked:!!p.value,onCheckedChange:b=>p.onChange(!!b),className:"data-[state=checked]:bg-blue-600 data-[state=checked]:border-blue-600",type:"button"}),(0,a.jsxs)("div",{className:"grid gap-1.5 font-normal",children:[(0,a.jsx)("p",{className:"text-sm leading-none font-medium",children:m.label}),(0,a.jsx)("p",{className:"text-sm text-muted-foreground",children:m.description})]})]})},m.name):null)})]})})},nu=({index:e,showForeignKeyButton:t=!0})=>{const{openOverlay:r}=je(),{control:s,register:n,formState:{errors:o},watch:l}=Ge(),i=t?l(`foreignKeys.${e}.referencedTable`):void 0,c=()=>{r(`table-builder.add-foreign-key-${e}`)};return(0,a.jsx)(Ot,{control:s,name:`fields.${e}.columnName`,render:()=>(0,a.jsxs)("div",{className:"flex",children:[(0,a.jsx)(Ke,{id:`fields.${e}.columnName`,...n(`fields.${e}.columnName`,{required:"Column name is required"}),placeholder:"column_name",className:V(t?"-me-px flex-1 rounded-e-none shadow-none focus-visible:z-10":"flex-1",o?.fields?.[e]?.columnName?"border-destructive ring-destructive ring-1":"")}),t&&(0,a.jsx)("button",{"aria-label":"Generate column name",className:V("inline-flex w-7 h-7 items-center justify-center rounded-e-md border border-input bg-background text-muted-foreground/80 text-sm outline-none transition-[color,box-shadow] hover:text-accent-foreground focus:z-10 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",i?"":"border-dashed"),type:"button",onClick:c,children:(0,a.jsx)(Xn,{"aria-hidden":"true",className:"size-3"})})]})})},Di=({index:e,isRequired:t=!0})=>{const{control:r,register:s,formState:{errors:n}}=Ge();return(0,a.jsx)(Ot,{control:r,name:`fields.${e}.defaultValue`,render:()=>(0,a.jsx)("div",{className:"flex flex-col gap-2",children:(0,a.jsx)(Ke,{id:`fields.${e}.defaultValue`,...s(`fields.${e}.defaultValue`,t?{required:"Default value is required"}:void 0),placeholder:"NULL",className:n?.fields?.[e]?.defaultValue?"border-destructive ring-destructive ring-1":""})})})},au=({index:e})=>{const{watch:t,control:r,register:s,setValue:n}=Ge(),o=t(`fields.${e}.isPrimaryKey`);return(0,a.jsx)(Ot,{control:r,name:`fields.${e}.isPrimaryKey`,render:()=>(0,a.jsx)("div",{className:"flex flex-1 items-center justify-start",children:(0,a.jsx)(kr,{id:`fields.${e}.isPrimaryKey`,...s(`fields.${e}.isPrimaryKey`),onCheckedChange:l=>{n(`fields.${e}.isPrimaryKey`,!!l),n(`fields.${e}.isNullable`,!1)},checked:o,className:"size-5"})})})},ey=e=>({...e,defaultValue:e.defaultValue?.trim()?e.defaultValue.trim():void 0}),ty=({tableName:e})=>{const t=St(),{closeOverlay:r}=je(),{selectedDatabase:s,dbType:n}=Me(),{mutateAsync:o,isPending:l}=ht({mutationFn:async c=>(await Wp({tableName:e,data:ey(c),db:s})).data.data,onSuccess:async()=>{await Promise.all([t.invalidateQueries({queryKey:Ee.columnsByTable(e),exact:!1}),t.invalidateQueries({queryKey:Ee.dataByTable(e),exact:!1})]),r("schema.add-column"),n&&cr.capture("column_added",{db_type:n})}});return{addColumn:async(c,d)=>we.promise(o(c,d),{loading:"Adding column...",success:u=>u||"Column added successfully",error:u=>typeof u.details=="string"&&u.details||u.message||"Failed to add column"}),isAddingColumn:l}},ry=Cr({fields:xd([Cr({columnName:pl.shape.columnName,columnType:pl.shape.columnType,defaultValue:Vt(),isPrimaryKey:bt(),isNullable:bt(),isUnique:bt(),isIdentity:bt(),isArray:bt()})])}),Ua={fields:[{columnName:"",columnType:"",defaultValue:"",isPrimaryKey:!1,isNullable:!0,isUnique:!1,isIdentity:!1,isArray:!1}]},sy=()=>{const e=Ge(),t=Ft({control:e.control,name:"fields.0.isPrimaryKey"});return(0,a.jsxs)("div",{className:"space-y-4",children:[(0,a.jsxs)("div",{className:"grid grid-cols-4 px-2",children:[(0,a.jsx)(me,{className:"text-xs",children:"Column Name"}),(0,a.jsx)(me,{className:"text-xs",children:"Column Type"}),(0,a.jsx)(me,{className:"text-xs",children:"Default Value"}),(0,a.jsx)(me,{className:"text-xs",children:"Primary"})]}),(0,a.jsx)("div",{className:"px-2 py-3",children:(0,a.jsxs)("div",{className:"grid grid-cols-4 gap-4",children:[(0,a.jsx)(nu,{index:0,showForeignKeyButton:!1}),(0,a.jsx)(ua,{index:0}),(0,a.jsx)(Di,{index:0,isRequired:!1}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(au,{index:0}),(0,a.jsx)(su,{index:0,isDisabled:!!t})]})]})})]})},ny=({tableName:e})=>{const{closeOverlay:t,isOverlayOpen:r}=je(),{addColumn:s,isAddingColumn:n}=ty({tableName:e}),o=Ms({mode:"onSubmit",defaultValues:Ua,resolver:da(ry)}),l=()=>{o.reset(Ua),t("schema.add-column")},i=async c=>{await s(c.fields[0]),o.reset(Ua)};return(0,a.jsx)(Ut,{title:"Add column",description:`Add a new column to "${e}".`,open:r("schema.add-column"),onOpenChange:c=>{c||l()},children:(0,a.jsx)(Ds,{...o,children:(0,a.jsxs)("form",{onSubmit:o.handleSubmit(i),className:"space-y-6",children:[(0,a.jsx)(sy,{}),(0,a.jsx)(Ai,{onCancel:l,isLoading:n})]})})})},ay=e=>({...e,defaultValue:e.defaultValue?.trim()?e.defaultValue.trim():null}),oy=({tableName:e,columnName:t})=>{const r=St(),{closeOverlay:s}=je(),{setEditingColumn:n}=fa(),{selectedDatabase:o}=Me(),{mutateAsync:l,isPending:i}=ht({mutationFn:async d=>(await bd({tableName:e,columnName:t,data:ay(d),db:o})).data.data,onSuccess:async()=>{await r.invalidateQueries({queryKey:Ee.columnsByTable(e),exact:!1}),n(null),s("schema.edit-column")}});return{alterColumn:async(d,u)=>we.promise(l(d,u),{loading:"Updating column...",success:h=>h||"Column updated successfully",error:h=>typeof h.details=="string"&&h.details||h.message||"Failed to update column"}),isAlteringColumn:i}},iy=Cr({fields:xd([Cr({columnName:Vt(),columnType:gl.shape.columnType,defaultValue:Vt(),isPrimaryKey:bt(),isNullable:gl.shape.isNullable,isUnique:bt(),isIdentity:bt(),isArray:bt()})])}),wn=e=>({fields:[{columnName:e?.columnName??"",columnType:e?.dataTypeLabel??"",defaultValue:e?.columnDefault??"",isPrimaryKey:!1,isNullable:e?.isNullable??!0,isUnique:!1,isIdentity:!1,isArray:e?.dataType==="array"}]}),ly=({tableName:e})=>{const{closeOverlay:t,isOverlayOpen:r}=je(),{editingColumn:s,setEditingColumn:n}=fa(),o=Ms({mode:"onSubmit",defaultValues:wn(null),resolver:da(iy)}),{alterColumn:l,isAlteringColumn:i}=oy({tableName:e,columnName:s?.columnName??""});(0,f.useEffect)(()=>{o.reset(wn(s))},[s,o]);const c=()=>{n(null),o.reset(wn(null)),t("schema.edit-column")},d=async u=>{await l({columnType:u.fields[0].columnType,isNullable:u.fields[0].isNullable,defaultValue:u.fields[0].defaultValue}),o.reset(wn(null))};return(0,a.jsx)(Ut,{title:s?`Edit ${s.columnName}`:"Edit column",description:s?`Update the type, nullability, and default value for "${s.columnName}".`:"Update the selected column.",open:r("schema.edit-column"),onOpenChange:u=>{u||c()},children:(0,a.jsx)(Ds,{...o,children:(0,a.jsxs)("form",{onSubmit:o.handleSubmit(d),className:"space-y-6",children:[(0,a.jsxs)("div",{className:"space-y-4",children:[(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(me,{htmlFor:"edit-column-name",children:"Column name"}),(0,a.jsx)(Ke,{id:"edit-column-name",value:s?.columnName??"",readOnly:!0,disabled:!0})]}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(me,{children:"Column type"}),(0,a.jsx)(ua,{index:0})]}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(me,{children:"Default value"}),(0,a.jsx)(Di,{index:0,isRequired:!1})]}),(0,a.jsx)(Ot,{control:o.control,name:"fields.0.isNullable",render:({field:u})=>(0,a.jsxs)("div",{className:"flex items-center gap-3 rounded-lg border border-border p-3",children:[(0,a.jsx)(kr,{id:"edit-column-nullable",checked:!!u.value,onCheckedChange:h=>u.onChange(h===!0)}),(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)(me,{htmlFor:"edit-column-nullable",className:"cursor-pointer",children:"Nullable"}),(0,a.jsx)("p",{className:"text-xs text-muted-foreground",children:"Allow this column to store NULL values."})]})]})})]}),(0,a.jsx)(Ai,{onCancel:c,isLoading:i})]})})})},cy=({tableName:e,columnName:t})=>{const r=St(),{selectedDatabase:s}=Me(),{mutateAsync:n,isPending:o}=ht({mutationFn:async i=>(await gd({tableName:e,columnName:t,data:i,db:s})).data.data,onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:Ee.columnsByTable(e),exact:!1}),r.invalidateQueries({queryKey:Ee.dataByTable(e),exact:!1})])}});return{renameColumn:async(i,c)=>we.promise(n(i,c),{loading:"Renaming column...",success:d=>d||"Column renamed successfully",error:d=>typeof d.details=="string"&&d.details||d.message||"Failed to rename column"}),isRenamingColumn:o}},dy=({col:e,tableName:t})=>{const{openOverlay:r}=je(),{setEditingColumn:s}=fa(),{renameColumn:n,isRenamingColumn:o}=cy({tableName:t,columnName:e.columnName}),{deleteColumn:l,isDeletingColumn:i}=Zd(),[c,d]=(0,f.useState)(!1),[u,h]=(0,f.useState)(!1),[m,p]=(0,f.useState)(e.columnName),[b,w]=(0,f.useState)(!1),x=()=>{s(e),r("schema.edit-column")},N=v=>{d(v),v||p(e.columnName)},C=v=>{h(v),v||w(!1)},S=async()=>{await n({newColumnName:m.trim()}),N(!1)},g=async()=>{await l({db:"",tableName:t,columnName:e.columnName,cascade:b}),C(!1)};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(gn,{children:[(0,a.jsx)(vn,{asChild:!0,children:(0,a.jsx)(B,{variant:"ghost",size:"icon-sm",children:(0,a.jsx)($m,{className:"size-4"})})}),(0,a.jsx)(yn,{align:"end",className:"w-48",children:(0,a.jsxs)(tu,{children:[(0,a.jsxs)($t,{onClick:x,children:[(0,a.jsx)(Km,{className:"size-4"}),"Edit Column"]}),(0,a.jsxs)($t,{onClick:()=>N(!0),children:[(0,a.jsx)(sp,{className:"size-4"}),"Rename Column"]}),(0,a.jsx)(ru,{}),(0,a.jsxs)($t,{variant:"destructive",onClick:()=>C(!0),children:[(0,a.jsx)(li,{className:"size-4"}),"Drop Column"]})]})})]}),(0,a.jsx)(uy,{columnName:e.columnName,newColumnName:m,setNewColumnName:p,isOpen:c,onOpenChange:N,onRename:S,isRenaming:o}),(0,a.jsx)(fy,{columnName:e.columnName,isOpen:u,onOpenChange:C,cascadeDelete:b,setCascadeDelete:w,onDrop:g,isDropping:i})]})},uy=({columnName:e,newColumnName:t,setNewColumnName:r,isOpen:s,onOpenChange:n,onRename:o,isRenaming:l})=>{const i=!t.trim()||t.trim()===e;return(0,a.jsx)(ta,{open:s,onOpenChange:n,children:(0,a.jsxs)(ra,{className:"max-w-md",children:[(0,a.jsxs)(sa,{children:[(0,a.jsx)(na,{children:"Rename Column"}),(0,a.jsx)(aa,{children:"Update the column name while keeping the rest of the schema unchanged."})]}),(0,a.jsxs)("div",{className:"space-y-4",children:[(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(me,{htmlFor:"current-column-name",children:"Current name"}),(0,a.jsx)(Ke,{id:"current-column-name",value:e,readOnly:!0,disabled:!0})]}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(me,{htmlFor:"new-column-name",children:"New name"}),(0,a.jsx)(Ke,{id:"new-column-name",value:t,onChange:c=>r(c.target.value),placeholder:"column_name",autoFocus:!0})]})]}),(0,a.jsxs)(bi,{className:"gap-2",children:[(0,a.jsx)(B,{variant:"outline",onClick:()=>n(!1),disabled:l,children:"Cancel"}),(0,a.jsx)(B,{onClick:o,disabled:i||l,children:l?"Renaming...":"Rename Column"})]})]})})},fy=({columnName:e,isOpen:t,onOpenChange:r,cascadeDelete:s,setCascadeDelete:n,onDrop:o,isDropping:l})=>(0,a.jsx)(ta,{open:t,onOpenChange:r,children:(0,a.jsxs)(ra,{className:"max-w-md",children:[(0,a.jsxs)(sa,{children:[(0,a.jsx)(na,{children:"Drop Column"}),(0,a.jsxs)(aa,{children:["Are you sure you want to drop the column"," ",(0,a.jsxs)("span",{className:"font-semibold text-foreground",children:['"',e,'"']}),"? This action cannot be undone and permanently removes the data stored in it."]})]}),(0,a.jsxs)("div",{className:"flex gap-3 rounded-lg border border-border p-3",children:[(0,a.jsx)(kr,{id:`drop-column-cascade-${e}`,checked:s,onCheckedChange:i=>n(i===!0)}),(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)(me,{htmlFor:`drop-column-cascade-${e}`,className:"cursor-pointer",children:"Drop with CASCADE"}),(0,a.jsx)("p",{className:"text-xs text-muted-foreground",children:"Also remove dependent indexes, constraints, and foreign key references."})]})]}),(0,a.jsxs)(bi,{className:"gap-2",children:[(0,a.jsx)(B,{variant:"outline",onClick:()=>r(!1),disabled:l,children:"Cancel"}),(0,a.jsx)(B,{variant:"destructive",onClick:o,disabled:l,children:l?"Dropping...":"Drop Column"})]})]})}),ha=()=>{const e=_r();return e!==void 0&&e.dataModel!=="relational"},hy=({tableName:e,refetch:t,isRefetching:r=!1})=>{const{openOverlay:s}=je(),n=ha();return(0,a.jsxs)("header",{className:"max-h-8 overflow-hidden border-b border-border w-full flex items-center bg-background text-foreground sticky top-0 left-0 right-0 z-0",children:[(0,a.jsx)(B,{type:"button",variant:"ghost",className:"size-8! aspect-square border-x-0 border-y-0 border-border rounded-none text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors",onClick:()=>{t()},"aria-label":`Refetch schema for ${e}`,disabled:r,children:(0,a.jsx)(di,{className:"size-4"})}),(0,a.jsx)(B,{variant:"ghost",asChild:!0,className:"h-8! border-l border-y-0 border-r-0 border-border rounded-none flex items-center gap-2 text-muted-foreground hover:text-foreground",children:(0,a.jsxs)(jm,{to:"/table/$table",params:{table:e},"aria-label":`View data for ${e}`,children:[(0,a.jsx)(bo,{className:"size-4"}),"View data"]})}),!n&&(0,a.jsxs)(B,{type:"button",variant:"default",className:"h-8! border-l border-y-0 border-r-0 border-border rounded-none flex items-center gap-2",onClick:()=>s("schema.add-column"),children:[(0,a.jsx)(Ln,{className:"size-4"}),"Add Column"]})]})},my=({col:e})=>e.dataTypeLabel==="enum"&&e.enumValues&&e.enumValues.length>0?(0,a.jsxs)(ir,{children:[(0,a.jsx)(ar,{asChild:!0,children:(0,a.jsx)(Is,{variant:"outline",className:"font-mono cursor-default truncate",children:e.dataTypeLabel})}),(0,a.jsx)(or,{side:"right",children:(0,a.jsxs)("div",{className:"text-xs space-y-0.5",children:[(0,a.jsx)("p",{className:"text-muted-foreground mb-1",children:"Enum values:"}),e.enumValues.map(t=>(0,a.jsx)("p",{className:"font-mono",children:t},t))]})})]}):(0,a.jsx)(Is,{variant:"outline",className:"font-mono",children:e.dataTypeLabel}),rR=({tableName:e})=>{const{tableCols:t,isLoadingTableCols:r,isRefetchingTableCols:s,errorTableCols:n,refetchTableCols:o}=mt({tableName:e}),l=(0,f.useMemo)(()=>[{id:"index",header:"",cell:({row:i})=>(0,a.jsx)("span",{className:"text-xs text-muted-foreground/60",children:i.index+1}),size:47,minSize:47,enableResizing:!1},{id:"columnName",header:"Name",accessorKey:"columnName",cell:({getValue:i})=>(0,a.jsx)("span",{className:"font-mono text-foreground font-medium truncate",children:i()}),minSize:100,size:200},{id:"dataTypeLabel",header:"Type",cell:({row:i})=>(0,a.jsx)(my,{col:i.original}),size:100,minSize:100},{id:"columnDefault",header:"Default",accessorKey:"columnDefault",cell:({getValue:i})=>{const c=i();return c?(0,a.jsx)("span",{className:"font-mono text-xs text-muted-foreground truncate",children:c}):(0,a.jsx)("span",{className:"text-muted-foreground/50",children:"—"})},minSize:100,size:180},{id:"isNullable",header:"Nullable",accessorKey:"isNullable",cell:({getValue:i})=>i()?(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"yes"}):(0,a.jsx)("span",{className:"text-xs text-muted-foreground/50",children:"no"}),minSize:100},{id:"key",header:"Key",cell:({row:i})=>{const{isPrimaryKey:c,isForeignKey:d}=i.original;return(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[c&&(0,a.jsx)(Is,{variant:"default",className:"text-[0.6rem] px-1.5",children:"PK"}),d&&(0,a.jsx)(Is,{variant:"secondary",className:"text-[0.6rem] px-1.5",children:"FK"})]})},minSize:100,size:90},{id:"references",header:"References",cell:({row:i})=>{const{isForeignKey:c,referencedTable:d,referencedColumn:u}=i.original;return!c||!d||!u?(0,a.jsx)("span",{className:"text-muted-foreground/50",children:"—"}):(0,a.jsxs)(ir,{children:[(0,a.jsx)(ar,{asChild:!0,children:(0,a.jsxs)("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground cursor-default",children:[(0,a.jsx)(Xn,{className:"size-3 text-muted-foreground/70"}),(0,a.jsxs)("span",{className:"font-mono",children:[d,".",u]})]})}),(0,a.jsx)(or,{side:"left",children:(0,a.jsxs)("p",{children:["References"," ",(0,a.jsxs)("span",{className:"font-mono font-medium",children:[d,".",u]})]})})]})},size:160,minSize:100},{id:"actions",header:"",cell:({row:i})=>(0,a.jsx)("div",{className:"flex justify-center items-center",children:(0,a.jsx)(dy,{col:i.original,tableName:e})}),size:50,enableResizing:!1}],[e]);return r?(0,a.jsx)("div",{className:"size-full flex items-center justify-center",children:(0,a.jsx)(dn,{size:"size-7"})}):n?(0,a.jsxs)("div",{className:"size-full flex flex-col items-center justify-center gap-2",children:[(0,a.jsx)("div",{className:"text-sm font-medium",children:"Failed to load schema"}),(0,a.jsx)("div",{className:"text-sm text-muted-foreground",children:n.message})]}):(0,a.jsxs)("div",{className:"flex-1 flex flex-col overflow-hidden",children:[(0,a.jsx)(hy,{tableName:e,refetch:o,isRefetching:s}),(0,a.jsx)(eu,{columns:l,data:t??[],renderCellAccessory:i=>(0,a.jsx)(Oi,{value:i})}),(0,a.jsx)(ny,{tableName:e}),(0,a.jsx)(ly,{tableName:e})]})},py=({index:e,tableName:t})=>{const{tableCols:r,isLoadingTableCols:s}=mt({tableName:t}),{control:n}=Ge();return Ft({control:n,name:`foreignKeys.${e}`})?(0,a.jsx)(Ot,{control:n,name:`foreignKeys.${e}`,render:({field:o})=>(0,a.jsxs)(dt,{value:o.value?.referencedColumn,onValueChange:l=>o.onChange({...o.value,referencedColumn:l}),disabled:s,children:[(0,a.jsx)(lt,{className:"w-full flex-1",disabled:s||!r?.length,children:(0,a.jsx)(it,{placeholder:r?.length?"Select a column":"No columns found"})}),(0,a.jsx)(ct,{children:r&&r.length>0&&s?(0,a.jsx)(ue,{value:"none",disabled:!0,children:"No columns found"}):r?.flatMap(l=>l.columnName?.trim()?[(0,a.jsx)(ue,{value:l.columnName,children:l.columnName},l.columnName)]:[])})]})}):null},gy=({index:e})=>{const{control:t}=Ge();return(0,a.jsx)(Ot,{control:t,name:`foreignKeys.${e}.onDelete`,defaultValue:"NO ACTION",render:({field:r})=>(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(me,{htmlFor:`foreignKeys.${e}.onDelete`,children:"Action if referenced row is deleted"}),(0,a.jsxs)(dt,{value:r.value,onValueChange:s=>r.onChange(s),children:[(0,a.jsx)(lt,{className:"w-full flex-1",children:(0,a.jsx)(it,{placeholder:"Select an action"})}),(0,a.jsx)(ct,{children:Xd.map(s=>(0,a.jsx)(ue,{value:s.value,children:s.label},s.value))})]})]})})},vy=({index:e})=>{const{control:t}=Ge();return(0,a.jsx)(Ot,{control:t,name:`foreignKeys.${e}.onUpdate`,defaultValue:"NO ACTION",render:({field:r})=>(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(me,{htmlFor:`foreignKeys.${e}.onUpdate`,children:"Action if referenced row is updated"}),(0,a.jsxs)(dt,{value:r.value,onValueChange:s=>r.onChange(s),children:[(0,a.jsx)(lt,{className:"w-full flex-1",children:(0,a.jsx)(it,{placeholder:"Select an action"})}),(0,a.jsx)(ct,{children:Xd.map(s=>(0,a.jsx)(ue,{value:s.value,children:s.label},s.value))})]})]})})},yy=({index:e})=>{const{control:t,watch:r}=Ge(),s=r(`foreignKeys.${e}.referencedTable`),n=Ft({control:t,name:`foreignKeys.${e}`});return!s||!n?null:(0,a.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,a.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Select columns from"," ",(0,a.jsx)("span",{className:"font-mono text-primary",children:n.referencedTable||"Unnamed table"})," ","to reference to"]}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,a.jsx)(me,{htmlFor:`foreignKeys.${e}.columnName`,children:r("tableName")||"Unnamed table"}),(0,a.jsx)(me,{htmlFor:`foreignKeys.${e}.referencedColumn`,children:n.referencedTable||"Unnamed table"})]}),(0,a.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2 flex-1",children:[(0,a.jsx)(Vv,{index:e}),(0,a.jsx)(zn,{className:"size-4 aspect-square text-muted-foreground"})]}),(0,a.jsx)("div",{className:"flex items-center gap-2 flex-1",children:(0,a.jsx)(py,{index:e,tableName:n.referencedTable})})]}),(0,a.jsx)("hr",{className:"my-8 border-border"}),(0,a.jsxs)("div",{className:"flex flex-col gap-6",children:[(0,a.jsx)(vy,{index:e}),(0,a.jsx)(gy,{index:e})]})]})]})},sR=()=>{const e=St(),{selectedDatabase:t}=Me(),{mutateAsync:r,isPending:s,reset:n}=ht({mutationFn:async({tableName:i,cascade:c=!1})=>(await Kp({tableName:i,db:t,cascade:c})).data.data,onSuccess:async()=>{await e.invalidateQueries({queryKey:Ee.lists()})}});return{deleteTable:async i=>{const c=r({tableName:i,cascade:!1});return we.promise(c,{loading:"Deleting table...",success:d=>d.fkViolation?`Table "${i}" has related records`:`Deleted table "${i}" with ${d.deletedCount} rows`,error:d=>d.message||"Failed to delete table"}),c},forceDeleteTable:async i=>{const c=r({tableName:i,cascade:!0});return we.promise(c,{loading:"Deleting table...",success:d=>`Force deleted table "${i}" with ${d.deletedCount} rows`,error:d=>d.message||"Failed to delete table"}),c},isDeletingTable:s,resetDeleteResult:n}},by=()=>{const{selectedDatabase:e,dbType:t}=Me(),{mutateAsync:r,isPending:s}=ht({mutationFn:async({tableName:o,format:l})=>{const i=await Up({tableName:o,format:l,db:e}),c=i.headers["content-disposition"],d=(typeof c=="string"?c:void 0)?.match(/filename="(.+)"/)?.[1]||`${o}_export.${l}`,u=i.headers["content-type"],h=typeof u=="string"?u:"application/octet-stream",m=new Blob([i.data],{type:h}),p=window.URL.createObjectURL(m),b=document.createElement("a");b.href=p,b.download=d,document.body.appendChild(b),b.click(),document.body.removeChild(b),window.URL.revokeObjectURL(p),t&&cr.capture("record_exported",{db_type:t,format:l})}});return{exportFile:async({tableName:o,format:l})=>we.promise(r({tableName:o,format:l}),{loading:"Exporting file...",success:"File exported successfully",error:i=>i.message||"Failed to export file"}),isExportingFile:s}},nR=({tableName:e,schemaName:t})=>{const r=St(),{selectedDatabase:s}=Me(),{mutateAsync:n,isPending:o}=ht({mutationFn:async i=>(await _p({tableName:e,data:{...i,schemaName:t},db:s})).data.data,onSuccess:async()=>{await r.invalidateQueries({queryKey:Ee.lists()}),await r.removeQueries({queryKey:[ce.CACHE_KEYS.TABLE_DATA,e]}),await r.removeQueries({queryKey:[ce.CACHE_KEYS.TABLE_COLUMNS,e]})}});return{renameTable:async(i,c)=>{const d=n(i,c);return we.promise(d,{loading:"Renaming table...",success:u=>u||"Table renamed successfully",error:u=>typeof u.details=="string"&&u.details||u.message||"Failed to rename table"}),d},isRenamingTable:o}},ou=()=>{const{selectedDatabase:e}=Me(),{data:t,isLoading:r,error:s}=Rr({queryKey:Ee.list(e),queryFn:()=>Jp(e),select:n=>n.data.data,enabled:!!e});return{tablesList:t,isLoadingTablesList:r,errorTablesList:s}},xy=365.2425,Sy=Math.pow(10,8)*24*60*60*1e3,aR=-Sy,iu=6048e5,Cy=864e5,wy=3600,lu=wy*24,oR=lu*7,Ny=lu*xy,jy=Ny/12,iR=jy*3,zl=Symbol.for("constructDateFrom");function He(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&zl in e?e[zl](t):e instanceof Date?new e.constructor(t):new Date(t)}function De(e,t){return He(t||e,e)}function qn(e,t,r){const s=De(e,r?.in);return isNaN(t)?He(r?.in||e,NaN):(t&&s.setDate(s.getDate()+t),s)}function cu(e,t,r){const s=De(e,r?.in);if(isNaN(t))return He(r?.in||e,NaN);if(!t)return s;const n=s.getDate(),o=He(r?.in||e,s.getTime());return o.setMonth(s.getMonth()+t+1,0),n>=o.getDate()?o:(s.setFullYear(o.getFullYear(),o.getMonth(),n),s)}var Iy={};function bn(){return Iy}function Ts(e,t){const r=bn(),s=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=De(e,t?.in),o=n.getDay(),l=(o<s?7:0)+o-s;return n.setDate(n.getDate()-l),n.setHours(0,0,0,0),n}function on(e,t){return Ts(e,{...t,weekStartsOn:1})}function du(e,t){const r=De(e,t?.in),s=r.getFullYear(),n=He(r,0);n.setFullYear(s+1,0,4),n.setHours(0,0,0,0);const o=on(n),l=He(r,0);l.setFullYear(s,0,4),l.setHours(0,0,0,0);const i=on(l);return r.getTime()>=o.getTime()?s+1:r.getTime()>=i.getTime()?s:s-1}function $l(e){const t=De(e),r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return r.setUTCFullYear(t.getFullYear()),+e-+r}function _s(e,...t){const r=He.bind(null,e||t.find(s=>typeof s=="object"));return t.map(r)}function Rs(e,t){const r=De(e,t?.in);return r.setHours(0,0,0,0),r}function Mi(e,t,r){const[s,n]=_s(r?.in,e,t),o=Rs(s),l=Rs(n),i=+o-$l(o),c=+l-$l(l);return Math.round((i-c)/Cy)}function Ty(e,t){const r=du(e,t),s=He(t?.in||e,0);return s.setFullYear(r,0,4),s.setHours(0,0,0,0),on(s)}function Ry(e,t,r){return qn(e,t*7,r)}function Ey(e,t,r){return cu(e,t*12,r)}function ky(e,t){let r,s=t?.in;return e.forEach(n=>{!s&&typeof n=="object"&&(s=He.bind(null,n));const o=De(n,s);(!r||r<o||isNaN(+o))&&(r=o)}),He(s,r||NaN)}function Ay(e,t){let r,s=t?.in;return e.forEach(n=>{!s&&typeof n=="object"&&(s=He.bind(null,n));const o=De(n,s);(!r||r>o||isNaN(+o))&&(r=o)}),He(s,r||NaN)}function Oy(e,t,r){const[s,n]=_s(r?.in,e,t);return+Rs(s)==+Rs(n)}function uu(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Dy(e){return!(!uu(e)&&typeof e!="number"||isNaN(+De(e)))}function fu(e,t,r){const[s,n]=_s(r?.in,e,t),o=s.getFullYear()-n.getFullYear(),l=s.getMonth()-n.getMonth();return o*12+l}function My(e,t){const r=De(e,t?.in),s=r.getMonth();return r.setFullYear(r.getFullYear(),s+1,0),r.setHours(23,59,59,999),r}function hu(e,t){const[r,s]=_s(e,t.start,t.end);return{start:r,end:s}}function _y(e,t){const{start:r,end:s}=hu(t?.in,e);let n=+r>+s;const o=n?+r:+s,l=n?s:r;l.setHours(0,0,0,0),l.setDate(1);let i=t?.step??1;if(!i)return[];i<0&&(i=-i,n=!n);const c=[];for(;+l<=o;)c.push(He(r,l)),l.setMonth(l.getMonth()+i);return n?c.reverse():c}function Py(e,t){const r=De(e,t?.in);return r.setDate(1),r.setHours(0,0,0,0),r}function Fy(e,t){const r=De(e,t?.in),s=r.getFullYear();return r.setFullYear(s+1,0,0),r.setHours(23,59,59,999),r}function mu(e,t){const r=De(e,t?.in);return r.setFullYear(r.getFullYear(),0,1),r.setHours(0,0,0,0),r}function Ly(e,t){const{start:r,end:s}=hu(t?.in,e);let n=+r>+s;const o=n?+r:+s,l=n?s:r;l.setHours(0,0,0,0),l.setMonth(0,1);let i=t?.step??1;if(!i)return[];i<0&&(i=-i,n=!n);const c=[];for(;+l<=o;)c.push(He(r,l)),l.setFullYear(l.getFullYear()+i);return n?c.reverse():c}function pu(e,t){const r=bn(),s=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=De(e,t?.in),o=n.getDay(),l=(o<s?-7:0)+6-(o-s);return n.setDate(n.getDate()+l),n.setHours(23,59,59,999),n}function zy(e,t){return pu(e,{...t,weekStartsOn:1})}var $y={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Vy=(e,t,r)=>{let s;const n=$y[e];return typeof n=="string"?s=n:t===1?s=n.one:s=n.other.replace("{{count}}",t.toString()),r?.addSuffix?r.comparison&&r.comparison>0?"in "+s:s+" ago":s};function qa(e){return(t={})=>{const r=t.width?String(t.width):e.defaultWidth;return e.formats[r]||e.formats[e.defaultWidth]}}var By={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Uy={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},qy={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Wy={date:qa({formats:By,defaultWidth:"full"}),time:qa({formats:Uy,defaultWidth:"full"}),dateTime:qa({formats:qy,defaultWidth:"full"})},Ky={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Hy=(e,t,r,s)=>Ky[e];function qs(e){return(t,r)=>{const s=r?.context?String(r.context):"standalone";let n;if(s==="formatting"&&e.formattingValues){const l=e.defaultFormattingWidth||e.defaultWidth,i=r?.width?String(r.width):l;n=e.formattingValues[i]||e.formattingValues[l]}else{const l=e.defaultWidth,i=r?.width?String(r.width):e.defaultWidth;n=e.values[i]||e.values[l]}const o=e.argumentCallback?e.argumentCallback(t):t;return n[o]}}var Gy={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Yy={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Jy={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},Qy={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},Xy={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},Zy={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},e0=(e,t)=>{const r=Number(e),s=r%100;if(s>20||s<10)switch(s%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},t0={ordinalNumber:e0,era:qs({values:Gy,defaultWidth:"wide"}),quarter:qs({values:Yy,defaultWidth:"wide",argumentCallback:e=>e-1}),month:qs({values:Jy,defaultWidth:"wide"}),day:qs({values:Qy,defaultWidth:"wide"}),dayPeriod:qs({values:Xy,defaultWidth:"wide",formattingValues:Zy,defaultFormattingWidth:"wide"})};function Ws(e){return(t,r={})=>{const s=r.width,n=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],o=t.match(n);if(!o)return null;const l=o[0],i=s&&e.parsePatterns[s]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(i)?s0(i,h=>h.test(l)):r0(i,h=>h.test(l));let d;d=e.valueCallback?e.valueCallback(c):c,d=r.valueCallback?r.valueCallback(d):d;const u=t.slice(l.length);return{value:d,rest:u}}}function r0(e,t){for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&t(e[r]))return r}function s0(e,t){for(let r=0;r<e.length;r++)if(t(e[r]))return r}function n0(e){return(t,r={})=>{const s=t.match(e.matchPattern);if(!s)return null;const n=s[0],o=t.match(e.parsePattern);if(!o)return null;let l=e.valueCallback?e.valueCallback(o[0]):o[0];l=r.valueCallback?r.valueCallback(l):l;const i=t.slice(n.length);return{value:l,rest:i}}}var a0=/^(\d+)(th|st|nd|rd)?/i,o0=/\d+/i,i0={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},l0={any:[/^b/i,/^(a|c)/i]},c0={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},d0={any:[/1/i,/2/i,/3/i,/4/i]},u0={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},f0={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},h0={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},m0={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},p0={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},g0={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},v0={ordinalNumber:n0({matchPattern:a0,parsePattern:o0,valueCallback:e=>parseInt(e,10)}),era:Ws({matchPatterns:i0,defaultMatchWidth:"wide",parsePatterns:l0,defaultParseWidth:"any"}),quarter:Ws({matchPatterns:c0,defaultMatchWidth:"wide",parsePatterns:d0,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Ws({matchPatterns:u0,defaultMatchWidth:"wide",parsePatterns:f0,defaultParseWidth:"any"}),day:Ws({matchPatterns:h0,defaultMatchWidth:"wide",parsePatterns:m0,defaultParseWidth:"any"}),dayPeriod:Ws({matchPatterns:p0,defaultMatchWidth:"any",parsePatterns:g0,defaultParseWidth:"any"})},Cs={code:"en-US",formatDistance:Vy,formatLong:Wy,formatRelative:Hy,localize:t0,match:v0,options:{weekStartsOn:0,firstWeekContainsDate:1}};function y0(e,t){const r=De(e,t?.in);return Mi(r,mu(r))+1}function _i(e,t){const r=De(e,t?.in),s=+on(r)-+Ty(r);return Math.round(s/iu)+1}function gu(e,t){const r=De(e,t?.in),s=r.getFullYear(),n=bn(),o=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,l=He(t?.in||e,0);l.setFullYear(s+1,0,o),l.setHours(0,0,0,0);const i=Ts(l,t),c=He(t?.in||e,0);c.setFullYear(s,0,o),c.setHours(0,0,0,0);const d=Ts(c,t);return+r>=+i?s+1:+r>=+d?s:s-1}function b0(e,t){const r=bn(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=gu(e,t),o=He(t?.in||e,0);return o.setFullYear(n,0,s),o.setHours(0,0,0,0),Ts(o,t)}function Pi(e,t){const r=De(e,t?.in),s=+Ts(r,t)-+b0(r,t);return Math.round(s/iu)+1}function Te(e,t){return(e<0?"-":"")+Math.abs(e).toString().padStart(t,"0")}var jr={y(e,t){const r=e.getFullYear(),s=r>0?r:1-r;return Te(t==="yy"?s%100:s,t.length)},M(e,t){const r=e.getMonth();return t==="M"?String(r+1):Te(r+1,2)},d(e,t){return Te(e.getDate(),t.length)},a(e,t){const r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];default:return r==="am"?"a.m.":"p.m."}},h(e,t){return Te(e.getHours()%12||12,t.length)},H(e,t){return Te(e.getHours(),t.length)},m(e,t){return Te(e.getMinutes(),t.length)},s(e,t){return Te(e.getSeconds(),t.length)},S(e,t){const r=t.length,s=e.getMilliseconds(),n=Math.trunc(s*Math.pow(10,r-3));return Te(n,t.length)}},ys={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Vl={G:function(e,t,r){const s=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return r.era(s,{width:"abbreviated"});case"GGGGG":return r.era(s,{width:"narrow"});default:return r.era(s,{width:"wide"})}},y:function(e,t,r){if(t==="yo"){const s=e.getFullYear(),n=s>0?s:1-s;return r.ordinalNumber(n,{unit:"year"})}return jr.y(e,t)},Y:function(e,t,r,s){const n=gu(e,s),o=n>0?n:1-n;if(t==="YY"){const l=o%100;return Te(l,2)}return t==="Yo"?r.ordinalNumber(o,{unit:"year"}):Te(o,t.length)},R:function(e,t){const r=du(e);return Te(r,t.length)},u:function(e,t){const r=e.getFullYear();return Te(r,t.length)},Q:function(e,t,r){const s=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(s);case"QQ":return Te(s,2);case"Qo":return r.ordinalNumber(s,{unit:"quarter"});case"QQQ":return r.quarter(s,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(s,{width:"narrow",context:"formatting"});default:return r.quarter(s,{width:"wide",context:"formatting"})}},q:function(e,t,r){const s=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(s);case"qq":return Te(s,2);case"qo":return r.ordinalNumber(s,{unit:"quarter"});case"qqq":return r.quarter(s,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(s,{width:"narrow",context:"standalone"});default:return r.quarter(s,{width:"wide",context:"standalone"})}},M:function(e,t,r){const s=e.getMonth();switch(t){case"M":case"MM":return jr.M(e,t);case"Mo":return r.ordinalNumber(s+1,{unit:"month"});case"MMM":return r.month(s,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(s,{width:"narrow",context:"formatting"});default:return r.month(s,{width:"wide",context:"formatting"})}},L:function(e,t,r){const s=e.getMonth();switch(t){case"L":return String(s+1);case"LL":return Te(s+1,2);case"Lo":return r.ordinalNumber(s+1,{unit:"month"});case"LLL":return r.month(s,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(s,{width:"narrow",context:"standalone"});default:return r.month(s,{width:"wide",context:"standalone"})}},w:function(e,t,r,s){const n=Pi(e,s);return t==="wo"?r.ordinalNumber(n,{unit:"week"}):Te(n,t.length)},I:function(e,t,r){const s=_i(e);return t==="Io"?r.ordinalNumber(s,{unit:"week"}):Te(s,t.length)},d:function(e,t,r){return t==="do"?r.ordinalNumber(e.getDate(),{unit:"date"}):jr.d(e,t)},D:function(e,t,r){const s=y0(e);return t==="Do"?r.ordinalNumber(s,{unit:"dayOfYear"}):Te(s,t.length)},E:function(e,t,r){const s=e.getDay();switch(t){case"E":case"EE":case"EEE":return r.day(s,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(s,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(s,{width:"short",context:"formatting"});default:return r.day(s,{width:"wide",context:"formatting"})}},e:function(e,t,r,s){const n=e.getDay(),o=(n-s.weekStartsOn+8)%7||7;switch(t){case"e":return String(o);case"ee":return Te(o,2);case"eo":return r.ordinalNumber(o,{unit:"day"});case"eee":return r.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(n,{width:"short",context:"formatting"});default:return r.day(n,{width:"wide",context:"formatting"})}},c:function(e,t,r,s){const n=e.getDay(),o=(n-s.weekStartsOn+8)%7||7;switch(t){case"c":return String(o);case"cc":return Te(o,t.length);case"co":return r.ordinalNumber(o,{unit:"day"});case"ccc":return r.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(n,{width:"narrow",context:"standalone"});case"cccccc":return r.day(n,{width:"short",context:"standalone"});default:return r.day(n,{width:"wide",context:"standalone"})}},i:function(e,t,r){const s=e.getDay(),n=s===0?7:s;switch(t){case"i":return String(n);case"ii":return Te(n,t.length);case"io":return r.ordinalNumber(n,{unit:"day"});case"iii":return r.day(s,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(s,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(s,{width:"short",context:"formatting"});default:return r.day(s,{width:"wide",context:"formatting"})}},a:function(e,t,r){const s=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(s,{width:"narrow",context:"formatting"});default:return r.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(e,t,r){const s=e.getHours();let n;switch(s===12?n=ys.noon:s===0?n=ys.midnight:n=s/12>=1?"pm":"am",t){case"b":case"bb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(e,t,r){const s=e.getHours();let n;switch(s>=17?n=ys.evening:s>=12?n=ys.afternoon:s>=4?n=ys.morning:n=ys.night,t){case"B":case"BB":case"BBB":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(e,t,r){if(t==="ho"){let s=e.getHours()%12;return s===0&&(s=12),r.ordinalNumber(s,{unit:"hour"})}return jr.h(e,t)},H:function(e,t,r){return t==="Ho"?r.ordinalNumber(e.getHours(),{unit:"hour"}):jr.H(e,t)},K:function(e,t,r){const s=e.getHours()%12;return t==="Ko"?r.ordinalNumber(s,{unit:"hour"}):Te(s,t.length)},k:function(e,t,r){let s=e.getHours();return s===0&&(s=24),t==="ko"?r.ordinalNumber(s,{unit:"hour"}):Te(s,t.length)},m:function(e,t,r){return t==="mo"?r.ordinalNumber(e.getMinutes(),{unit:"minute"}):jr.m(e,t)},s:function(e,t,r){return t==="so"?r.ordinalNumber(e.getSeconds(),{unit:"second"}):jr.s(e,t)},S:function(e,t){return jr.S(e,t)},X:function(e,t,r){const s=e.getTimezoneOffset();if(s===0)return"Z";switch(t){case"X":return Ul(s);case"XXXX":case"XX":return Br(s);default:return Br(s,":")}},x:function(e,t,r){const s=e.getTimezoneOffset();switch(t){case"x":return Ul(s);case"xxxx":case"xx":return Br(s);default:return Br(s,":")}},O:function(e,t,r){const s=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Bl(s,":");default:return"GMT"+Br(s,":")}},z:function(e,t,r){const s=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Bl(s,":");default:return"GMT"+Br(s,":")}},t:function(e,t,r){const s=Math.trunc(+e/1e3);return Te(s,t.length)},T:function(e,t,r){return Te(+e,t.length)}};function Bl(e,t=""){const r=e>0?"-":"+",s=Math.abs(e),n=Math.trunc(s/60),o=s%60;return o===0?r+String(n):r+String(n)+t+Te(o,2)}function Ul(e,t){return e%60===0?(e>0?"-":"+")+Te(Math.abs(e)/60,2):Br(e,t)}function Br(e,t=""){const r=e>0?"-":"+",s=Math.abs(e),n=Te(Math.trunc(s/60),2),o=Te(s%60,2);return r+n+t+o}var ql=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});default:return t.date({width:"full"})}},vu=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});default:return t.time({width:"full"})}},x0=(e,t)=>{const r=e.match(/(P+)(p+)?/)||[],s=r[1],n=r[2];if(!n)return ql(e,t);let o;switch(s){case"P":o=t.dateTime({width:"short"});break;case"PP":o=t.dateTime({width:"medium"});break;case"PPP":o=t.dateTime({width:"long"});break;default:o=t.dateTime({width:"full"})}return o.replace("{{date}}",ql(s,t)).replace("{{time}}",vu(n,t))},S0={p:vu,P:x0},C0=/^D+$/,w0=/^Y+$/,N0=["D","DD","YY","YYYY"];function j0(e){return C0.test(e)}function I0(e){return w0.test(e)}function T0(e,t,r){const s=R0(e,t,r);if(console.warn(s),N0.includes(e))throw new RangeError(s)}function R0(e,t,r){const s=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${s} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var E0=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,k0=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,A0=/^'([^]*?)'?$/,O0=/''/g,D0=/[a-zA-Z]/;function lr(e,t,r){const s=bn(),n=r?.locale??s.locale??Cs,o=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,l=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??s.weekStartsOn??s.locale?.options?.weekStartsOn??0,i=De(e,r?.in);if(!Dy(i))throw new RangeError("Invalid time value");let c=t.match(k0).map(u=>{const h=u[0];if(h==="p"||h==="P"){const m=S0[h];return m(u,n.formatLong)}return u}).join("").match(E0).map(u=>{if(u==="''")return{isToken:!1,value:"'"};const h=u[0];if(h==="'")return{isToken:!1,value:M0(u)};if(Vl[h])return{isToken:!0,value:u};if(h.match(D0))throw new RangeError("Format string contains an unescaped latin alphabet character `"+h+"`");return{isToken:!1,value:u}});n.localize.preprocessor&&(c=n.localize.preprocessor(i,c));const d={firstWeekContainsDate:o,weekStartsOn:l,locale:n};return c.map(u=>{if(!u.isToken)return u.value;const h=u.value;(!r?.useAdditionalWeekYearTokens&&I0(h)||!r?.useAdditionalDayOfYearTokens&&j0(h))&&T0(h,t,String(e));const m=Vl[h[0]];return m(i,h,n.localize,d)}).join("")}function M0(e){const t=e.match(A0);return t?t[1].replace(O0,"'"):e}function _0(e,t){const r=De(e,t?.in),s=r.getFullYear(),n=r.getMonth(),o=He(r,0);return o.setFullYear(s,n+1,0),o.setHours(0,0,0,0),o.getDate()}function P0(e,t){return De(e,t?.in).getMonth()}function F0(e,t){return De(e,t?.in).getFullYear()}function L0(e,t){return+De(e)>+De(t)}function z0(e,t){return+De(e)<+De(t)}function $0(e,t,r){const[s,n]=_s(r?.in,e,t);return s.getFullYear()===n.getFullYear()&&s.getMonth()===n.getMonth()}function V0(e,t,r){const[s,n]=_s(r?.in,e,t);return s.getFullYear()===n.getFullYear()}function B0(e,t,r){const s=De(e,r?.in),n=s.getFullYear(),o=s.getDate(),l=He(r?.in||e,0);l.setFullYear(n,t,15),l.setHours(0,0,0,0);const i=_0(l);return s.setMonth(t,Math.min(o,i)),s}function U0(e,t,r){const s=De(e,r?.in);return isNaN(+s)?He(r?.in||e,NaN):(s.setFullYear(t),s)}function q0(e,t,r="long"){return new Intl.DateTimeFormat("en-US",{hour:"numeric",timeZone:e,timeZoneName:r}).format(t).split(/\s/g).slice(2).join(" ")}var W0={},Js={};function Kr(e,t){try{const r=(W0[e]||=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"}).format)(t).split("GMT")[1];return r in Js?Js[r]:Wl(r,r.split(":"))}catch{if(e in Js)return Js[e];const r=e?.match(K0);return r?Wl(e,r.slice(1)):NaN}}var K0=/([+-]\d\d):?(\d\d)?/;function Wl(e,t){const r=+(t[0]||0),s=+(t[1]||0),n=+(t[2]||0)/60;return Js[e]=r*60+s>0?r*60+s+n:r*60-s-n}var Qs=class Xs extends Date{constructor(...t){super(),t.length>1&&typeof t[t.length-1]=="string"&&(this.timeZone=t.pop()),this.internal=new Date,isNaN(Kr(this.timeZone,this))?this.setTime(NaN):t.length?typeof t[0]=="number"&&(t.length===1||t.length===2&&typeof t[1]!="number")?this.setTime(t[0]):typeof t[0]=="string"?this.setTime(+new Date(t[0])):t[0]instanceof Date?this.setTime(+t[0]):(this.setTime(+new Date(...t)),yu(this,NaN),_o(this)):this.setTime(Date.now())}static tz(t,...r){return r.length?new Xs(...r,t):new Xs(Date.now(),t)}withTimeZone(t){return new Xs(+this,t)}getTimezoneOffset(){const t=-Kr(this.timeZone,this);return t>0?Math.floor(t):Math.ceil(t)}setTime(t){return Date.prototype.setTime.apply(this,arguments),_o(this),+this}[Symbol.for("constructDateFrom")](t){return new Xs(+new Date(t),this.timeZone)}},Kl=/^(get|set)(?!UTC)/;Object.getOwnPropertyNames(Date.prototype).forEach(e=>{if(!Kl.test(e))return;const t=e.replace(Kl,"$1UTC");Qs.prototype[t]&&(e.startsWith("get")?Qs.prototype[e]=function(){return this.internal[t]()}:(Qs.prototype[e]=function(){return Date.prototype[t].apply(this.internal,arguments),H0(this),+this},Qs.prototype[t]=function(){return Date.prototype[t].apply(this,arguments),_o(this),+this}))});function _o(e){e.internal.setTime(+e),e.internal.setUTCSeconds(e.internal.getUTCSeconds()-Math.round(-Kr(e.timeZone,e)*60))}function H0(e){Date.prototype.setFullYear.call(e,e.internal.getUTCFullYear(),e.internal.getUTCMonth(),e.internal.getUTCDate()),Date.prototype.setHours.call(e,e.internal.getUTCHours(),e.internal.getUTCMinutes(),e.internal.getUTCSeconds(),e.internal.getUTCMilliseconds()),yu(e)}function yu(e){const t=Kr(e.timeZone,e),r=t>0?Math.floor(t):Math.ceil(t),s=new Date(+e);s.setUTCHours(s.getUTCHours()-1);const n=-new Date(+e).getTimezoneOffset(),o=n- -new Date(+s).getTimezoneOffset(),l=Date.prototype.getHours.apply(e)!==e.internal.getUTCHours();o&&l&&e.internal.setUTCMinutes(e.internal.getUTCMinutes()+o);const i=n-r;i&&Date.prototype.setUTCMinutes.call(e,Date.prototype.getUTCMinutes.call(e)+i);const c=new Date(+e);c.setUTCSeconds(0);const d=n>0?c.getSeconds():(c.getSeconds()-60)%60,u=Math.round(-(Kr(e.timeZone,e)*60))%60;(u||d)&&(e.internal.setUTCSeconds(e.internal.getUTCSeconds()+u),Date.prototype.setUTCSeconds.call(e,Date.prototype.getUTCSeconds.call(e)+u+d));const h=Kr(e.timeZone,e),m=h>0?Math.floor(h):Math.ceil(h),p=-new Date(+e).getTimezoneOffset()-m,b=m!==r,w=p-i;if(b&&w){Date.prototype.setUTCMinutes.call(e,Date.prototype.getUTCMinutes.call(e)+w);const x=Kr(e.timeZone,e),N=m-(x>0?Math.floor(x):Math.ceil(x));N&&(e.internal.setUTCMinutes(e.internal.getUTCMinutes()+N),Date.prototype.setUTCMinutes.call(e,Date.prototype.getUTCMinutes.call(e)+N))}}var Pt=class Zs extends Qs{static tz(t,...r){return r.length?new Zs(...r,t):new Zs(Date.now(),t)}toISOString(){const[t,r,s]=this.tzComponents(),n=`${t}${r}:${s}`;return this.internal.toISOString().slice(0,-1)+n}toString(){return`${this.toDateString()} ${this.toTimeString()}`}toDateString(){const[t,r,s,n]=this.internal.toUTCString().split(" ");return`${t?.slice(0,-1)} ${s} ${r} ${n}`}toTimeString(){const t=this.internal.toUTCString().split(" ")[4],[r,s,n]=this.tzComponents();return`${t} GMT${r}${s}${n} (${q0(this.timeZone,this)})`}toLocaleString(t,r){return Date.prototype.toLocaleString.call(this,t,{...r,timeZone:r?.timeZone||this.timeZone})}toLocaleDateString(t,r){return Date.prototype.toLocaleDateString.call(this,t,{...r,timeZone:r?.timeZone||this.timeZone})}toLocaleTimeString(t,r){return Date.prototype.toLocaleTimeString.call(this,t,{...r,timeZone:r?.timeZone||this.timeZone})}tzComponents(){const t=this.getTimezoneOffset();return[t>0?"-":"+",String(Math.floor(Math.abs(t)/60)).padStart(2,"0"),String(Math.abs(t)%60).padStart(2,"0")]}withTimeZone(t){return new Zs(+this,t)}[Symbol.for("constructDateFrom")](t){return new Zs(+new Date(t),this.timeZone)}},G0=5,Y0=4;function J0(e,t){const r=t.startOfMonth(e),s=r.getDay()>0?r.getDay():7,n=t.addDays(e,-s+1),o=t.addDays(n,34);return t.getMonth(e)===t.getMonth(o)?G0:Y0}function bu(e,t){const r=t.startOfMonth(e),s=r.getDay();return s===1?r:s===0?t.addDays(r,-6):t.addDays(r,-1*(s-1))}function Q0(e,t){const r=bu(e,t),s=J0(e,t);return t.addDays(r,s*7-1)}var xu={...Cs,labels:{labelDayButton:(e,t,r,s)=>{let n;s&&typeof s.format=="function"?n=s.format.bind(s):n=(l,i)=>lr(l,i,{locale:Cs,...r});let o=n(e,"PPPP");return t.today&&(o=`Today, ${o}`),t.selected&&(o=`${o}, selected`),o},labelMonthDropdown:"Choose the Month",labelNext:"Go to the Next Month",labelPrevious:"Go to the Previous Month",labelWeekNumber:e=>`Week ${e}`,labelYearDropdown:"Choose the Year",labelGrid:(e,t,r)=>{let s;return r&&typeof r.format=="function"?s=r.format.bind(r):s=(n,o)=>lr(n,o,{locale:Cs,...t}),s(e,"LLLL yyyy")},labelGridcell:(e,t,r,s)=>{let n;s&&typeof s.format=="function"?n=s.format.bind(s):n=(l,i)=>lr(l,i,{locale:Cs,...r});let o=n(e,"PPPP");return t?.today&&(o=`Today, ${o}`),o},labelNav:"Navigation bar",labelWeekNumberHeader:"Week Number",labelWeekday:(e,t,r)=>{let s;return r&&typeof r.format=="function"?s=r.format.bind(r):s=(n,o)=>lr(n,o,{locale:Cs,...t}),s(e,"cccc")}}},fr=class Po{constructor(t,r){this.today=()=>this.overrides?.today?this.overrides.today():this.options.timeZone?Pt.tz(this.options.timeZone):new(this.options.Date??Date),this.newDate=(s,n,o)=>this.overrides?.newDate?this.overrides.newDate(s,n,o):this.options.timeZone?new Pt(s,n,o,this.options.timeZone):new Date(s,n,o),this.addDays=(s,n)=>this.overrides?.addDays?this.overrides.addDays(s,n):qn(s,n),this.addMonths=(s,n)=>this.overrides?.addMonths?this.overrides.addMonths(s,n):cu(s,n),this.addWeeks=(s,n)=>this.overrides?.addWeeks?this.overrides.addWeeks(s,n):Ry(s,n),this.addYears=(s,n)=>this.overrides?.addYears?this.overrides.addYears(s,n):Ey(s,n),this.differenceInCalendarDays=(s,n)=>this.overrides?.differenceInCalendarDays?this.overrides.differenceInCalendarDays(s,n):Mi(s,n),this.differenceInCalendarMonths=(s,n)=>this.overrides?.differenceInCalendarMonths?this.overrides.differenceInCalendarMonths(s,n):fu(s,n),this.eachMonthOfInterval=s=>this.overrides?.eachMonthOfInterval?this.overrides.eachMonthOfInterval(s):_y(s),this.eachYearOfInterval=s=>{const n=this.overrides?.eachYearOfInterval?this.overrides.eachYearOfInterval(s):Ly(s),o=new Set(n.map(i=>this.getYear(i)));if(o.size===n.length)return n;const l=[];return o.forEach(i=>{l.push(new Date(i,0,1))}),l},this.endOfBroadcastWeek=s=>this.overrides?.endOfBroadcastWeek?this.overrides.endOfBroadcastWeek(s):Q0(s,this),this.endOfISOWeek=s=>this.overrides?.endOfISOWeek?this.overrides.endOfISOWeek(s):zy(s),this.endOfMonth=s=>this.overrides?.endOfMonth?this.overrides.endOfMonth(s):My(s),this.endOfWeek=(s,n)=>this.overrides?.endOfWeek?this.overrides.endOfWeek(s,n):pu(s,this.options),this.endOfYear=s=>this.overrides?.endOfYear?this.overrides.endOfYear(s):Fy(s),this.format=(s,n,o)=>{const l=this.overrides?.format?this.overrides.format(s,n,this.options):lr(s,n,this.options);return this.options.numerals&&this.options.numerals!=="latn"?this.replaceDigits(l):l},this.getISOWeek=s=>this.overrides?.getISOWeek?this.overrides.getISOWeek(s):_i(s),this.getMonth=(s,n)=>this.overrides?.getMonth?this.overrides.getMonth(s,this.options):P0(s,this.options),this.getYear=(s,n)=>this.overrides?.getYear?this.overrides.getYear(s,this.options):F0(s,this.options),this.getWeek=(s,n)=>this.overrides?.getWeek?this.overrides.getWeek(s,this.options):Pi(s,this.options),this.isAfter=(s,n)=>this.overrides?.isAfter?this.overrides.isAfter(s,n):L0(s,n),this.isBefore=(s,n)=>this.overrides?.isBefore?this.overrides.isBefore(s,n):z0(s,n),this.isDate=s=>this.overrides?.isDate?this.overrides.isDate(s):uu(s),this.isSameDay=(s,n)=>this.overrides?.isSameDay?this.overrides.isSameDay(s,n):Oy(s,n),this.isSameMonth=(s,n)=>this.overrides?.isSameMonth?this.overrides.isSameMonth(s,n):$0(s,n),this.isSameYear=(s,n)=>this.overrides?.isSameYear?this.overrides.isSameYear(s,n):V0(s,n),this.max=s=>this.overrides?.max?this.overrides.max(s):ky(s),this.min=s=>this.overrides?.min?this.overrides.min(s):Ay(s),this.setMonth=(s,n)=>this.overrides?.setMonth?this.overrides.setMonth(s,n):B0(s,n),this.setYear=(s,n)=>this.overrides?.setYear?this.overrides.setYear(s,n):U0(s,n),this.startOfBroadcastWeek=(s,n)=>this.overrides?.startOfBroadcastWeek?this.overrides.startOfBroadcastWeek(s,this):bu(s,this),this.startOfDay=s=>this.overrides?.startOfDay?this.overrides.startOfDay(s):Rs(s),this.startOfISOWeek=s=>this.overrides?.startOfISOWeek?this.overrides.startOfISOWeek(s):on(s),this.startOfMonth=s=>this.overrides?.startOfMonth?this.overrides.startOfMonth(s):Py(s),this.startOfWeek=(s,n)=>this.overrides?.startOfWeek?this.overrides.startOfWeek(s,this.options):Ts(s,this.options),this.startOfYear=s=>this.overrides?.startOfYear?this.overrides.startOfYear(s):mu(s),this.options={locale:xu,...t},this.overrides=r}getDigitMap(){const{numerals:t="latn"}=this.options,r=new Intl.NumberFormat("en-US",{numberingSystem:t}),s={};for(let n=0;n<10;n++)s[n.toString()]=r.format(n);return s}replaceDigits(t){const r=this.getDigitMap();return t.replace(/\d/g,s=>r[s]||s)}formatNumber(t){return this.replaceDigits(t.toString())}getMonthYearOrder(){const t=this.options.locale?.code;return t&&Po.yearFirstLocales.has(t)?"year-first":"month-first"}formatMonthYear(t){const{locale:r,timeZone:s,numerals:n}=this.options,o=r?.code;if(o&&Po.yearFirstLocales.has(o))try{return new Intl.DateTimeFormat(o,{month:"long",year:"numeric",timeZone:s,numberingSystem:n}).format(t)}catch{}const l=this.getMonthYearOrder()==="year-first"?"y LLLL":"LLLL y";return this.format(t,l)}};fr.yearFirstLocales=new Set(["eu","hu","ja","ja-Hira","ja-JP","ko","ko-KR","lt","lt-LT","lv","lv-LV","mn","mn-MN","zh","zh-CN","zh-HK","zh-TW"]);var hr=new fr,Su=class{constructor(e,t,r=hr){this.date=e,this.displayMonth=t,this.outside=!!(t&&!r.isSameMonth(e,t)),this.dateLib=r,this.isoDate=r.format(e,"yyyy-MM-dd"),this.displayMonthId=r.format(t,"yyyy-MM"),this.dateMonthId=r.format(e,"yyyy-MM")}isEqualTo(e){return this.dateLib.isSameDay(e.date,this.date)&&this.dateLib.isSameMonth(e.displayMonth,this.displayMonth)}},X0=class{constructor(e,t){this.date=e,this.weeks=t}},Z0=class{constructor(e,t){this.days=t,this.weekNumber=e}};function eb(e){return f.createElement("span",{...e})}function tb(e){const{size:t=24,orientation:r="left",className:s,style:n}=e;return f.createElement("svg",{className:s,style:n,width:t,height:t,viewBox:"0 0 24 24"},r==="up"&&f.createElement("polygon",{points:"6.77 17 12.5 11.43 18.24 17 20 15.28 12.5 8 5 15.28"}),r==="down"&&f.createElement("polygon",{points:"6.77 8 12.5 13.57 18.24 8 20 9.72 12.5 17 5 9.72"}),r==="left"&&f.createElement("polygon",{points:"16 18.112 9.81111111 12 16 5.87733333 14.0888889 4 6 12 14.0888889 20"}),r==="right"&&f.createElement("polygon",{points:"8 18.112 14.18888889 12 8 5.87733333 9.91111111 4 18 12 9.91111111 20"}))}function rb(e){const{day:t,modifiers:r,...s}=e;return f.createElement("td",{...s})}function sb(e){const{day:t,modifiers:r,...s}=e,n=f.useRef(null);return f.useEffect(()=>{r.focused&&n.current?.focus()},[r.focused]),f.createElement("button",{ref:n,...s})}var X;(function(e){e.Root="root",e.Chevron="chevron",e.Day="day",e.DayButton="day_button",e.CaptionLabel="caption_label",e.Dropdowns="dropdowns",e.Dropdown="dropdown",e.DropdownRoot="dropdown_root",e.Footer="footer",e.MonthGrid="month_grid",e.MonthCaption="month_caption",e.MonthsDropdown="months_dropdown",e.Month="month",e.Months="months",e.Nav="nav",e.NextMonthButton="button_next",e.PreviousMonthButton="button_previous",e.Week="week",e.Weeks="weeks",e.Weekday="weekday",e.Weekdays="weekdays",e.WeekNumber="week_number",e.WeekNumberHeader="week_number_header",e.YearsDropdown="years_dropdown"})(X||(X={}));var $e;(function(e){e.disabled="disabled",e.hidden="hidden",e.outside="outside",e.focused="focused",e.today="today"})($e||($e={}));var Yt;(function(e){e.range_end="range_end",e.range_middle="range_middle",e.range_start="range_start",e.selected="selected"})(Yt||(Yt={}));var It;(function(e){e.weeks_before_enter="weeks_before_enter",e.weeks_before_exit="weeks_before_exit",e.weeks_after_enter="weeks_after_enter",e.weeks_after_exit="weeks_after_exit",e.caption_after_enter="caption_after_enter",e.caption_after_exit="caption_after_exit",e.caption_before_enter="caption_before_enter",e.caption_before_exit="caption_before_exit"})(It||(It={}));var Cu=(0,f.createContext)(void 0);function ma(){const e=(0,f.useContext)(Cu);if(e===void 0)throw new Error("useDayPicker() must be used within a custom component.");return e}function nb(e){const{options:t,className:r,...s}=e,{classNames:n,components:o,styles:l}=ma(),i=[n[X.Dropdown],r].join(" "),c=t?.find(({value:d})=>d===s.value);return f.createElement("span",{"data-disabled":s.disabled,className:n[X.DropdownRoot],style:l?.[X.DropdownRoot]},f.createElement(o.Select,{className:i,...s},t?.map(({value:d,label:u,disabled:h})=>f.createElement(o.Option,{key:d,value:d,disabled:h},u))),f.createElement("span",{className:n[X.CaptionLabel],style:l?.[X.CaptionLabel],"aria-hidden":!0},c?.label,f.createElement(o.Chevron,{orientation:"down",size:18,className:n[X.Chevron],style:l?.[X.Chevron]})))}function ab(e){return f.createElement("div",{...e})}function ob(e){return f.createElement("div",{...e})}function ib(e){const{calendarMonth:t,displayIndex:r,...s}=e;return f.createElement("div",{...s},e.children)}function lb(e){const{calendarMonth:t,displayIndex:r,...s}=e;return f.createElement("div",{...s})}function cb(e){return f.createElement("table",{...e})}function db(e){return f.createElement("div",{...e})}function ub(e){const{components:t}=ma();return f.createElement(t.Dropdown,{...e})}function fb(e){const{onPreviousClick:t,onNextClick:r,previousMonth:s,nextMonth:n,...o}=e,{components:l,classNames:i,styles:c,labels:{labelPrevious:d,labelNext:u}}=ma(),h=(0,f.useCallback)(p=>{n&&r?.(p)},[n,r]),m=(0,f.useCallback)(p=>{s&&t?.(p)},[s,t]);return f.createElement("nav",{...o},f.createElement(l.PreviousMonthButton,{type:"button",className:i[X.PreviousMonthButton],style:c?.[X.PreviousMonthButton],tabIndex:s?void 0:-1,"aria-disabled":s?void 0:!0,"aria-label":d(s),onClick:m},f.createElement(l.Chevron,{disabled:s?void 0:!0,className:i[X.Chevron],style:c?.[X.Chevron],orientation:"left"})),f.createElement(l.NextMonthButton,{type:"button",className:i[X.NextMonthButton],style:c?.[X.NextMonthButton],tabIndex:n?void 0:-1,"aria-disabled":n?void 0:!0,"aria-label":u(n),onClick:h},f.createElement(l.Chevron,{disabled:n?void 0:!0,orientation:"right",className:i[X.Chevron],style:c?.[X.Chevron]})))}function hb(e){return f.createElement("button",{...e})}function mb(e){return f.createElement("option",{...e})}function pb(e){return f.createElement("button",{...e})}function gb(e){const{rootRef:t,...r}=e;return f.createElement("div",{...r,ref:t})}function vb(e){return f.createElement("select",{...e})}function yb(e){const{week:t,...r}=e;return f.createElement("tr",{...r})}function bb(e){return f.createElement("th",{...e})}function xb(e){return f.createElement("thead",{"aria-hidden":!0},f.createElement("tr",{...e}))}function Sb(e){const{week:t,...r}=e;return f.createElement("th",{...r})}function Cb(e){return f.createElement("th",{...e})}function wb(e){return f.createElement("tbody",{...e})}function Nb(e){const{components:t}=ma();return f.createElement(t.Dropdown,{...e})}var jb=ti({CaptionLabel:()=>eb,Chevron:()=>tb,Day:()=>rb,DayButton:()=>sb,Dropdown:()=>nb,DropdownNav:()=>ab,Footer:()=>ob,Month:()=>ib,MonthCaption:()=>lb,MonthGrid:()=>cb,Months:()=>db,MonthsDropdown:()=>ub,Nav:()=>fb,NextMonthButton:()=>hb,Option:()=>mb,PreviousMonthButton:()=>pb,Root:()=>gb,Select:()=>vb,Week:()=>yb,WeekNumber:()=>Sb,WeekNumberHeader:()=>Cb,Weekday:()=>bb,Weekdays:()=>xb,Weeks:()=>wb,YearsDropdown:()=>Nb});function yr(e,t,r=!1,s=hr){let{from:n,to:o}=e;const{differenceInCalendarDays:l,isSameDay:i}=s;return n&&o?(l(o,n)<0&&([n,o]=[o,n]),l(t,n)>=(r?1:0)&&l(o,t)>=(r?1:0)):!r&&o?i(o,t):!r&&n?i(n,t):!1}function Fi(e){return!!(e&&typeof e=="object"&&"before"in e&&"after"in e)}function pa(e){return!!(e&&typeof e=="object"&&"from"in e)}function Li(e){return!!(e&&typeof e=="object"&&"after"in e)}function zi(e){return!!(e&&typeof e=="object"&&"before"in e)}function wu(e){return!!(e&&typeof e=="object"&&"dayOfWeek"in e)}function Nu(e,t){return Array.isArray(e)&&e.every(t.isDate)}function br(e,t,r=hr){const s=Array.isArray(t)?t:[t],{isSameDay:n,differenceInCalendarDays:o,isAfter:l}=r;return s.some(i=>{if(typeof i=="boolean")return i;if(r.isDate(i))return n(e,i);if(Nu(i,r))return i.some(c=>n(e,c));if(pa(i))return yr(i,e,!1,r);if(wu(i))return Array.isArray(i.dayOfWeek)?i.dayOfWeek.includes(e.getDay()):i.dayOfWeek===e.getDay();if(Fi(i)){const c=o(i.before,e),d=o(i.after,e),u=c>0,h=d<0;return l(i.before,i.after)?h&&u:u||h}return Li(i)?o(e,i.after)>0:zi(i)?o(i.before,e)>0:typeof i=="function"?i(e):!1})}function Ib(e,t,r,s,n){const{disabled:o,hidden:l,modifiers:i,showOutsideDays:c,broadcastCalendar:d,today:u=n.today()}=t,{isSameDay:h,isSameMonth:m,startOfMonth:p,isBefore:b,endOfMonth:w,isAfter:x}=n,N=r&&p(r),C=s&&w(s),S={[$e.focused]:[],[$e.outside]:[],[$e.disabled]:[],[$e.hidden]:[],[$e.today]:[]},g={};for(const v of e){const{date:y,displayMonth:R}=v,I=!!(R&&!m(y,R)),k=!!(N&&b(y,N)),T=!!(C&&x(y,C)),D=!!(o&&br(y,o,n)),_=!!(l&&br(y,l,n))||k||T||!d&&!c&&I||d&&c===!1&&I,O=h(y,u);I&&S.outside.push(v),D&&S.disabled.push(v),_&&S.hidden.push(v),O&&S.today.push(v),i&&Object.keys(i).forEach(F=>{const E=i?.[F];E&&br(y,E,n)&&(g[F]?g[F].push(v):g[F]=[v])})}return v=>{const y={[$e.focused]:!1,[$e.disabled]:!1,[$e.hidden]:!1,[$e.outside]:!1,[$e.today]:!1},R={};for(const I in S)y[I]=S[I].some(k=>k===v);for(const I in g)R[I]=g[I].some(k=>k===v);return{...y,...R}}}function Tb(e,t,r={}){return Object.entries(e).filter(([,s])=>s===!0).reduce((s,[n])=>(r[n]?s.push(r[n]):t[$e[n]]?s.push(t[$e[n]]):t[Yt[n]]&&s.push(t[Yt[n]]),s),[t[X.Day]])}function Rb(e){return{...jb,...e}}function Eb(e){const t={"data-mode":e.mode??void 0,"data-required":"required"in e?e.required:void 0,"data-multiple-months":e.numberOfMonths&&e.numberOfMonths>1||void 0,"data-week-numbers":e.showWeekNumber||void 0,"data-broadcast-calendar":e.broadcastCalendar||void 0,"data-nav-layout":e.navLayout||void 0};return Object.entries(e).forEach(([r,s])=>{r.startsWith("data-")&&(t[r]=s)}),t}function $i(){const e={};for(const t in X)e[X[t]]=`rdp-${X[t]}`;for(const t in $e)e[$e[t]]=`rdp-${$e[t]}`;for(const t in Yt)e[Yt[t]]=`rdp-${Yt[t]}`;for(const t in It)e[It[t]]=`rdp-${It[t]}`;return e}function kb(e,t,r){return(r??new fr(t)).formatMonthYear(e)}function Ab(e,t,r){return(r??new fr(t)).format(e,"d")}function Ob(e,t=hr){return t.format(e,"LLLL")}function Db(e,t,r){return(r??new fr(t)).format(e,"cccccc")}function Mb(e,t=hr){return e<10?t.formatNumber(`0${e.toLocaleString()}`):t.formatNumber(`${e.toLocaleString()}`)}function _b(){return""}function Pb(e,t=hr){return t.format(e,"yyyy")}var Fb=ti({formatCaption:()=>kb,formatDay:()=>Ab,formatMonthDropdown:()=>Ob,formatWeekNumber:()=>Mb,formatWeekNumberHeader:()=>_b,formatWeekdayName:()=>Db,formatYearDropdown:()=>Pb});function Lb(e){return{...Fb,...e}}function ju(e,t,r,s){let n=(s??new fr(r)).format(e,"PPPP");return t.today&&(n=`Today, ${n}`),t.selected&&(n=`${n}, selected`),n}function Iu(e,t,r){return(r??new fr(t)).formatMonthYear(e)}function Tu(e,t,r,s){let n=(s??new fr(r)).format(e,"PPPP");return t?.today&&(n=`Today, ${n}`),n}function Ru(e){return"Choose the Month"}function Eu(){return""}var zb="Go to the Next Month";function ku(e,t){return zb}function Au(e){return"Go to the Previous Month"}function Ou(e,t,r){return(r??new fr(t)).format(e,"cccc")}function Du(e,t){return`Week ${e}`}function Mu(e){return"Week Number"}function _u(e){return"Choose the Year"}var $b=ti({labelDayButton:()=>ju,labelGrid:()=>Iu,labelGridcell:()=>Tu,labelMonthDropdown:()=>Ru,labelNav:()=>Eu,labelNext:()=>ku,labelPrevious:()=>Au,labelWeekNumber:()=>Du,labelWeekNumberHeader:()=>Mu,labelWeekday:()=>Ou,labelYearDropdown:()=>_u}),Ht=(e,t,r)=>t||(r?typeof r=="function"?r:(...s)=>r:e);function Vb(e,t){const r=t.locale?.labels??{};return{...$b,...e??{},labelDayButton:Ht(ju,e?.labelDayButton,r.labelDayButton),labelMonthDropdown:Ht(Ru,e?.labelMonthDropdown,r.labelMonthDropdown),labelNext:Ht(ku,e?.labelNext,r.labelNext),labelPrevious:Ht(Au,e?.labelPrevious,r.labelPrevious),labelWeekNumber:Ht(Du,e?.labelWeekNumber,r.labelWeekNumber),labelYearDropdown:Ht(_u,e?.labelYearDropdown,r.labelYearDropdown),labelGrid:Ht(Iu,e?.labelGrid,r.labelGrid),labelGridcell:Ht(Tu,e?.labelGridcell,r.labelGridcell),labelNav:Ht(Eu,e?.labelNav,r.labelNav),labelWeekNumberHeader:Ht(Mu,e?.labelWeekNumberHeader,r.labelWeekNumberHeader),labelWeekday:Ht(Ou,e?.labelWeekday,r.labelWeekday)}}function Bb(e,t,r,s,n){const{startOfMonth:o,startOfYear:l,endOfYear:i,eachMonthOfInterval:c,getMonth:d}=n;return c({start:l(e),end:i(e)}).map(u=>{const h=s.formatMonthDropdown(u,n);return{value:d(u),label:h,disabled:t&&u<o(t)||r&&u>o(r)||!1}})}function Ub(e,t={},r={}){let s={...t?.[X.Day]};return Object.entries(e).filter(([,n])=>n===!0).forEach(([n])=>{s={...s,...r?.[n]}}),s}function qb(e,t,r,s){const n=s??e.today(),o=r?e.startOfBroadcastWeek(n,e):t?e.startOfISOWeek(n):e.startOfWeek(n),l=[];for(let i=0;i<7;i++){const c=e.addDays(o,i);l.push(c)}return l}function Wb(e,t,r,s,n=!1){if(!e||!t)return;const{startOfYear:o,endOfYear:l,eachYearOfInterval:i,getYear:c}=s,d=i({start:o(e),end:l(t)});return n&&d.reverse(),d.map(u=>{const h=r.formatYearDropdown(u,s);return{value:c(u),label:h,disabled:!1}})}function Kb(e,t={}){const{weekStartsOn:r,locale:s}=t,n=r??s?.options?.weekStartsOn??0,o=i=>{const c=typeof i=="number"||typeof i=="string"?new Date(i):i;return new Pt(c.getFullYear(),c.getMonth(),c.getDate(),12,0,0,e)},l=i=>{const c=o(i);return new Date(c.getFullYear(),c.getMonth(),c.getDate(),0,0,0,0)};return{today:()=>o(Pt.tz(e)),newDate:(i,c,d)=>new Pt(i,c,d,12,0,0,e),startOfDay:i=>o(i),startOfWeek:(i,c)=>{const d=o(i),u=c?.weekStartsOn??n,h=(d.getDay()-u+7)%7;return d.setDate(d.getDate()-h),d},startOfISOWeek:i=>{const c=o(i),d=(c.getDay()-1+7)%7;return c.setDate(c.getDate()-d),c},startOfMonth:i=>{const c=o(i);return c.setDate(1),c},startOfYear:i=>{const c=o(i);return c.setMonth(0,1),c},endOfWeek:(i,c)=>{const d=o(i),u=(((c?.weekStartsOn??n)+6)%7-d.getDay()+7)%7;return d.setDate(d.getDate()+u),d},endOfISOWeek:i=>{const c=o(i),d=(7-c.getDay())%7;return c.setDate(c.getDate()+d),c},endOfMonth:i=>{const c=o(i);return c.setMonth(c.getMonth()+1,0),c},endOfYear:i=>{const c=o(i);return c.setMonth(11,31),c},eachMonthOfInterval:i=>{const c=o(i.start),d=o(i.end),u=[],h=new Pt(c.getFullYear(),c.getMonth(),1,12,0,0,e),m=d.getFullYear()*12+d.getMonth();for(;h.getFullYear()*12+h.getMonth()<=m;)u.push(new Pt(h,e)),h.setMonth(h.getMonth()+1,1);return u},addDays:(i,c)=>{const d=o(i);return d.setDate(d.getDate()+c),d},addWeeks:(i,c)=>{const d=o(i);return d.setDate(d.getDate()+c*7),d},addMonths:(i,c)=>{const d=o(i);return d.setMonth(d.getMonth()+c),d},addYears:(i,c)=>{const d=o(i);return d.setFullYear(d.getFullYear()+c),d},eachYearOfInterval:i=>{const c=o(i.start),d=o(i.end),u=[],h=new Pt(c.getFullYear(),0,1,12,0,0,e);for(;h.getFullYear()<=d.getFullYear();)u.push(new Pt(h,e)),h.setFullYear(h.getFullYear()+1,0,1);return u},getWeek:(i,c)=>{const d=l(i);return Pi(d,{weekStartsOn:c?.weekStartsOn??n,firstWeekContainsDate:c?.firstWeekContainsDate??s?.options?.firstWeekContainsDate??1})},getISOWeek:i=>{const c=l(i);return _i(c)},differenceInCalendarDays:(i,c)=>{const d=l(i),u=l(c);return Mi(d,u)},differenceInCalendarMonths:(i,c)=>{const d=l(i),u=l(c);return fu(d,u)}}}var xn=e=>e instanceof HTMLElement?e:null,Wa=e=>[...e.querySelectorAll("[data-animated-month]")??[]],Hb=e=>xn(e.querySelector("[data-animated-month]")),Ka=e=>xn(e.querySelector("[data-animated-caption]")),Ha=e=>xn(e.querySelector("[data-animated-weeks]")),Gb=e=>xn(e.querySelector("[data-animated-nav]")),Yb=e=>xn(e.querySelector("[data-animated-weekdays]"));function Jb(e,t,{classNames:r,months:s,focused:n,dateLib:o}){const l=(0,f.useRef)(null),i=(0,f.useRef)(s),c=(0,f.useRef)(!1);(0,f.useLayoutEffect)(()=>{const d=i.current;if(i.current=s,!t||!e.current||!(e.current instanceof HTMLElement)||s.length===0||d.length===0||s.length!==d.length)return;const u=o.isSameMonth(s[0].date,d[0].date),h=o.isAfter(s[0].date,d[0].date),m=h?r[It.caption_after_enter]:r[It.caption_before_enter],p=h?r[It.weeks_after_enter]:r[It.weeks_before_enter],b=l.current,w=e.current.cloneNode(!0);if(w instanceof HTMLElement?(Wa(w).forEach(C=>{if(!(C instanceof HTMLElement))return;const S=Hb(C);S&&C.contains(S)&&C.removeChild(S);const g=Ka(C);g&&g.classList.remove(m);const v=Ha(C);v&&v.classList.remove(p)}),l.current=w):l.current=null,c.current||u||n)return;const x=b instanceof HTMLElement?Wa(b):[],N=Wa(e.current);if(N?.every(C=>C instanceof HTMLElement)&&x?.every(C=>C instanceof HTMLElement)){c.current=!0;const C=[];e.current.style.isolation="isolate";const S=Gb(e.current);S&&(S.style.zIndex="1"),N.forEach((g,v)=>{const y=x[v];if(!y)return;g.style.position="relative",g.style.overflow="hidden";const R=Ka(g);R&&R.classList.add(m);const I=Ha(g);I&&I.classList.add(p);const k=()=>{c.current=!1,e.current&&(e.current.style.isolation=""),S&&(S.style.zIndex=""),R&&R.classList.remove(m),I&&I.classList.remove(p),g.style.position="",g.style.overflow="",g.contains(y)&&g.removeChild(y)};C.push(k),y.style.pointerEvents="none",y.style.position="absolute",y.style.overflow="hidden",y.setAttribute("aria-hidden","true");const T=Yb(y);T&&(T.style.opacity="0");const D=Ka(y);D&&(D.classList.add(h?r[It.caption_before_exit]:r[It.caption_after_exit]),D.addEventListener("animationend",k));const _=Ha(y);_&&_.classList.add(h?r[It.weeks_before_exit]:r[It.weeks_after_exit]),g.insertBefore(y,g.firstChild)})}})}function Qb(e,t,r,s){const n=e[0],o=e[e.length-1],{ISOWeek:l,fixedWeeks:i,broadcastCalendar:c}=r??{},{addDays:d,differenceInCalendarDays:u,differenceInCalendarMonths:h,endOfBroadcastWeek:m,endOfISOWeek:p,endOfMonth:b,endOfWeek:w,isAfter:x,startOfBroadcastWeek:N,startOfISOWeek:C,startOfWeek:S}=s,g=c?N(n,s):l?C(n):S(n),v=c?m(o):l?p(b(o)):w(b(o)),y=t&&(c?m(t):l?p(t):w(t)),R=u(y&&x(v,y)?y:v,g),I=h(o,n)+1,k=[];for(let D=0;D<=R;D++){const _=d(g,D);k.push(_)}const T=(c?35:42)*I;if(i&&k.length<T){const D=T-k.length;for(let _=0;_<D;_++){const O=d(k[k.length-1],1);k.push(O)}}return k}function Xb(e){const t=[];return e.reduce((r,s)=>{const n=s.weeks.reduce((o,l)=>o.concat(l.days.slice()),t.slice());return r.concat(n.slice())},t.slice())}function Zb(e,t,r,s){const{numberOfMonths:n=1}=r,o=[];for(let l=0;l<n;l++){const i=s.addMonths(e,l);if(t&&i>t)break;o.push(i)}return o}function Hl(e,t,r,s){const{month:n,defaultMonth:o,today:l=s.today(),numberOfMonths:i=1}=e;let c=n||o||l;const{differenceInCalendarMonths:d,addMonths:u,startOfMonth:h}=s;return r&&d(r,c)<i-1&&(c=u(r,-1*(i-1))),t&&d(c,t)<0&&(c=t),h(c)}function ex(e,t,r,s){const{addDays:n,endOfBroadcastWeek:o,endOfISOWeek:l,endOfMonth:i,endOfWeek:c,getISOWeek:d,getWeek:u,startOfBroadcastWeek:h,startOfISOWeek:m,startOfWeek:p}=s,b=e.reduce((w,x)=>{const N=r.broadcastCalendar?h(x,s):r.ISOWeek?m(x):p(x),C=r.broadcastCalendar?o(x):r.ISOWeek?l(i(x)):c(i(x)),S=t.filter(R=>R>=N&&R<=C),g=r.broadcastCalendar?35:42;if(r.fixedWeeks&&S.length<g){const R=t.filter(I=>{const k=g-S.length;return I>C&&I<=n(C,k)});S.push(...R)}const v=S.reduce((R,I)=>{const k=r.ISOWeek?d(I):u(I),T=R.find(_=>_.weekNumber===k),D=new Su(I,x,s);return T?T.days.push(D):R.push(new Z0(k,[D])),R},[]),y=new X0(x,v);return w.push(y),w},[]);return r.reverseMonths?b.reverse():b}function tx(e,t){let{startMonth:r,endMonth:s}=e;const{startOfYear:n,startOfDay:o,startOfMonth:l,endOfMonth:i,addYears:c,endOfYear:d,today:u}=t,h=e.captionLayout==="dropdown"||e.captionLayout==="dropdown-years";return r?r=l(r):!r&&h&&(r=n(c(e.today??u(),-100))),s?s=i(s):!s&&h&&(s=d(e.today??u())),[r&&o(r),s&&o(s)]}function rx(e,t,r,s){if(r.disableNavigation)return;const{pagedNavigation:n,numberOfMonths:o=1}=r,{startOfMonth:l,addMonths:i,differenceInCalendarMonths:c}=s,d=n?o:1,u=l(e);if(!t)return i(u,d);if(!(c(t,e)<o))return i(u,d)}function sx(e,t,r,s){if(r.disableNavigation)return;const{pagedNavigation:n,numberOfMonths:o}=r,{startOfMonth:l,addMonths:i,differenceInCalendarMonths:c}=s,d=n?o??1:1,u=l(e);if(!t)return i(u,-d);if(!(c(u,t)<=0))return i(u,-d)}function nx(e){return e.reduce((t,r)=>t.concat(r.weeks.slice()),[].slice())}function ga(e,t){const[r,s]=(0,f.useState)(e);return[t===void 0?r:t,s]}function ax(e,t){const[r,s]=tx(e,t),{startOfMonth:n,endOfMonth:o}=t,l=Hl(e,r,s,t),[i,c]=ga(l,e.month?l:void 0);(0,f.useEffect)(()=>{const S=Hl(e,r,s,t);c(S)},[e.timeZone]);const{months:d,weeks:u,days:h,previousMonth:m,nextMonth:p}=(0,f.useMemo)(()=>{const S=Zb(i,s,{numberOfMonths:e.numberOfMonths},t),g=Qb(S,e.endMonth?o(e.endMonth):void 0,{ISOWeek:e.ISOWeek,fixedWeeks:e.fixedWeeks,broadcastCalendar:e.broadcastCalendar},t),v=ex(S,g,{broadcastCalendar:e.broadcastCalendar,fixedWeeks:e.fixedWeeks,ISOWeek:e.ISOWeek,reverseMonths:e.reverseMonths},t);return{months:v,weeks:nx(v),days:Xb(v),previousMonth:sx(i,r,e,t),nextMonth:rx(i,s,e,t)}},[t,i.getTime(),s?.getTime(),r?.getTime(),e.disableNavigation,e.broadcastCalendar,e.endMonth?.getTime(),e.fixedWeeks,e.ISOWeek,e.numberOfMonths,e.pagedNavigation,e.reverseMonths]),{disableNavigation:b,onMonthChange:w}=e,x=S=>u.some(g=>g.days.some(v=>v.isEqualTo(S))),N=S=>{if(b)return;let g=n(S);r&&g<n(r)&&(g=n(r)),s&&g>n(s)&&(g=n(s)),c(g),w?.(g)};return{months:d,weeks:u,days:h,navStart:r,navEnd:s,previousMonth:m,nextMonth:p,goToMonth:N,goToDay:S=>{x(S)||N(S.date)}}}var nr;(function(e){e[e.Today=0]="Today",e[e.Selected=1]="Selected",e[e.LastFocused=2]="LastFocused",e[e.FocusedModifier=3]="FocusedModifier"})(nr||(nr={}));function Gl(e){return!e[$e.disabled]&&!e[$e.hidden]&&!e[$e.outside]}function ox(e,t,r,s){let n,o=-1;for(const l of e){const i=t(l);Gl(i)&&(i[$e.focused]&&o<nr.FocusedModifier?(n=l,o=nr.FocusedModifier):s?.isEqualTo(l)&&o<nr.LastFocused?(n=l,o=nr.LastFocused):r(l.date)&&o<nr.Selected?(n=l,o=nr.Selected):i[$e.today]&&o<nr.Today&&(n=l,o=nr.Today))}return n||(n=e.find(l=>Gl(t(l)))),n}function ix(e,t,r,s,n,o,l){const{ISOWeek:i,broadcastCalendar:c}=o,{addDays:d,addMonths:u,addWeeks:h,addYears:m,endOfBroadcastWeek:p,endOfISOWeek:b,endOfWeek:w,max:x,min:N,startOfBroadcastWeek:C,startOfISOWeek:S,startOfWeek:g}=l;let v={day:d,week:h,month:u,year:m,startOfWeek:y=>c?C(y,l):i?S(y):g(y),endOfWeek:y=>c?p(y):i?b(y):w(y)}[e](r,t==="after"?1:-1);return t==="before"&&s?v=x([s,v]):t==="after"&&n&&(v=N([n,v])),v}function Pu(e,t,r,s,n,o,l,i=0){if(i>365)return;const c=ix(e,t,r.date,s,n,o,l),d=!!(o.disabled&&br(c,o.disabled,l)),u=!!(o.hidden&&br(c,o.hidden,l)),h=new Su(c,c,l);return!d&&!u?h:Pu(e,t,h,s,n,o,l,i+1)}function lx(e,t,r,s,n){const{autoFocus:o}=e,[l,i]=(0,f.useState)(),c=ox(t.days,r,s||(()=>!1),l),[d,u]=(0,f.useState)(o?c:void 0);return{isFocusTarget:b=>!!c?.isEqualTo(b),setFocused:u,focused:d,blur:()=>{i(d),u(void 0)},moveFocus:(b,w)=>{if(!d)return;const x=Pu(b,w,d,t.navStart,t.navEnd,e,n);x&&(e.disableNavigation&&!t.days.some(N=>N.isEqualTo(x))||(t.goToDay(x),u(x)))}}}function cx(e,t){const{selected:r,required:s,onSelect:n}=e,[o,l]=ga(r,n?r:void 0),i=n?r:o,{isSameDay:c}=t,d=p=>i?.some(b=>c(b,p))??!1,{min:u,max:h}=e;return{selected:i,select:(p,b,w)=>{let x=[...i??[]];if(d(p)){if(i?.length===u||s&&i?.length===1)return;x=i?.filter(N=>!c(N,p))}else i?.length===h?x=[p]:x=[...x,p];return n||l(x),n?.(x,p,b,w),x},isSelected:d}}function dx(e,t,r=0,s=0,n=!1,o=hr){const{from:l,to:i}=t||{},{isSameDay:c,isAfter:d,isBefore:u}=o;let h;if(!l&&!i)h={from:e,to:r>0?void 0:e};else if(l&&!i)c(l,e)?r===0?h={from:l,to:e}:n?h={from:l,to:void 0}:h=void 0:u(e,l)?h={from:e,to:l}:h={from:l,to:e};else if(l&&i)if(c(l,e)&&c(i,e))n?h={from:l,to:i}:h=void 0;else if(c(l,e))h={from:l,to:r>0?void 0:e};else if(c(i,e))h={from:e,to:r>0?void 0:e};else if(u(e,l))h={from:e,to:i};else if(d(e,l))h={from:l,to:e};else if(d(e,i))h={from:l,to:e};else throw new Error("Invalid range");if(h?.from&&h?.to){const m=o.differenceInCalendarDays(h.to,h.from);s>0&&m>s?h={from:e,to:void 0}:r>1&&m<r&&(h={from:e,to:void 0})}return h}function ux(e,t,r=hr){const s=Array.isArray(t)?t:[t];let n=e.from;const o=r.differenceInCalendarDays(e.to,e.from),l=Math.min(o,6);for(let i=0;i<=l;i++){if(s.includes(n.getDay()))return!0;n=r.addDays(n,1)}return!1}function Yl(e,t,r=hr){return yr(e,t.from,!1,r)||yr(e,t.to,!1,r)||yr(t,e.from,!1,r)||yr(t,e.to,!1,r)}function fx(e,t,r=hr){const s=Array.isArray(t)?t:[t];if(s.filter(o=>typeof o!="function").some(o=>typeof o=="boolean"?o:r.isDate(o)?yr(e,o,!1,r):Nu(o,r)?o.some(l=>yr(e,l,!1,r)):pa(o)?o.from&&o.to?Yl(e,{from:o.from,to:o.to},r):!1:wu(o)?ux(e,o.dayOfWeek,r):Fi(o)?r.isAfter(o.before,o.after)?Yl(e,{from:r.addDays(o.after,1),to:r.addDays(o.before,-1)},r):br(e.from,o,r)||br(e.to,o,r):Li(o)||zi(o)?br(e.from,o,r)||br(e.to,o,r):!1))return!0;const n=s.filter(o=>typeof o=="function");if(n.length){let o=e.from;const l=r.differenceInCalendarDays(e.to,e.from);for(let i=0;i<=l;i++){if(n.some(c=>c(o)))return!0;o=r.addDays(o,1)}}return!1}function hx(e,t){const{disabled:r,excludeDisabled:s,resetOnSelect:n,selected:o,required:l,onSelect:i}=e,[c,d]=ga(o,i?o:void 0),u=i?o:c;return{selected:u,select:(p,b,w)=>{const{min:x,max:N}=e;let C;if(p){const S=u?.from,g=u?.to,v=!!S&&!!g,y=!!S&&!!g&&t.isSameDay(S,g)&&t.isSameDay(p,S);n&&(v||!u?.from)?!l&&y?C=void 0:C={from:p,to:void 0}:C=dx(p,u,x,N,l,t)}return s&&r&&C?.from&&C.to&&fx({from:C.from,to:C.to},r,t)&&(C.from=p,C.to=void 0),i||d(C),i?.(C,p,b,w),C},isSelected:p=>u&&yr(u,p,!1,t)}}function mx(e,t){const{selected:r,required:s,onSelect:n}=e,[o,l]=ga(r,n?r:void 0),i=n?r:o,{isSameDay:c}=t;return{selected:i,select:(h,m,p)=>{let b=h;return!s&&i&&i&&c(h,i)&&(b=void 0),n||l(b),n?.(b,h,m,p),b},isSelected:h=>i?c(i,h):!1}}function px(e,t){const r=mx(e,t),s=cx(e,t),n=hx(e,t);switch(e.mode){case"single":return r;case"multiple":return s;case"range":return n;default:return}}function jt(e,t){return e instanceof Pt&&e.timeZone===t?e:new Pt(e,t)}function bs(e,t,r){if(!r)return jt(e,t);const s=jt(e,t),n=new Pt(s.getFullYear(),s.getMonth(),s.getDate(),12,0,0,t);return new Date(n.getTime())}function Jl(e,t,r){return typeof e=="boolean"||typeof e=="function"?e:e instanceof Date?bs(e,t,r):Array.isArray(e)?e.map(s=>s instanceof Date?bs(s,t,r):s):pa(e)?{...e,from:e.from?jt(e.from,t):e.from,to:e.to?jt(e.to,t):e.to}:Fi(e)?{before:bs(e.before,t,r),after:bs(e.after,t,r)}:Li(e)?{after:bs(e.after,t,r)}:zi(e)?{before:bs(e.before,t,r)}:e}function Ga(e,t,r){return e&&(Array.isArray(e)?e.map(s=>Jl(s,t,r)):Jl(e,t,r))}function gx(e){let t=e;const r=t.timeZone;if(r&&(t={...e,timeZone:r},t.today&&(t.today=jt(t.today,r)),t.month&&(t.month=jt(t.month,r)),t.defaultMonth&&(t.defaultMonth=jt(t.defaultMonth,r)),t.startMonth&&(t.startMonth=jt(t.startMonth,r)),t.endMonth&&(t.endMonth=jt(t.endMonth,r)),t.mode==="single"&&t.selected?t.selected=jt(t.selected,r):t.mode==="multiple"&&t.selected?t.selected=t.selected?.map(Y=>jt(Y,r)):t.mode==="range"&&t.selected&&(t.selected={from:t.selected.from?jt(t.selected.from,r):t.selected.from,to:t.selected.to?jt(t.selected.to,r):t.selected.to}),t.disabled!==void 0&&(t.disabled=Ga(t.disabled,r)),t.hidden!==void 0&&(t.hidden=Ga(t.hidden,r)),t.modifiers)){const Y={};Object.keys(t.modifiers).forEach(Q=>{Y[Q]=Ga(t.modifiers?.[Q],r)}),t.modifiers=Y}const{components:s,formatters:n,labels:o,dateLib:l,locale:i,classNames:c}=(0,f.useMemo)(()=>{const Y={...xu,...t.locale},Q=t.broadcastCalendar?1:t.weekStartsOn,te=t.noonSafe&&t.timeZone?Kb(t.timeZone,{weekStartsOn:Q,locale:Y}):void 0,ye=t.dateLib&&te?{...te,...t.dateLib}:t.dateLib??te,le=new fr({locale:Y,weekStartsOn:Q,firstWeekContainsDate:t.firstWeekContainsDate,useAdditionalWeekYearTokens:t.useAdditionalWeekYearTokens,useAdditionalDayOfYearTokens:t.useAdditionalDayOfYearTokens,timeZone:t.timeZone,numerals:t.numerals},ye);return{dateLib:le,components:Rb(t.components),formatters:Lb(t.formatters),labels:Vb(t.labels,le.options),locale:Y,classNames:{...$i(),...t.classNames}}},[t.locale,t.broadcastCalendar,t.weekStartsOn,t.firstWeekContainsDate,t.useAdditionalWeekYearTokens,t.useAdditionalDayOfYearTokens,t.timeZone,t.numerals,t.dateLib,t.noonSafe,t.components,t.formatters,t.labels,t.classNames]);t.today||(t={...t,today:l.today()});const{captionLayout:d,mode:u,navLayout:h,numberOfMonths:m=1,onDayBlur:p,onDayClick:b,onDayFocus:w,onDayKeyDown:x,onDayMouseEnter:N,onDayMouseLeave:C,onNextClick:S,onPrevClick:g,showWeekNumber:v,styles:y}=t,{formatCaption:R,formatDay:I,formatMonthDropdown:k,formatWeekNumber:T,formatWeekNumberHeader:D,formatWeekdayName:_,formatYearDropdown:O}=n,F=ax(t,l),{days:E,months:z,navStart:G,navEnd:fe,previousMonth:Z,nextMonth:re,goToMonth:Ne}=F,L=Ib(E,t,G,fe,l),{isSelected:$,select:ne,selected:ee}=px(t,l)??{},{blur:pe,focused:K,isFocusTarget:Ie,moveFocus:Pe,setFocused:pt}=lx(t,F,L,$??(()=>!1),l),{labelDayButton:Ye,labelGridcell:st,labelGrid:Zt,labelMonthDropdown:oe,labelNav:he,labelPrevious:ie,labelNext:gt,labelWeekday:Nt,labelWeekNumber:nt,labelWeekNumberHeader:er,labelYearDropdown:Ue}=o,Kt=(0,f.useMemo)(()=>qb(l,t.ISOWeek,t.broadcastCalendar,t.today),[l,t.ISOWeek,t.broadcastCalendar,t.today]),de=u!==void 0||b!==void 0,j=(0,f.useCallback)(()=>{Z&&(Ne(Z),g?.(Z))},[Z,Ne,g]),A=(0,f.useCallback)(()=>{re&&(Ne(re),S?.(re))},[Ne,re,S]),M=(0,f.useCallback)((Y,Q)=>te=>{te.preventDefault(),te.stopPropagation(),pt(Y),!Q.disabled&&(ne?.(Y.date,Q,te),b?.(Y.date,Q,te))},[ne,b,pt]),W=(0,f.useCallback)((Y,Q)=>te=>{pt(Y),w?.(Y.date,Q,te)},[w,pt]),H=(0,f.useCallback)((Y,Q)=>te=>{pe(),p?.(Y.date,Q,te)},[pe,p]),U=(0,f.useCallback)((Y,Q)=>te=>{const ye={ArrowLeft:[te.shiftKey?"month":"day",t.dir==="rtl"?"after":"before"],ArrowRight:[te.shiftKey?"month":"day",t.dir==="rtl"?"before":"after"],ArrowDown:[te.shiftKey?"year":"week","after"],ArrowUp:[te.shiftKey?"year":"week","before"],PageUp:[te.shiftKey?"year":"month","before"],PageDown:[te.shiftKey?"year":"month","after"],Home:["startOfWeek","before"],End:["endOfWeek","after"]};if(ye[te.key]){te.preventDefault(),te.stopPropagation();const[le,Fe]=ye[te.key];Pe(le,Fe)}x?.(Y.date,Q,te)},[Pe,x,t.dir]),J=(0,f.useCallback)((Y,Q)=>te=>{N?.(Y.date,Q,te)},[N]),ae=(0,f.useCallback)((Y,Q)=>te=>{C?.(Y.date,Q,te)},[C]),xe=(0,f.useCallback)((Y,Q)=>te=>{const ye=Number(te.target.value),le=l.setMonth(l.startOfMonth(Y),ye);Ne(l.addMonths(le,-Q))},[l,Ne]),Je=(0,f.useCallback)((Y,Q)=>te=>{const ye=Number(te.target.value),le=l.setYear(l.startOfMonth(Y),ye);Ne(l.addMonths(le,-Q))},[l,Ne]),{className:vt,style:Ze}=(0,f.useMemo)(()=>({className:[c[X.Root],t.className].filter(Boolean).join(" "),style:{...y?.[X.Root],...t.style}}),[c,t.className,t.style,y]),Ls=Eb(t),wr=Y=>{const Q=y?.[X.Dropdown],te=y?.[Y];if(!(!Q&&!te))return{...Q,...te}},se=(0,f.useRef)(null);Jb(se,!!t.animate,{classNames:c,months:z,focused:K,dateLib:l});const Se={dayPickerProps:t,selected:ee,select:ne,isSelected:$,months:z,nextMonth:re,previousMonth:Z,goToMonth:Ne,getModifiers:L,components:s,classNames:c,styles:y,labels:o,formatters:n};return f.createElement(Cu.Provider,{value:Se},f.createElement(s.Root,{rootRef:t.animate?se:void 0,className:vt,style:Ze,dir:t.dir,id:t.id,lang:t.lang??i.code,nonce:t.nonce,title:t.title,role:t.role,"aria-label":t["aria-label"],"aria-labelledby":t["aria-labelledby"],...Ls},f.createElement(s.Months,{className:c[X.Months],style:y?.[X.Months]},!t.hideNavigation&&!h&&f.createElement(s.Nav,{"data-animated-nav":t.animate?"true":void 0,className:c[X.Nav],style:y?.[X.Nav],"aria-label":he(),onPreviousClick:j,onNextClick:A,previousMonth:Z,nextMonth:re}),z.map((Y,Q)=>{const te=t.reverseMonths?z.length-1-Q:Q;return f.createElement(s.Month,{"data-animated-month":t.animate?"true":void 0,className:c[X.Month],style:y?.[X.Month],key:Q,displayIndex:Q,calendarMonth:Y},h==="around"&&!t.hideNavigation&&Q===0&&f.createElement(s.PreviousMonthButton,{type:"button",className:c[X.PreviousMonthButton],style:y?.[X.PreviousMonthButton],tabIndex:Z?void 0:-1,"aria-disabled":Z?void 0:!0,"aria-label":ie(Z),onClick:j,"data-animated-button":t.animate?"true":void 0},f.createElement(s.Chevron,{disabled:Z?void 0:!0,className:c[X.Chevron],style:y?.[X.Chevron],orientation:t.dir==="rtl"?"right":"left"})),f.createElement(s.MonthCaption,{"data-animated-caption":t.animate?"true":void 0,className:c[X.MonthCaption],style:y?.[X.MonthCaption],calendarMonth:Y,displayIndex:Q},d?.startsWith("dropdown")?f.createElement(s.DropdownNav,{className:c[X.Dropdowns],style:y?.[X.Dropdowns]},(()=>{const ye=d==="dropdown"||d==="dropdown-months"?f.createElement(s.MonthsDropdown,{key:"month",className:c[X.MonthsDropdown],"aria-label":oe(),disabled:!!t.disableNavigation,onChange:xe(Y.date,te),options:Bb(Y.date,G,fe,n,l),style:wr(X.MonthsDropdown),value:l.getMonth(Y.date)}):f.createElement("span",{key:"month"},k(Y.date,l)),le=d==="dropdown"||d==="dropdown-years"?f.createElement(s.YearsDropdown,{key:"year",className:c[X.YearsDropdown],"aria-label":Ue(l.options),disabled:!!t.disableNavigation,onChange:Je(Y.date,te),options:Wb(G,fe,n,l,!!t.reverseYears),style:wr(X.YearsDropdown),value:l.getYear(Y.date)}):f.createElement("span",{key:"year"},O(Y.date,l));return l.getMonthYearOrder()==="year-first"?[le,ye]:[ye,le]})(),f.createElement("span",{role:"status","aria-live":"polite",style:{border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"absolute",width:"1px",whiteSpace:"nowrap",wordWrap:"normal"}},R(Y.date,l.options,l))):f.createElement(s.CaptionLabel,{className:c[X.CaptionLabel],style:y?.[X.CaptionLabel],role:"status","aria-live":"polite"},R(Y.date,l.options,l))),h==="around"&&!t.hideNavigation&&Q===m-1&&f.createElement(s.NextMonthButton,{type:"button",className:c[X.NextMonthButton],style:y?.[X.NextMonthButton],tabIndex:re?void 0:-1,"aria-disabled":re?void 0:!0,"aria-label":gt(re),onClick:A,"data-animated-button":t.animate?"true":void 0},f.createElement(s.Chevron,{disabled:re?void 0:!0,className:c[X.Chevron],style:y?.[X.Chevron],orientation:t.dir==="rtl"?"left":"right"})),Q===m-1&&h==="after"&&!t.hideNavigation&&f.createElement(s.Nav,{"data-animated-nav":t.animate?"true":void 0,className:c[X.Nav],style:y?.[X.Nav],"aria-label":he(),onPreviousClick:j,onNextClick:A,previousMonth:Z,nextMonth:re}),f.createElement(s.MonthGrid,{role:"grid","aria-multiselectable":u==="multiple"||u==="range","aria-label":Zt(Y.date,l.options,l)||void 0,className:c[X.MonthGrid],style:y?.[X.MonthGrid]},!t.hideWeekdays&&f.createElement(s.Weekdays,{"data-animated-weekdays":t.animate?"true":void 0,className:c[X.Weekdays],style:y?.[X.Weekdays]},v&&f.createElement(s.WeekNumberHeader,{"aria-label":er(l.options),className:c[X.WeekNumberHeader],style:y?.[X.WeekNumberHeader],scope:"col"},D()),Kt.map(ye=>f.createElement(s.Weekday,{"aria-label":Nt(ye,l.options,l),className:c[X.Weekday],key:String(ye),style:y?.[X.Weekday],scope:"col"},_(ye,l.options,l)))),f.createElement(s.Weeks,{"data-animated-weeks":t.animate?"true":void 0,className:c[X.Weeks],style:y?.[X.Weeks]},Y.weeks.map(ye=>f.createElement(s.Week,{className:c[X.Week],key:ye.weekNumber,style:y?.[X.Week],week:ye},v&&f.createElement(s.WeekNumber,{week:ye,style:y?.[X.WeekNumber],"aria-label":nt(ye.weekNumber,{locale:i}),className:c[X.WeekNumber],scope:"row",role:"rowheader"},T(ye.weekNumber,l)),ye.days.map(le=>{const{date:Fe}=le,ge=L(le);if(ge[$e.focused]=!ge.hidden&&!!K?.isEqualTo(le),ge[Yt.selected]=$?.(Fe)||ge.selected,pa(ee)){const{from:gs,to:Na}=ee;ge[Yt.range_start]=!!(gs&&Na&&l.isSameDay(Fe,gs)),ge[Yt.range_end]=!!(gs&&Na&&l.isSameDay(Fe,Na)),ge[Yt.range_middle]=yr(ee,Fe,!0,l)}const ps=Ub(ge,y,t.modifiersStyles),ut=Tb(ge,c,t.modifiersClassNames),pr=!de&&!ge.hidden?st(Fe,ge,l.options,l):void 0;return f.createElement(s.Day,{key:`${le.isoDate}_${le.displayMonthId}`,day:le,modifiers:ge,className:ut.join(" "),style:ps,role:"gridcell","aria-selected":ge.selected||void 0,"aria-label":pr,"data-day":le.isoDate,"data-month":le.outside?le.dateMonthId:void 0,"data-selected":ge.selected||void 0,"data-disabled":ge.disabled||void 0,"data-hidden":ge.hidden||void 0,"data-outside":le.outside||void 0,"data-focused":ge.focused||void 0,"data-today":ge.today||void 0},!ge.hidden&&de?f.createElement(s.DayButton,{className:c[X.DayButton],style:y?.[X.DayButton],type:"button",day:le,modifiers:ge,disabled:!ge.focused&&ge.disabled||void 0,"aria-disabled":ge.focused&&ge.disabled||void 0,tabIndex:Ie(le)?0:-1,"aria-label":Ye(Fe,ge,l.options,l),onClick:M(le,ge),onBlur:H(le,ge),onFocus:W(le,ge),onKeyDown:U(le,ge),onMouseEnter:J(le,ge),onMouseLeave:ae(le,ge)},I(Fe,l.options,l)):!ge.hidden&&I(le.date,l.options,l))}))))))})),t.footer&&f.createElement(s.Footer,{className:c[X.Footer],style:y?.[X.Footer],role:"status","aria-live":"polite"},t.footer)))}function vx({className:e,classNames:t,showOutsideDays:r=!0,captionLayout:s="label",buttonVariant:n="ghost",formatters:o,components:l,...i}){const c=$i();return(0,a.jsx)(gx,{showOutsideDays:r,className:V("p-3 [--cell-radius:var(--radius-md)] [--cell-size:--spacing(6)] bg-background group/calendar [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,e),captionLayout:s,formatters:{formatMonthDropdown:d=>d.toLocaleString("default",{month:"short"}),...o},classNames:{root:V("w-fit",c.root),months:V("flex gap-4 flex-col md:flex-row relative",c.months),month:V("flex flex-col w-full gap-4",c.month),nav:V("flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",c.nav),button_previous:V(hl({variant:n}),"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",c.button_previous),button_next:V(hl({variant:n}),"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",c.button_next),month_caption:V("flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",c.month_caption),dropdowns:V("w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",c.dropdowns),dropdown_root:V("relative cn-calendar-dropdown-root rounded-(--cell-radius)",c.dropdown_root),dropdown:V("absolute bg-popover inset-0 opacity-0",c.dropdown),caption_label:V("select-none font-medium",s==="label"?"text-sm":"cn-calendar-caption-label rounded-(--cell-radius) flex items-center gap-1 text-sm [&>svg]:text-muted-foreground [&>svg]:size-3.5",c.caption_label),month_grid:V("w-full border-collapse",c.month_grid),weekdays:V("flex",c.weekdays),weekday:V("text-muted-foreground rounded-(--cell-radius) flex-1 font-normal text-[0.8rem] select-none",c.weekday),week:V("flex w-full mt-2",c.week),week_number_header:V("select-none w-(--cell-size)",c.week_number_header),week_number:V("text-[0.8rem] select-none text-muted-foreground",c.week_number),day:V("relative w-full rounded-(--cell-radius) h-full p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius) group/day aspect-square select-none",i.showWeekNumber?"[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)":"[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",c.day),range_start:V("rounded-l-(--cell-radius) bg-muted elative after:bg-muted after:absolute after:inset-y-0 after:w-4 after:right-0 -z-0 isolate",c.range_start),range_middle:V("rounded-none",c.range_middle),range_end:V("rounded-r-(--cell-radius) bg-muted relative after:bg-muted-200 after:absolute after:inset-y-0 after:w-4 after:left-0 -z-0 isolate",c.range_end),today:V("bg-muted text-foreground rounded-(--cell-radius) data-[selected=true]:rounded-none",c.today),outside:V("text-muted-foreground aria-selected:text-muted-foreground",c.outside),disabled:V("text-muted-foreground opacity-50",c.disabled),hidden:V("invisible",c.hidden),...t},components:{Root:({className:d,rootRef:u,...h})=>(0,a.jsx)("div",{"data-slot":"calendar",ref:u,className:V(d),...h}),Chevron:({className:d,orientation:u,...h})=>u==="left"?(0,a.jsx)(oi,{className:V("size-4",d),...h}):u==="right"?(0,a.jsx)(ci,{className:V("size-4",d),...h}):(0,a.jsx)(us,{className:V("size-4",d),...h}),DayButton:yx,WeekNumber:({children:d,...u})=>(0,a.jsx)("td",{...u,children:(0,a.jsx)("div",{className:"flex size-(--cell-size) items-center justify-center text-center",children:d})}),...l},...i})}function yx({className:e,day:t,modifiers:r,...s}){const n=$i(),o=f.useRef(null);return f.useEffect(()=>{r.focused&&o.current?.focus()},[r.focused]),(0,a.jsx)(B,{ref:o,variant:"ghost",size:"icon","data-day":t.date.toLocaleDateString(),"data-selected-single":r.selected&&!r.range_start&&!r.range_end&&!r.range_middle,"data-range-start":r.range_start,"data-range-end":r.range_end,"data-range-middle":r.range_middle,className:V("data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-foreground relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) [&>span]:text-xs [&>span]:opacity-70",n.day,e),...s})}function Ur({value:e,onChange:t,placeholder:r="Pick a date",className:s,disabled:n,startYear:o=1980,endYear:l=new Date().getFullYear()+10,icon:i=!0,isFormatted:c=!0,showTime:d=!1,modal:u,open:h,onOpenChange:m}){const[p,b]=(0,f.useState)(!1),w=h??p,x=O=>{b(O),m?.(O)},[N]=(0,f.useState)(()=>new Date),C=e?e.getHours():0,S=e?e.getMinutes():0,g=e?e.getSeconds():0,v=(O,F)=>{F({target:{value:String(O)}})},y=O=>{O&&e&&(O.setHours(e.getHours()),O.setMinutes(e.getMinutes()),O.setSeconds(e.getSeconds())),t?.(O),d||x(!1)},R=(O,F)=>{const E=e?new Date(e):new Date;O==="hours"&&E.setHours(F),O==="minutes"&&E.setMinutes(F),O==="seconds"&&E.setSeconds(F),t?.(E)},I=O=>{const F=Rs(new Date);switch(O){case"NULL":t?.(null);break;case"NOW":t?.(new Date);break;case"TODAY":t?.(F);break;case"YESTERDAY":t?.(qn(F,-1));break;case"TOMORROW":t?.(qn(F,1))}},k=Array.from({length:24},(O,F)=>F),T=Array.from({length:60},(O,F)=>F),D=Array.from({length:60},(O,F)=>F),_=e&&e instanceof Date&&!Number.isNaN(e.getTime())?c?d?lr(e,"dd/MM/yyyy HH:mm:ss"):lr(e,"dd/MM/yyyy"):d?lr(e,"yyyy-MM-dd HH:mm:ss"):lr(e,"yyyy-MM-dd"):e===null?"NULL":r;return(0,a.jsxs)(Mr,{modal:u,open:w,onOpenChange:x,children:[(0,a.jsx)(fs,{asChild:!0,children:(0,a.jsxs)(B,{variant:"outline",className:V("w-full justify-start text-left font-normal",!e&&"text-muted-foreground",s),disabled:n,children:[i&&(0,a.jsx)(rp,{className:"mr-2 size-4"}),_]})}),(0,a.jsx)(ur,{className:"w-auto p-0",align:"end",children:(0,a.jsxs)("div",{className:"flex",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-1 p-2 border-r",children:[(0,a.jsx)(B,{variant:"ghost",size:"sm",className:"justify-start text-xs h-7",onClick:()=>I("NULL"),children:"NULL"}),(0,a.jsx)(B,{variant:"ghost",size:"sm",className:"justify-start text-xs h-7",onClick:()=>I("NOW"),children:"NOW"}),(0,a.jsx)(B,{variant:"ghost",size:"sm",className:"justify-start text-xs h-7",onClick:()=>I("TODAY"),children:"TODAY"}),(0,a.jsx)(B,{variant:"ghost",size:"sm",className:"justify-start text-xs h-7",onClick:()=>I("YESTERDAY"),children:"YESTERDAY"}),(0,a.jsx)(B,{variant:"ghost",size:"sm",className:"justify-start text-xs h-7",onClick:()=>I("TOMORROW"),children:"TOMORROW"})]}),(0,a.jsx)(vx,{components:{Dropdown:O=>(0,a.jsxs)(dt,{onValueChange:F=>{O.onChange&&v(F,O.onChange)},value:String(O.value),children:[(0,a.jsx)(lt,{className:"h-8 w-fit font-medium first-letter:capitalize focus:ring-0 focus:ring-offset-0",children:(0,a.jsx)(it,{})}),(0,a.jsx)(ct,{children:O.options?.map(F=>(0,a.jsx)(ue,{value:String(F.value),children:F.label},F.value))})]}),DropdownNav:O=>(0,a.jsx)("div",{className:"flex w-full items-center gap-2",children:O.children})},defaultMonth:e||N,hideNavigation:!0,mode:"single",onSelect:y,selected:e||void 0,startMonth:new Date(o,0),endMonth:new Date(l,11)}),d&&(0,a.jsxs)("div",{className:"flex border-l",children:[(0,a.jsx)(Ya,{label:"H",values:k,selected:C,onChange:O=>R("hours",O)}),(0,a.jsx)(Ya,{label:"M",values:T,selected:S,onChange:O=>R("minutes",O)}),(0,a.jsx)(Ya,{label:"S",values:D,selected:g,onChange:O=>R("seconds",O)})]})]})})]})}function Ya({label:e,values:t,selected:r,onChange:s}){const n=(0,f.useRef)(new Map);return(0,f.useEffect)(()=>{const o=n.current.get(r);o&&o.scrollIntoView({block:"center",behavior:"auto"})},[r]),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("div",{className:"px-3 py-2 text-xs font-medium text-muted-foreground text-center border-b",children:e}),(0,a.jsx)(hg,{className:"h-[224px]",children:(0,a.jsx)("div",{className:"flex flex-col p-1",children:t.map(o=>(0,a.jsx)("button",{ref:l=>{l&&n.current.set(o,l)},type:"button",onClick:()=>s(o),className:V("w-10 h-8 text-sm rounded-md hover:bg-accent flex items-center justify-center",r===o&&"bg-primary text-primary-foreground hover:bg-primary"),children:o.toString().padStart(2,"0")},o))})})]})}function Fu(e,t,r){try{return e(t)}catch(s){return Cg("[nuqs] Error while parsing value `%s`: %O"+(r?" (for key `%s`)":""),t,s,r),null}}function mr(e){function t(r){if(typeof r>"u")return null;let s="";if(Array.isArray(r)){if(r[0]===void 0)return null;s=r[0]}return typeof r=="string"&&(s=r),Fu(e.parse,s)}return{type:"single",eq:(r,s)=>r===s,...e,parseServerSide:t,withDefault(r){return{...this,defaultValue:r,parseServerSide(s){return t(s)??r}}},withOptions(r){return{...this,...r}}}}var lR=mr({parse:e=>e,serialize:String}),cR=mr({parse:e=>{const t=parseInt(e);return t==t?t:null},serialize:e=>""+Math.round(e)}),dR=mr({parse:e=>{const t=parseInt(e);return t==t?t-1:null},serialize:e=>""+Math.round(e+1)}),uR=mr({parse:e=>{const t=parseInt(e,16);return t==t?t:null},serialize:e=>{const t=Math.round(e).toString(16);return(t.length&1?"0":"")+t}}),fR=mr({parse:e=>{const t=parseFloat(e);return t==t?t:null},serialize:String}),hR=mr({parse:e=>e.toLowerCase()==="true",serialize:String});function Vi(e,t){return e.valueOf()===t.valueOf()}var mR=mr({parse:e=>{const t=parseInt(e);return t==t?new Date(t):null},serialize:e=>""+e.valueOf(),eq:Vi}),pR=mr({parse:e=>{const t=new Date(e);return t.valueOf()==t.valueOf()?t:null},serialize:e=>e.toISOString(),eq:Vi}),gR=mr({parse:e=>{const t=new Date(e.slice(0,10));return t.valueOf()==t.valueOf()?t:null},serialize:e=>e.toISOString().slice(0,10),eq:Vi});function Es(e){return mr({parse:t=>{try{const r=JSON.parse(t);if("~standard"in e){const s=e["~standard"].validate(r);if(s instanceof Promise)throw new Error("[nuqs] Only synchronous Standard Schemas are supported in parseAsJson.");return s.issues?null:s.value}return e(r)}catch{return null}},serialize:t=>JSON.stringify(t),eq(t,r){return t===r||JSON.stringify(t)===JSON.stringify(r)}})}var Ja=vi(),bx={};function xx(e,t={}){const r=(0,f.useId)(),s=kg(),n=Ag(),{history:o="replace",scroll:l=s?.scroll??!1,shallow:i=s?.shallow??!0,throttleMs:c=sn.timeMs,limitUrlUpdates:d=s?.limitUrlUpdates,clearOnDefault:u=s?.clearOnDefault??!0,startTransition:h,urlKeys:m=bx}=t,p=Object.keys(e).join(","),b=(0,f.useMemo)(()=>Object.fromEntries(Object.keys(e).map(I=>[I,m[I]??I])),[p,JSON.stringify(m)]),w=Eg(Object.values(b)),x=w.searchParams,N=(0,f.useRef)({}),C=(0,f.useMemo)(()=>Object.fromEntries(Object.keys(e).map(I=>[I,e[I].defaultValue??null])),[Object.values(e).map(({defaultValue:I})=>I).join(",")]),S=Ra.useQueuedQueries(Object.values(b)),[g,v]=(0,f.useState)(()=>Qa(e,m,x??new URLSearchParams,S).state),y=(0,f.useRef)(g);if(Le("[nuq+ %s `%s`] render - state: %O, iSP: %s",r,p,g,x),Object.keys(N.current).join("&")!==Object.values(b).join("&")){const{state:I,hasChanged:k}=Qa(e,m,x,S,N.current,y.current);k&&(Le("[nuq+ %s `%s`] State changed: %O",r,p,{state:I,initialSearchParams:x,queuedQueries:S,queryRef:N.current,stateRef:y.current}),y.current=I,v(I)),N.current=Object.fromEntries(Object.entries(b).map(([T,D])=>[D,e[T]?.type==="multi"?x?.getAll(D):x?.get(D)??null]))}(0,f.useEffect)(()=>{const{state:I,hasChanged:k}=Qa(e,m,x,S,N.current,y.current);k&&(Le("[nuq+ %s `%s`] State changed: %O",r,p,{state:I,initialSearchParams:x,queuedQueries:S,queryRef:N.current,stateRef:y.current}),y.current=I,v(I))},[Object.values(b).map(I=>`${I}=${x?.getAll(I)}`).join("&"),JSON.stringify(S)]),(0,f.useEffect)(()=>{const I=Object.keys(e).reduce((k,T)=>(k[T]=({state:D,query:_})=>{v(O=>{const{defaultValue:F}=e[T],E=b[T],z=D??F??null,G=O[T]??F??null;return Object.is(G,z)?(Le("[nuq+ %s `%s`] Cross-hook key sync %s: %O (default: %O). no change, skipping, resolved: %O",r,p,E,D,F,y.current),O):(y.current={...y.current,[T]:z},N.current[E]=_,Le("[nuq+ %s `%s`] Cross-hook key sync %s: %O (default: %O). updateInternalState, resolved: %O",r,p,E,D,F,y.current),y.current)})},k),{});for(const k of Object.keys(e)){const T=b[k];Le("[nuq+ %s `%s`] Subscribing to sync for `%s`",r,T,p),Ja.on(T,I[k])}return()=>{for(const k of Object.keys(e)){const T=b[k];Le("[nuq+ %s `%s`] Unsubscribing to sync for `%s`",r,T,p),Ja.off(T,I[k])}}},[p,b]);const R=(0,f.useCallback)((I,k={})=>{const T=Object.fromEntries(Object.keys(e).map(G=>[G,null])),D=typeof I=="function"?I(Ql(y.current,C))??T:I??T;Le("[nuq+ %s `%s`] setState: %O",r,p,D);let _,O=0,F=!1;const E=[];for(let[G,fe]of Object.entries(D)){const Z=e[G],re=b[G];if(!Z||fe===void 0)continue;(k.clearOnDefault??Z.clearOnDefault??u)&&fe!==null&&Z.defaultValue!==void 0&&(Z.eq??(($,ne)=>$===ne))(fe,Z.defaultValue)&&(fe=null);const Ne=fe===null?null:(Z.serialize??String)(fe);Ja.emit(re,{state:fe,query:Ne});const L={key:re,query:Ne,options:{history:k.history??Z.history??o,shallow:k.shallow??Z.shallow??i,scroll:k.scroll??Z.scroll??l,startTransition:k.startTransition??Z.startTransition??h}};if(k?.limitUrlUpdates?.method==="debounce"||d?.method==="debounce"||Z.limitUrlUpdates?.method==="debounce"){L.options.shallow===!0&&console.warn(hn(422));const $=k?.limitUrlUpdates?.timeMs??d?.timeMs??Z.limitUrlUpdates?.timeMs??sn.timeMs,ne=Ra.push(L,$,w,n);O<$&&(_=ne,O=$)}else{const $=k?.limitUrlUpdates?.timeMs??Z?.limitUrlUpdates?.timeMs??d?.timeMs??k.throttleMs??Z.throttleMs??c;E.push(Ra.abort(re)),Pn.push(L,$),F=!0}}const z=E.reduce((G,fe)=>fe(G),F?Pn.flush(w,n):Pn.getPendingPromise(w));return _??z},[p,o,i,l,c,d?.method,d?.timeMs,h,b,w.updateUrl,w.getSearchParamsSnapshot,w.rateLimitFactor,n,C]);return[(0,f.useMemo)(()=>Ql(g,C),[g,C]),R]}function Qa(e,t,r,s,n,o){let l=!1;const i=Object.entries(e).reduce((c,[d,u])=>{const h=t?.[d]??d,m=s[h],p=u.type==="multi"?[]:null,b=m===void 0?(u.type==="multi"?r?.getAll(h):r?.get(h))??p:m;return n&&o&&Id(n[h]??p,b)?(c[d]=o[d]??null,c):(l=!0,c[d]=(Mg(b)?null:Fu(u.parse,b,h))??null,n&&(n[h]=b),c)},{});if(!l){const c=Object.keys(e),d=Object.keys(o??{});l=c.length!==d.length||c.some(u=>!d.includes(u))}return{state:i,hasChanged:l}}function Ql(e,t){return Object.fromEntries(Object.keys(e).map(r=>[r,e[r]??t[r]??null]))}function ve(e,t={}){const{parse:r,type:s,serialize:n,eq:o,defaultValue:l,...i}=t,[{[e]:c},d]=xx({[e]:{parse:r??(u=>u),type:s,serialize:n,eq:o,defaultValue:l}},i);return[c,(0,f.useCallback)((u,h={})=>d(m=>({[e]:typeof u=="function"?u(m[e]):u}),h),[e,d])]}var Lu=Dr()(e=>({tableName:null,columnName:null,referencedColumn:null,setRecordReference:(t,r,s)=>e({tableName:t,columnName:r,referencedColumn:s}),clearRecordReference:()=>e({tableName:null,columnName:null,referencedColumn:null})})),Nn=e=>String(e).padStart(2,"0"),Xa=e=>`${e.getFullYear()}-${Nn(e.getMonth()+1)}-${Nn(e.getDate())}T${Nn(e.getHours())}:${Nn(e.getMinutes())}`,zu=({columnName:e,dataTypeLabel:t,columnDefault:r,enumValues:s,isForeignKey:n,referencedTable:o,referencedColumn:l,hideLabel:i=!1})=>{const[,c]=ve(ce.REFERENCED_TABLE_STATE_KEYS.ACTIVE_TABLE),{control:d}=Ge(),{openOverlay:u}=je(),{setRecordReference:h}=Lu(),m=p=>{const b={...p,value:p.value??""},w=i?e:void 0;if(n)return(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsxs)("div",{className:"flex",children:[(0,a.jsx)(Ke,{id:e,"aria-label":w,placeholder:r??"",className:"-me-px flex-1 rounded-e-none shadow-none focus-visible:z-10",...b}),(0,a.jsx)(zs,{delayDuration:0,children:(0,a.jsxs)(ir,{children:[(0,a.jsx)(ar,{asChild:!0,children:(0,a.jsx)("button",{"aria-label":"Go to table",className:"inline-flex w-9 items-center justify-center rounded-e-md border border-input bg-background text-muted-foreground/80 text-sm outline-none transition-[color,box-shadow] hover:text-accent-foreground focus:z-10 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",type:"button",onClick:()=>{o&&e&&l&&h(o,e,l),u("records.record-reference"),c(o)},children:(0,a.jsx)(Xn,{"aria-hidden":"true",className:"size-4",size:16})})}),(0,a.jsx)(or,{className:"px-2 py-1 text-xs",children:"Go to table"})]})})]}),(0,a.jsxs)("span",{className:"text-xs text-muted-foreground",children:["Has a foreign key relation to"," ",(0,a.jsx)("button",{type:"button",className:"font-mono text-primary",onClick:()=>{o&&e&&l&&h(o,e,l),u("records.record-reference"),c(o)},children:o})," ","table"]})]});if(t==="int"||t==="bigint"||t==="smallint"||t==="numeric"||t==="float"||t==="double"||t==="money")return(0,a.jsx)(Ke,{id:e,"aria-label":w,type:"number",placeholder:r??"0",...b});if(t==="boolean")return(0,a.jsxs)(dt,{value:p.value,onValueChange:x=>p.onChange(x),children:[(0,a.jsx)(lt,{"aria-label":w,className:"w-full",children:(0,a.jsx)(it,{placeholder:r??"true"})}),(0,a.jsxs)(ct,{children:[(0,a.jsx)(ue,{value:"true",children:"true"}),(0,a.jsx)(ue,{value:"false",children:"false"})]})]});if(t==="text"||t==="xml")return(0,a.jsx)(Sr,{id:e,"aria-label":w,placeholder:r??"",rows:4,...b});if(t==="json"||t==="jsonb")return(0,a.jsx)(Sr,{id:e,"aria-label":w,placeholder:r??'{"key": "value"}',rows:6,...b});if(t==="date")return r?.toLowerCase().includes("current_date")||r?.toLowerCase().includes("now()")||r?.toLowerCase().includes("curdate()")?(0,a.jsxs)("div",{className:"flex",children:[(0,a.jsx)(Ur,{value:p.value?new Date(p.value):p.value===""?null:void 0,onChange:x=>p.onChange(x?x.toISOString().split("T")[0]:""),placeholder:r??"Select a date",className:"-me-px flex-1 rounded-e-none shadow-none focus-visible:z-10"}),(0,a.jsx)(zs,{delayDuration:0,children:(0,a.jsxs)(ir,{children:[(0,a.jsx)(ar,{asChild:!0,children:(0,a.jsx)("button",{"aria-label":"Set to now",className:"inline-flex w-7 items-center justify-center rounded-e-md border border-input bg-background text-muted-foreground/80 text-sm outline-none transition-[color,box-shadow] hover:text-accent-foreground focus:z-10 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",type:"button",onClick:()=>{const x=new Date().toISOString().split("T")[0];p.onChange(x)},children:(0,a.jsx)(Ia,{"aria-hidden":"true",className:"size-4",size:16})})}),(0,a.jsx)(or,{className:"px-2 py-1 text-xs",children:"Set to now"})]})})]}):(0,a.jsx)(Ur,{value:p.value?new Date(p.value):p.value===""?null:void 0,onChange:x=>p.onChange(x?x.toISOString().split("T")[0]:""),placeholder:r??"Select a date"});if(t==="timestamptz")return r?.toLowerCase().includes("current_timestamp")||r?.toLowerCase().includes("now()")||r?.toLowerCase().includes("localtimestamp")?(0,a.jsxs)("div",{className:"flex",children:[(0,a.jsx)(Ur,{value:p.value?new Date(p.value):p.value===""?null:void 0,onChange:x=>p.onChange(x?x.toISOString():""),showTime:!0,isFormatted:!1,placeholder:r??"Select a date and time",className:"-me-px flex-1 rounded-e-none shadow-none focus-visible:z-10"}),(0,a.jsx)(zs,{delayDuration:0,children:(0,a.jsxs)(ir,{children:[(0,a.jsx)(ar,{asChild:!0,children:(0,a.jsx)("button",{"aria-label":"Set to now",className:"inline-flex w-7 items-center justify-center rounded-e-md border border-input bg-background text-muted-foreground/80 text-sm outline-none transition-[color,box-shadow] hover:text-accent-foreground focus:z-10 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",type:"button",onClick:()=>{const x=new Date().toISOString();p.onChange(x)},children:(0,a.jsx)(Ia,{"aria-hidden":"true",className:"size-4",size:16})})}),(0,a.jsx)(or,{className:"px-2 py-1 text-xs",children:"Set to now"})]})})]}):(0,a.jsx)(Ur,{value:p.value?new Date(p.value):p.value===""?null:void 0,onChange:x=>p.onChange(x?x.toISOString():""),showTime:!0,isFormatted:!1,placeholder:r??"Select a date and time"});if(t==="timestamp")return r?.toLowerCase().includes("current_timestamp")||r?.toLowerCase().includes("now()")||r?.toLowerCase().includes("localtimestamp")?(0,a.jsxs)("div",{className:"flex",children:[(0,a.jsx)(Ur,{value:p.value?new Date(p.value):p.value===""?null:void 0,onChange:x=>p.onChange(x?Xa(x):""),showTime:!0,isFormatted:!1,placeholder:r??"Select a date and time",className:"-me-px flex-1 rounded-e-none shadow-none focus-visible:z-10"}),(0,a.jsx)(zs,{delayDuration:0,children:(0,a.jsxs)(ir,{children:[(0,a.jsx)(ar,{asChild:!0,children:(0,a.jsx)("button",{"aria-label":"Set to now",className:"inline-flex w-7 items-center justify-center rounded-e-md border border-input bg-background text-muted-foreground/80 text-sm outline-none transition-[color,box-shadow] hover:text-accent-foreground focus:z-10 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",type:"button",onClick:()=>{p.onChange(Xa(new Date))},children:(0,a.jsx)(Ia,{"aria-hidden":"true",className:"size-4",size:16})})}),(0,a.jsx)(or,{className:"px-2 py-1 text-xs",children:"Set to now"})]})})]}):(0,a.jsx)(Ur,{value:p.value?new Date(p.value):p.value===""?null:void 0,onChange:x=>p.onChange(x?Xa(x):""),showTime:!0,isFormatted:!1,placeholder:r??"Select a date and time"});if(t==="uuid")return(0,a.jsxs)("div",{className:"flex",children:[(0,a.jsx)(Ke,{id:e,"aria-label":w,type:"text",placeholder:r??"",pattern:"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",className:"-me-px flex-1 rounded-e-none shadow-none focus-visible:z-10",...b}),(0,a.jsx)(zs,{delayDuration:0,children:(0,a.jsxs)(ir,{children:[(0,a.jsx)(ar,{asChild:!0,children:(0,a.jsx)("button",{"aria-label":"Generate UUID",className:"inline-flex w-9 items-center justify-center rounded-e-md border border-input bg-background text-muted-foreground/80 text-sm outline-none transition-[color,box-shadow] hover:text-accent-foreground focus:z-10 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",type:"button",onClick:()=>{const x=crypto.randomUUID();p.onChange(x)},children:(0,a.jsx)(di,{"aria-hidden":"true",className:"size-4",size:16})})}),(0,a.jsx)(or,{className:"px-2 py-1 text-xs",children:"Generate UUID"})]})})]});if(t==="array")return(0,a.jsx)(Sr,{id:e,"aria-label":w,placeholder:r??'["item1", "item2"]',rows:3,...b});if(t==="enum")return s&&s.length>0?(0,a.jsxs)(dt,{value:p.value,onValueChange:x=>p.onChange(x),children:[(0,a.jsx)(lt,{"aria-label":w,className:"w-full",children:(0,a.jsx)(it,{placeholder:r??"Select a value"})}),(0,a.jsx)(ct,{children:s.map(x=>(0,a.jsx)(ue,{value:x,children:x},x))})]}):(0,a.jsx)(Ke,{id:e,"aria-label":w,placeholder:r??"",...b});if(t==="interval")return(0,a.jsx)(Ke,{id:e,"aria-label":w,type:"text",placeholder:r??"1 day",...b});if(t==="bytea"){const{value:x,...N}=b,C=typeof x=="string"?x:"";return(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[C&&(0,a.jsx)("div",{role:"group","aria-label":`${e} stored value`,className:"truncate rounded-md border border-input bg-muted/40 px-3 py-2 font-mono text-xs",children:C}),(0,a.jsx)(Ke,{id:e,"aria-label":w,type:"file",...N})]})}return t==="inet"||t==="cidr"||t==="macaddr"||t==="macaddr8"?(0,a.jsx)(Ke,{id:e,"aria-label":w,type:"text",placeholder:t==="inet"?"192.168.1.1":t==="cidr"?"192.168.1.0/24":t==="macaddr"?"08:00:2b:01:02:03":"08:00:2b:01:02:03:04:05",...b}):t==="point"||t==="line"||t==="polygon"?(0,a.jsx)(Ke,{id:e,"aria-label":w,type:"text",placeholder:t==="point"?"(x,y)":t==="line"?"{A,B,C}":"((x1,y1),(x2,y2),...)",...b}):(0,a.jsx)(Ke,{id:e,"aria-label":w,type:"text",placeholder:r??"",...b})};return(0,a.jsx)(Ot,{control:d,name:e,render:({field:p})=>i?(0,a.jsx)("div",{role:"group","aria-label":e,children:m(p)}):(0,a.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,a.jsxs)("div",{className:"col-span-1 flex flex-col gap-1",children:[(0,a.jsx)(me,{htmlFor:e,children:e}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:t})]}),(0,a.jsx)("div",{className:"col-span-2 w-full",children:m(p)})]})},e)},Sx=({tableName:e})=>{const t=St(),{closeOverlay:r}=je(),{selectedDatabase:s,dbType:n}=Me(),{mutateAsync:o,isPending:l}=ht({mutationFn:async c=>(await qp({tableName:e,data:c,db:s})).data.data,onSuccess:async()=>{await Promise.all([t.invalidateQueries({queryKey:Ee.dataByTable(e),exact:!1}),t.invalidateQueries({queryKey:Ee.lists()})]),r("records.add-record"),n&&cr.capture("record_created",{db_type:n})}});return{createRecord:async(c,d)=>{if(!c||Object.keys(c).length===0)throw new Error("At least one field is required");return we.promise(o(c,d),{loading:"Creating record...",success:u=>u||"Record created successfully",error:u=>u.detail||u.message||"Failed to create record"})},isCreatingRecord:l}};function Cx({className:e,...t}){return(0,a.jsx)("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:(0,a.jsx)("table",{"data-slot":"table",className:V("w-full caption-bottom text-xs",e),...t})})}function wx({className:e,...t}){return(0,a.jsx)("thead",{"data-slot":"table-header",className:V("[&_tr]:border-b",e),...t})}function Nx({className:e,...t}){return(0,a.jsx)("tbody",{"data-slot":"table-body",className:V("[&_tr:last-child]:border-0",e),...t})}function Za({className:e,...t}){return(0,a.jsx)("tr",{"data-slot":"table-row",className:V("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",e),...t})}function jx({className:e,...t}){return(0,a.jsx)("th",{"data-slot":"table-head",className:V("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0",e),...t})}function Xl({className:e,...t}){return(0,a.jsx)("td",{"data-slot":"table-cell",className:V("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",e),...t})}var va=({tableName:e,isReferencedTable:t=!1})=>{const{selectedDatabase:r}=Me(),[s]=ve(ce.REFERENCED_TABLE_STATE_KEYS.ACTIVE_TABLE),n=e||s||"",[o]=ve(t?ce.REFERENCED_TABLE_STATE_KEYS.CURSOR:ce.TABLE_STATE_KEYS.CURSOR),[l]=ve(t?ce.REFERENCED_TABLE_STATE_KEYS.LIMIT.toString():ce.TABLE_STATE_KEYS.LIMIT),[i]=ve(t?ce.REFERENCED_TABLE_STATE_KEYS.DIRECTION:ce.TABLE_STATE_KEYS.DIRECTION),[c]=ve(ce.REFERENCED_TABLE_STATE_KEYS.SORT,Es(v=>v).withDefault([]).withOptions({history:"push"})),[d]=ve(ce.TABLE_STATE_KEYS.SORT),[u]=ve(ce.TABLE_STATE_KEYS.ORDER),[h]=ve(t?ce.REFERENCED_TABLE_STATE_KEYS.FILTERS:ce.TABLE_STATE_KEYS.FILTERS,Es(v=>v).withDefault([]).withOptions({history:"push"})),m={tableName:n,cursor:o,limit:l,direction:i,sort:t&&c?.length>0?JSON.stringify(c):d,order:u,filters:h?.length>0?JSON.stringify(h):void 0,db:r},p=v=>Yp({tableName:v.tableName,limit:v.limit?.toString()||ce.CACHE_KEYS.TABLE_DEFAULT_LIMIT.toString(),db:v.db??void 0,cursor:v.cursor,direction:v.direction,sort:v.sort??void 0,order:v.order,filters:v.filters}),{data:b,isLoading:w,isRefetching:x,refetch:N,error:C}=Rr({queryKey:Ee.data(m),queryFn:()=>p(m),select:v=>v.data.data,enabled:!!n}),S=St();return{tableData:b,prefetchPage:(v,y)=>{const R={...m,cursor:v,direction:y};S.prefetchQuery({queryKey:Ee.data(R),queryFn:()=>p(R)})},pageKey:JSON.stringify(Ee.data(m)),isLoadingTableData:w,isRefetchingTableData:x,errorTableData:C,refetchTableData:N}},Ix=({tableName:e})=>{const[t,r]=ve(ce.REFERENCED_TABLE_STATE_KEYS.FILTERS,Es(S=>S).withDefault([]).withOptions({history:"push"})),[,s]=ve(ce.REFERENCED_TABLE_STATE_KEYS.CURSOR),[,n]=ve(ce.REFERENCED_TABLE_STATE_KEYS.DIRECTION),{tableCols:o}=mt({tableName:e}),[l,i]=(0,f.useState)(!1),[c,d]=(0,f.useState)([]),u=()=>{const S=o?.[0]?.columnName??"";d(g=>[...g,{columnName:S,operator:"=",value:""}])},h=S=>{d(c.filter((g,v)=>v!==S))},m=(S,g)=>{d(c.map((v,y)=>y===S?{...v,columnName:g}:v))},p=(S,g)=>{d(c.map((v,y)=>y===S?{...v,value:g}:v))},b=(S,g)=>{d(c.map((v,y)=>y===S?{...v,operator:g}:v))},w=()=>{d([]),r([]),s(null),n(null),i(!1)},x=()=>{const S=c.filter(g=>g.columnName&&g.operator&&g.value!=="");r(S),s(null),n(null),i(!1)},N=t.length>0,C=S=>{S&&d(t),i(S)};return(0,a.jsxs)(Mr,{modal:!0,open:l,onOpenChange:C,children:[(0,a.jsx)(fs,{asChild:!0,children:(0,a.jsxs)(B,{type:"button",variant:"ghost",className:"border-r border-l-0 border-y-0 border-border rounded-none text-xs h-full text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors","aria-label":"Filter table data","data-active":N,children:[(0,a.jsx)(ad,{className:"size-4"}),"Filter",N&&(0,a.jsx)(et,{className:"text-[10px] font-normal text-primary bg-primary/10 border border-primary/30 px-1.5 py-0.5",children:t.length})]})}),(0,a.jsxs)(ur,{className:"w-md space-y-2",align:"start",children:[(0,a.jsx)("div",{className:"flex items-center gap-4",children:(0,a.jsxs)(B,{variant:"outline",size:"lg",className:"text-sm",onClick:u,children:["Add filter",c&&c.length>0&&(0,a.jsx)(et,{className:"text-xs font-normal text-primary bg-primary/10 border border-primary/30 px-1.5 py-0.5",children:c.length})]})}),(0,a.jsx)("div",{className:"flex flex-col gap-4",children:c.length>0?c.map((S,g)=>(0,a.jsxs)("div",{className:"flex-1 flex h-9 gap-2",children:[(0,a.jsxs)(dt,{value:S.columnName,onValueChange:v=>m(g,v),children:[(0,a.jsx)(lt,{className:"w-full flex-1",children:(0,a.jsx)(it,{placeholder:"Select column"})}),(0,a.jsx)(ct,{children:o?.map(v=>(0,a.jsx)(ue,{value:v.columnName,children:v.columnName},v.columnName))})]}),(0,a.jsxs)(dt,{value:S.operator,onValueChange:v=>b(g,v),children:[(0,a.jsx)(lt,{children:(0,a.jsx)(it,{placeholder:"Op"})}),(0,a.jsxs)(ct,{children:[(0,a.jsx)(ue,{value:"=",children:"="}),(0,a.jsx)(ue,{value:"!=",children:"!="}),(0,a.jsx)(ue,{value:">",children:">"}),(0,a.jsx)(ue,{value:">=",children:">="}),(0,a.jsx)(ue,{value:"<",children:"<"}),(0,a.jsx)(ue,{value:"<=",children:"<="}),(0,a.jsx)(ue,{value:"is",children:"is"}),(0,a.jsx)(ue,{value:"is not",children:"is not"}),(0,a.jsx)(ue,{value:"like",children:"like"}),(0,a.jsx)(ue,{value:"not like",children:"not like"}),(0,a.jsx)(ue,{value:"ilike",children:"ilike"}),(0,a.jsx)(ue,{value:"not ilike",children:"not ilike"})]})]}),(0,a.jsx)(Ke,{type:"text",placeholder:"Value",value:S.value,onChange:v=>p(g,v.target.value)}),(0,a.jsx)(B,{variant:"ghost",size:"icon",className:"text-xs",onClick:()=>h(g),children:(0,a.jsx)(As,{className:"size-4"})})]},`${S.columnName}-${g}`)):(0,a.jsx)("div",{className:"flex-1 flex h-9 gap-2 items-center justify-center",children:(0,a.jsx)("p",{className:"text-sm text-muted-foreground text-center",children:"No filters applied"})})}),(0,a.jsxs)("div",{className:"gap-2 flex justify-end",children:[(0,a.jsx)(B,{variant:"outline",size:"lg",className:"text-sm",onClick:w,children:"Reset"}),(0,a.jsx)(B,{variant:"default",size:"lg",className:"text-sm",onClick:x,children:"Apply"})]})]})]})},Tx=({tableName:e})=>{const{tableCols:t}=mt({tableName:e}),[r,s]=ve(ce.REFERENCED_TABLE_STATE_KEYS.SORT,Es(C=>C).withDefault([]).withOptions({history:"push"})),[,n]=ve(ce.REFERENCED_TABLE_STATE_KEYS.CURSOR),[,o]=ve(ce.REFERENCED_TABLE_STATE_KEYS.DIRECTION),[l,i]=(0,f.useState)(!1),[c,d]=(0,f.useState)([]),u=()=>{const C=t?.[0]?.columnName??"";d(S=>[...S,{columnName:C,direction:"asc"}])},h=C=>{d(c.filter((S,g)=>g!==C))},m=(C,S)=>{d(c.map((g,v)=>v===C?{...g,columnName:S}:g))},p=(C,S)=>{d(c.map((g,v)=>v===C?{...g,direction:S}:g))},b=()=>{d([]),s([]),n(null),o(null),i(!1)},w=()=>{const C=c.filter(S=>S.columnName);s(C),n(null),o(null),i(!1)},x=r.length>0,N=C=>{C&&d(r),i(C)};return(0,a.jsxs)(Mr,{modal:!0,open:l,onOpenChange:N,children:[(0,a.jsx)(fs,{asChild:!0,children:(0,a.jsxs)(B,{variant:"ghost",className:"border-r border-l-0 border-y-0 border-border rounded-none text-xs h-full text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors",children:[(0,a.jsx)(Xm,{className:"size-4"}),"Sort",x&&(0,a.jsx)(et,{className:"text-[10px] font-normal text-primary bg-primary/10 border border-primary/30 px-1.5 py-0.5",children:r.length})]})}),(0,a.jsxs)(ur,{className:"w-md space-y-2",align:"start",children:[(0,a.jsx)("div",{className:"flex items-center gap-4",children:(0,a.jsxs)(B,{variant:"outline",size:"lg",className:"text-sm",onClick:u,children:["Add sort",c&&c.length>0&&(0,a.jsx)(et,{className:"text-xs font-normal text-primary bg-primary/10 border border-primary/30 px-1.5 py-0.5",children:c.length})]})}),(0,a.jsx)("div",{className:"flex flex-col gap-4",children:c.length>0?c.map((C,S)=>(0,a.jsxs)("div",{className:"flex-1 flex h-9 gap-2 items-center",children:[(0,a.jsxs)(dt,{value:C.columnName,onValueChange:g=>m(S,g),children:[(0,a.jsx)(lt,{className:"w-full flex-1",children:(0,a.jsx)(it,{placeholder:"Select column"})}),(0,a.jsx)(ct,{children:t?.map(g=>(0,a.jsx)(ue,{value:g.columnName,children:g.columnName},g.columnName))})]}),(0,a.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,a.jsx)(me,{htmlFor:`sort-direction-${S}`,children:"Asc"}),(0,a.jsx)(Zn,{id:`sort-direction-${S}`,checked:C.direction==="desc",onCheckedChange:g=>p(S,g?"desc":"asc")}),(0,a.jsx)(me,{htmlFor:`sort-direction-${S}`,children:"Desc"})]}),(0,a.jsx)(B,{variant:"ghost",size:"icon",className:"text-xs",onClick:()=>h(S),children:(0,a.jsx)(As,{className:"size-4"})})]},`${C.columnName}-${S}`)):(0,a.jsx)("div",{className:"flex-1 flex h-9 gap-2 items-center justify-center",children:(0,a.jsx)("p",{className:"text-sm text-muted-foreground text-center",children:"No sorts applied"})})}),(0,a.jsxs)("div",{className:"gap-2 flex justify-end",children:[(0,a.jsx)(B,{variant:"outline",size:"lg",className:"text-sm",onClick:b,children:"Reset"}),(0,a.jsx)(B,{variant:"default",size:"lg",className:"text-sm",onClick:w,children:"Apply"})]})]})]})},Rx=({tableName:e,referencedColumn:t,columnName:r})=>{const{setValue:s}=Ge(),{closeOverlay:n}=je(),{tableCols:o,isLoadingTableCols:l}=mt({tableName:e}),[i,c]=ve(ce.REFERENCED_TABLE_STATE_KEYS.ACTIVE_TABLE),{tableData:d,isLoadingTableData:u}=va({tableName:e,isReferencedTable:!0}),[,h]=ve(ce.REFERENCED_TABLE_STATE_KEYS.CURSOR),[,m]=ve(ce.REFERENCED_TABLE_STATE_KEYS.DIRECTION),[p,b]=ve(ce.REFERENCED_TABLE_STATE_KEYS.LIMIT.toString());(0,f.useEffect)(()=>{e&&i!==e&&c(e),e&&!p&&b(ce.REFERENCED_TABLE_STATE_KEYS.DEFAULT_LIMIT.toString())},[e,i,p,c,b]);const w=()=>{d?.meta?.nextCursor&&(h(d.meta.nextCursor),m("forward"))},x=()=>{d?.meta?.prevCursor&&(h(d.meta.prevCursor),m("backward"))},N=(0,f.useMemo)(()=>o?.map(g=>({id:g.columnName,accessorKey:g.columnName,header:g.columnName,cell:({row:v})=>(0,a.jsx)("div",{className:"font-medium max-w-[200px] truncate",children:dr(v.getValue(g.columnName))})}))??[],[o]),C=si({columns:N??[],data:d?.data??[],getCoreRowModel:ri()}),S=g=>{s(r??"",g.original[t??""]),n("records.record-reference")};return l||u?(0,a.jsx)("div",{className:"flex items-center justify-center h-full",children:(0,a.jsx)(dn,{size:"size-8"})}):(0,a.jsxs)("div",{children:[(0,a.jsxs)("div",{className:"sticky top-0 left-0 right-0 h-8 border-b border-border w-full flex items-center justify-between bg-background z-50",children:[(0,a.jsxs)("div",{className:"flex items-center h-full",children:[(0,a.jsx)(Ix,{tableName:e}),(0,a.jsx)(Tx,{tableName:e})]}),(0,a.jsxs)("div",{className:"flex items-center h-full",children:[(0,a.jsx)(B,{variant:"ghost",size:"icon",className:"border-l border-r-0 border-y-0 border-border rounded-none text-xs h-full aspect-square size-8 text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors",onClick:x,disabled:!d?.meta?.hasPreviousPage,children:(0,a.jsx)(Wm,{className:"size-3"})}),(0,a.jsx)(B,{variant:"ghost",size:"icon",className:"border-r border-l border-y-0 border-border rounded-none text-xs h-full aspect-square size-8 text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors",onClick:w,disabled:!d?.meta?.hasNextPage,children:(0,a.jsx)(zn,{className:"size-3"})})]})]}),(0,a.jsxs)(Cx,{children:[(0,a.jsx)(wx,{children:C.getHeaderGroups().map(g=>(0,a.jsx)(Za,{className:"hover:bg-transparent text-xs sticky top-0 right-0 left-0 supports-backdrop-filter:backdrop-blur-sm",children:g.headers.map(v=>(0,a.jsx)(jx,{className:"border-r border-border",children:v.isPlaceholder?null:rs(v.column.columnDef.header,v.getContext())},v.id))},g.id))}),(0,a.jsx)(Nx,{children:C.getRowModel().rows?.length?C.getRowModel().rows.map(g=>(0,a.jsx)(Za,{className:"text-xs cursor-pointer",onClick:()=>S(g),children:g.getVisibleCells().map(v=>(0,a.jsx)(Xl,{className:"border-r border-border",children:rs(v.column.columnDef.cell,v.getContext())},v.id))},g.id)):(0,a.jsx)(Za,{children:(0,a.jsx)(Xl,{className:"h-24 text-center",colSpan:N.length,children:"No results."})})})]})]})},$u=()=>{const{closeOverlay:e,isOverlayOpen:t}=je(),{tableName:r,referencedColumn:s,columnName:n,clearRecordReference:o}=Lu(),[,l]=ve(ce.REFERENCED_TABLE_STATE_KEYS.ACTIVE_TABLE),[,i]=ve(ce.REFERENCED_TABLE_STATE_KEYS.CURSOR),[,c]=ve(ce.REFERENCED_TABLE_STATE_KEYS.DIRECTION),[,d]=ve(ce.REFERENCED_TABLE_STATE_KEYS.LIMIT.toString()),[,u]=ve(ce.REFERENCED_TABLE_STATE_KEYS.SORT.toString()),[,h]=ve(ce.REFERENCED_TABLE_STATE_KEYS.ORDER.toString()),[,m]=ve(ce.REFERENCED_TABLE_STATE_KEYS.FILTERS,Es(b=>b).withDefault([]).withOptions({history:"push"}));if(!r||!s)return null;const p=()=>{e("records.record-reference"),o(),l(null),i(null),c(null),d(null),u(null),h(null),m(null)};return(0,a.jsx)(Ut,{title:`View records in the table ${r}`,size:"max-w-lg!",contentClassName:"p-0",open:t("records.record-reference"),onOpenChange:b=>{b||p()},children:(0,a.jsx)(Rx,{tableName:r,referencedColumn:s,columnName:n??""})})},Ex=({tableName:e})=>{const{closeOverlay:t,isOverlayOpen:r}=je(),{tableCols:s,isLoadingTableCols:n}=mt({tableName:e}),{createRecord:o,isCreatingRecord:l}=Sx({tableName:e}),i=Ms(),c=async h=>{o(h,{onSuccess:()=>{i.reset(),t("records.add-record")},onError:m=>{console.error("Failed to create record:",m)}})},d=()=>{i.reset(),t("records.add-record")},u=()=>s&&s.length>0?(0,a.jsxs)(Ds,{...i,children:[(0,a.jsxs)("form",{onSubmit:i.handleSubmit(c),className:"flex flex-col h-full",children:[(0,a.jsx)("div",{className:"space-y-6",children:s&&s.length>0&&!n?s.map(h=>(0,a.jsx)(zu,{...h},h.columnName)):null}),(0,a.jsxs)("div",{className:"flex justify-end gap-2 py-6",children:[(0,a.jsx)(un,{asChild:!0,onClick:d,disabled:l,children:(0,a.jsx)(B,{variant:"outline",size:"lg",children:"Close"})}),(0,a.jsx)(B,{type:"submit",size:"lg",disabled:l||!i.formState.isDirty,children:"Save"})]})]}),(0,a.jsx)($u,{})]}):(0,a.jsx)("div",{className:"flex flex-col h-full",children:(0,a.jsx)("div",{className:"space-y-6",children:(0,a.jsx)(rt,{variant:"info",title:"No columns found",message:"Please add at least one column to the table before adding a record."})})});return(0,a.jsx)(Ut,{title:`Add a new record to the table: ${e}`,open:r("records.add-record"),onOpenChange:h=>{h||d()},children:u()})},Bi=Ip,ya=({className:e,ref:t,...r})=>(0,a.jsx)(cd,{ref:t,className:V("inline-flex h-10 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),...r});ya.displayName=cd.displayName;var as=({className:e,ref:t,...r})=>(0,a.jsx)(ld,{ref:t,className:V("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),...r});as.displayName=ld.displayName;var os=({className:e,ref:t,...r})=>(0,a.jsx)(dd,{ref:t,className:V("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...r});os.displayName=dd.displayName;var is=e=>{const t=e.trim();if(t.startsWith("[")||t.startsWith("{"))try{const r=JSON.parse(t);if(Array.isArray(r))return r;if(typeof r=="object"&&r!==null)return[r];throw new Error("Invalid JSON format")}catch(r){throw r instanceof SyntaxError?new Error(`Invalid JSON format: ${r.message.replace("JSON.","")}`):r}return kx(t)},kx=e=>{const t=e.split(`
|
|
4
|
+
`).filter(l=>l.trim());if(t.length<1)throw new Error("No data to parse");const r=t[0],s=Ox(r),n=Zl(r,s).map(l=>l.trim());if(n.length===0)throw new Error("No headers found in CSV");const o=[];for(let l=1;l<t.length;l++){const i=Zl(t[l],s);i.length!==n.length&&console.warn(`Row ${l+1} has ${i.length} values but ${n.length} headers expected`);const c={};n.forEach((d,u)=>{const h=i[u]?.trim()??"";c[d]=Dx(h)}),o.push(c)}if(o.length===0)throw new Error("No records found in CSV");return o},Ax={",":/,/g," ":/\t/g,";":/;/g},Ox=e=>{const t=[","," ",";"];let r=0,s=",";for(const n of t){const o=(e.match(Ax[n])||[]).length;o>r&&(r=o,s=n)}return s},Zl=(e,t)=>{const r=[];let s="",n=!1;for(let o=0;o<e.length;o++){const l=e[o],i=e[o+1];l==='"'?n&&i==='"'?(s+='"',o++):n=!n:l===t&&!n?(r.push(s),s=""):s+=l}return r.push(s),r},Dx=e=>{if(e===""||e==="null")return null;if(e==="true")return!0;if(e==="false")return!1;if(!Number.isNaN(Number(e))&&e!==""){const t=Number(e);if(String(t)===e||e.includes(".")&&!Number.isNaN(parseFloat(e)))return t}if(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))try{return JSON.parse(e)}catch{}return e},ba=({tableName:e})=>{const t=St(),{selectedDatabase:r,dbType:s}=Me(),{mutateAsync:n,isPending:o}=ht({mutationFn:async i=>(await Mp({tableName:e,records:i,db:r})).data.data,onSuccess:async()=>{await Promise.all([t.invalidateQueries({queryKey:Ee.dataByTable(e),exact:!1}),t.invalidateQueries({queryKey:Ee.lists(),exact:!1}),t.invalidateQueries({queryKey:Ee.columnsByTable(e),exact:!1})])}});return{bulkInsertRecords:async(i,c)=>{if(!i||i.length===0)throw new Error("At least one record is required");return we.promise(n(i),{loading:`Inserting ${i.length} record${i.length!==1?"s":""}...`,success:d=>(c?.onSuccess?.(d),s&&c?.format&&cr.capture("bulk_insert",{db_type:s,format:c.format}),d.failureCount>0?`${d.successCount} records inserted, ${d.failureCount} failed`:d.message),error:d=>(c?.onError?.(d),d.detail||d.message||"Failed to insert records")})},isInserting:o}},Mx=({tableName:e})=>{const{closeOverlay:t,isOverlayOpen:r}=je(),{bulkInsertRecords:s,isInserting:n}=ba({tableName:e}),o=(0,f.useRef)(null),[l,i]=(0,f.useState)(""),[c,d]=(0,f.useState)(null),[u,h]=(0,f.useState)([]),[m,p]=(0,f.useState)(null),[b,w]=(0,f.useState)("file"),x=g=>{const v=g.target.files?.[0];v&&(d(v),h([]),p(null))},N=(0,f.useCallback)(()=>{p(null),h([]);try{if(b==="file"&&c){const g=new FileReader;g.onload=v=>{try{const y=v.target?.result,R=is(y);h(R)}catch(y){p(y instanceof Error?y.message:"Failed to parse file")}},g.readAsText(c)}else if(l.trim()){const g=is(l);h(g)}else p(b==="file"?"No file selected":"Input is empty")}catch(g){p(g instanceof Error?g.message:"Failed to format data")}},[l,c,b]),C=async()=>{if(u.length===0){p("No records to insert");return}try{await s(u,{format:"csv",onSuccess:()=>{i(""),d(null),h([]),p(null),t("records.bulk-insert-csv")}})}catch(g){console.error("Error inserting records:",g)}},S=()=>{i(""),d(null),h([]),p(null),t("records.bulk-insert-csv")};return(0,a.jsx)(Ut,{title:`Add data from CSV into: ${e}`,open:r("records.bulk-insert-csv"),onOpenChange:g=>{g||S()},children:(0,a.jsxs)("div",{className:"flex flex-col h-full gap-4",children:[(0,a.jsx)(rt,{variant:"info",title:"CSV Import",message:"Enter CSV data with headers. Supports comma, tab, or semicolon delimiters. First row should be column names."}),(0,a.jsxs)(Bi,{value:b,onValueChange:g=>w(g),children:[(0,a.jsxs)(ya,{className:"grid w-full grid-cols-2",children:[(0,a.jsx)(as,{value:"file",children:"File"}),(0,a.jsx)(as,{value:"text",children:"Text"})]}),(0,a.jsx)(os,{value:"file",className:"flex-1 flex flex-col gap-4",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(me,{htmlFor:"file-input",className:"mb-2 text-sm font-medium text-foreground",children:"Select CSV file"}),(0,a.jsx)("input",{id:"file-input",ref:o,type:"file",accept:".csv",onChange:x,disabled:n,className:"text-sm text-muted-foreground file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 cursor-pointer disabled:opacity-50"})]})}),(0,a.jsx)(os,{value:"text",className:"flex-1 flex flex-col gap-4",children:(0,a.jsxs)("div",{className:"flex-1 flex flex-col",children:[(0,a.jsx)(me,{htmlFor:"text-input",className:"text-sm font-medium mb-2 text-foreground",children:"Data Input"}),(0,a.jsx)(Sr,{id:"text-input",value:l,onChange:g=>{i(g.target.value),h([]),p(null)},placeholder:`column1,column2,column3
|
|
5
|
+
value1,value2,value3
|
|
6
|
+
value4,value5,value6`,className:"flex-1 resize-none font-mono text-sm",disabled:n})]})})]}),m&&(0,a.jsx)(rt,{variant:"error",title:"Parse Error",message:m}),u.length>0&&(0,a.jsx)(rt,{variant:"success",title:"Ready to Insert",message:`${u.length} record${u.length!==1?"s":""} parsed successfully`}),(0,a.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,a.jsx)(B,{variant:"secondary",size:"lg",onClick:N,disabled:b==="file"?!c:!l.trim()||n,children:"Format"}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(un,{asChild:!0,onClick:S,disabled:n,children:(0,a.jsx)(B,{variant:"outline",size:"lg",children:"Close"})}),(0,a.jsx)(B,{type:"button",size:"lg",onClick:C,disabled:u.length===0||n,children:n?"Inserting...":"Insert"})]})]})]})})},_x=({tableName:e})=>{const{closeOverlay:t,isOverlayOpen:r}=je(),{bulkInsertRecords:s,isInserting:n}=ba({tableName:e}),o=(0,f.useRef)(null),[l,i]=(0,f.useState)(""),[c,d]=(0,f.useState)(null),[u,h]=(0,f.useState)([]),[m,p]=(0,f.useState)(null),[b,w]=(0,f.useState)("file"),x=g=>{const v=g.target.files?.[0];v&&(d(v),h([]),p(null))},N=(0,f.useCallback)(()=>{p(null),h([]);try{if(b==="file"&&c){const g=new FileReader;g.onload=v=>{try{const y=v.target?.result,R=is(y);h(R)}catch(y){p(y instanceof Error?y.message:"Failed to parse file")}},g.readAsText(c)}else if(l.trim()){const g=is(l);h(g)}else p(b==="file"?"No file selected":"Input is empty")}catch(g){p(g instanceof Error?g.message:"Failed to format data")}},[l,c,b]),C=async()=>{if(u.length===0){p("No records to insert");return}try{await s(u,{format:"excel",onSuccess:()=>{i(""),d(null),h([]),p(null),t("records.bulk-insert-excel")}})}catch(g){console.error("Error inserting records:",g)}},S=()=>{i(""),d(null),h([]),p(null),t("records.bulk-insert-excel")};return(0,a.jsx)(Ut,{title:`Add data from Excel into: ${e}`,open:r("records.bulk-insert-excel"),onOpenChange:g=>{g||S()},children:(0,a.jsxs)("div",{className:"flex flex-col h-full gap-4",children:[(0,a.jsx)(rt,{variant:"info",title:"Excel Import",message:"Upload an Excel file (.xlsx, .xls) with headers in the first row. Column names should match your table schema."}),(0,a.jsxs)(Bi,{value:b,onValueChange:g=>w(g),children:[(0,a.jsxs)(ya,{className:"grid w-full grid-cols-2",children:[(0,a.jsx)(as,{value:"file",children:"File"}),(0,a.jsx)(as,{value:"text",children:"Text"})]}),(0,a.jsx)(os,{value:"file",className:"flex-1 flex flex-col gap-4",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(me,{htmlFor:"file-input",className:"mb-2 text-sm font-medium text-foreground",children:"Select Excel file"}),(0,a.jsx)("input",{id:"file-input",ref:o,type:"file",accept:".xlsx,.xls",onChange:x,disabled:n,className:"text-sm text-muted-foreground file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 cursor-pointer disabled:opacity-50"})]})}),(0,a.jsx)(os,{value:"text",className:"flex-1 flex flex-col gap-4",children:(0,a.jsxs)("div",{className:"flex-1 flex flex-col",children:[(0,a.jsx)(me,{htmlFor:"text-input",className:"mb-2 text-sm font-medium text-foreground",children:"Data Input"}),(0,a.jsx)(Sr,{id:"text-input",value:l,onChange:g=>{i(g.target.value),h([]),p(null)},placeholder:`column1 column2 column3
|
|
7
|
+
value1 value2 value3
|
|
8
|
+
value4 value5 value6`,className:"flex-1 resize-none font-mono text-sm",disabled:n})]})})]}),m&&(0,a.jsx)(rt,{variant:"error",title:"Parse Error",message:m}),u.length>0&&(0,a.jsx)(rt,{variant:"success",title:"Ready to Insert",message:`${u.length} record${u.length!==1?"s":""} parsed successfully`}),(0,a.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,a.jsx)(B,{variant:"secondary",size:"lg",onClick:N,disabled:b==="file"?!c:!l.trim()||n,children:"Format"}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(un,{asChild:!0,onClick:S,disabled:n,children:(0,a.jsx)(B,{variant:"outline",size:"lg",children:"Close"})}),(0,a.jsx)(B,{type:"button",size:"lg",onClick:C,disabled:u.length===0||n,children:n?"Inserting...":"Insert"})]})]})]})})},Px=({tableName:e})=>{const{closeOverlay:t,isOverlayOpen:r}=je(),{bulkInsertRecords:s,isInserting:n}=ba({tableName:e}),o=(0,f.useRef)(null),[l,i]=(0,f.useState)(""),[c,d]=(0,f.useState)(null),[u,h]=(0,f.useState)([]),[m,p]=(0,f.useState)(null),[b,w]=(0,f.useState)("file"),x=g=>{const v=g.target.files?.[0];v&&(d(v),h([]),p(null))},N=(0,f.useCallback)(()=>{p(null),h([]);try{if(b==="file"&&c){const g=new FileReader;g.onload=v=>{try{const y=v.target?.result,R=is(y);h(R)}catch(y){p(y instanceof Error?y.message:"Failed to parse file")}},g.readAsText(c)}else if(l.trim()){const g=is(l);h(g)}else p(b==="file"?"No file selected":"Input is empty")}catch(g){p(g instanceof Error?g.message:"Failed to format data")}},[l,c,b]),C=async()=>{if(u.length===0){p("No records to insert");return}try{await s(u,{format:"json",onSuccess:()=>{i(""),d(null),h([]),p(null),t("records.bulk-insert-json")}})}catch(g){console.error("Error inserting records:",g)}},S=()=>{i(""),d(null),h([]),p(null),t("records.bulk-insert-json")};return(0,a.jsx)(Ut,{title:`Add data from JSON into: ${e}`,open:r("records.bulk-insert-json"),onOpenChange:g=>{g||S()},children:(0,a.jsxs)("div",{className:"flex flex-col h-full gap-4",children:[(0,a.jsx)(rt,{variant:"info",title:"JSON Import",message:'Enter JSON array or single object. Example: [{"name": "John", "age": 30}, {"name": "Jane", "age": 28}]'}),(0,a.jsxs)(Bi,{value:b,onValueChange:g=>w(g),children:[(0,a.jsxs)(ya,{className:"grid w-full grid-cols-2",children:[(0,a.jsx)(as,{value:"file",children:"File"}),(0,a.jsx)(as,{value:"text",children:"Text"})]}),(0,a.jsx)(os,{value:"file",className:"flex-1 flex flex-col gap-4",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(me,{htmlFor:"file-input",className:"mb-2 text-sm font-medium text-foreground",children:"Select JSON file"}),(0,a.jsx)("input",{id:"file-input",ref:o,type:"file",accept:".json",onChange:x,disabled:n,className:"text-sm text-muted-foreground file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 cursor-pointer disabled:opacity-50"})]})}),(0,a.jsx)(os,{value:"text",className:"flex-1 flex flex-col gap-4",children:(0,a.jsxs)("div",{className:"flex-1 flex flex-col",children:[(0,a.jsx)(me,{htmlFor:"text-input",className:"mb-2 text-sm font-medium text-foreground",children:"Data Input"}),(0,a.jsx)(Sr,{id:"text-input",value:l,onChange:g=>{i(g.target.value),h([]),p(null)},placeholder:'[{"column1": "value1", "column2": "value2"}]',className:"flex-1 resize-none font-mono text-sm",disabled:n})]})})]}),m&&(0,a.jsx)(rt,{variant:"error",title:"Parse Error",message:m}),u.length>0&&(0,a.jsx)(rt,{variant:"success",title:"Ready to Insert",message:`${u.length} record${u.length!==1?"s":""} parsed successfully`}),(0,a.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,a.jsx)(B,{variant:"secondary",size:"lg",onClick:N,disabled:b==="file"?!c:!l.trim()||n,children:"Format"}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(un,{asChild:!0,onClick:S,disabled:n,children:(0,a.jsx)(B,{variant:"outline",size:"lg",children:"Close"})}),(0,a.jsx)(B,{type:"button",size:"lg",onClick:C,disabled:u.length===0||n,children:n?"Inserting...":"Insert"})]})]})]})})},Fx=({tableName:e})=>{const{closeOverlay:t,isOverlayOpen:r}=je(),{bulkInsertRecords:s,isInserting:n}=ba({tableName:e}),[o,l]=(0,f.useState)(""),[i,c]=(0,f.useState)([]),[d,u]=(0,f.useState)(null),[h,m]=(0,f.useState)("auto"),p=(0,f.useCallback)(()=>{u(null),c([]);try{if(!o.trim()){u("Input is empty");return}const N=is(o);c(N)}catch(N){u(N instanceof Error?N.message:"Failed to parse data")}},[o]),b=async()=>{if(i.length===0){u("No records to insert");return}try{await s(i,{onSuccess:()=>{l(""),c([]),u(null)}})}catch(N){console.error("Error inserting records:",N)}},w=()=>{l(""),c([]),u(null),t("records.bulk-insert")},x=()=>{l(""),c([]),u(null)};return(0,a.jsx)(Ut,{title:`Bulk Insert Records into: ${e}`,open:r("records.bulk-insert"),onOpenChange:N=>{N||w()},children:(0,a.jsxs)("div",{className:"flex flex-col h-full gap-4",children:[(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)("button",{onClick:()=>m("auto"),type:"button",className:V("px-3 py-1 text-sm rounded-md transition-colors",h==="auto"?"bg-primary text-primary-foreground font-medium":"bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground"),children:"Auto"}),(0,a.jsx)("button",{onClick:()=>m("csv"),type:"button",className:V("px-3 py-1 text-sm rounded-md transition-colors",h==="csv"?"bg-primary text-primary-foreground font-medium":"bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground"),children:"CSV"}),(0,a.jsx)("button",{onClick:()=>m("json"),type:"button",className:V("px-3 py-1 text-sm rounded-md transition-colors",h==="json"?"bg-primary text-primary-foreground font-medium":"bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground"),children:"JSON"})]}),(0,a.jsx)(rt,{variant:"info",title:"Bulk Insert",message:h==="json"?'Enter JSON array or single object. Example: [{"name": "John", "age": 30}, {"name": "Jane", "age": 28}]':"Enter CSV data with headers. Supports comma, tab, or semicolon delimiters. First row should be column names."}),(0,a.jsxs)("div",{className:"flex-1 flex flex-col",children:[(0,a.jsx)(me,{htmlFor:"text-input",className:"mb-2 text-sm font-medium text-foreground",children:"Data Input"}),(0,a.jsx)(Sr,{id:"text-input",value:o,onChange:N=>{l(N.target.value),c([]),u(null)},placeholder:h==="json"?'[{"column1": "value1", "column2": "value2"}]':`column1,column2,column3
|
|
9
|
+
value1,value2,value3
|
|
10
|
+
value4,value5,value6`,className:"flex-1 resize-none font-mono text-sm"})]}),d&&(0,a.jsx)(rt,{variant:"error",title:"Parse Error",message:d}),i.length>0&&(0,a.jsx)(rt,{variant:"success",title:"Ready to Insert",message:`${i.length} record${i.length!==1?"s":""} parsed successfully`}),(0,a.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(B,{variant:"outline",size:"lg",onClick:x,disabled:!o||n,children:"Clear"}),(0,a.jsx)(B,{variant:"secondary",size:"lg",onClick:p,disabled:!o||n,children:"Preview"})]}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(un,{asChild:!0,onClick:w,disabled:n,children:(0,a.jsx)(B,{variant:"outline",size:"lg",children:"Close"})}),(0,a.jsx)(B,{type:"button",size:"lg",onClick:b,disabled:i.length===0||n,children:n?"Inserting...":"Insert"})]})]})]})})},zr=null,tr=null,xr=Dr()((e,t)=>({isLive:!1,status:"idle",isPulsing:!1,activeTable:null,generation:0,highlightedRowIds:new Set,highlightedCellKeys:new Set,setLive:(r,s)=>{e(r?{isLive:!0,status:"healthy",activeTable:s??t().activeTable,generation:t().generation+1}:{isLive:!1,status:"idle",isPulsing:!1,generation:t().generation+1})},pauseLive:()=>{e({isLive:!1,status:"paused",isPulsing:!1,generation:t().generation+1})},setStatus:r=>{e({status:r})},triggerPulse:()=>{zr&&clearTimeout(zr),e({isPulsing:!0}),zr=setTimeout(()=>{e({isPulsing:!1}),zr=null},800)},setHighlights:(r,s,n=1500)=>{if(r.length===0&&s.length===0){t().clearHighlights();return}tr&&clearTimeout(tr),e({highlightedRowIds:new Set(r),highlightedCellKeys:new Set(s)}),tr=setTimeout(()=>{e({highlightedRowIds:new Set,highlightedCellKeys:new Set}),tr=null},n)},clearHighlights:()=>{tr&&(clearTimeout(tr),tr=null),e({highlightedRowIds:new Set,highlightedCellKeys:new Set})},isRowHighlighted:r=>t().highlightedRowIds.has(r),isCellHighlighted:(r,s)=>t().highlightedCellKeys.has(`${r}:${s}`),reset:()=>{zr&&(clearTimeout(zr),zr=null),tr&&(clearTimeout(tr),tr=null),e({isLive:!1,status:"idle",isPulsing:!1,activeTable:null,generation:t().generation+1,highlightedRowIds:new Set,highlightedCellKeys:new Set})}})),ls=Dr()(e=>({tableName:null,rowIndex:null,isDirty:!1,setRowDetails:(t,r)=>e({tableName:t,rowIndex:r}),selectRowDetails:t=>e({rowIndex:t}),clearRowDetails:()=>e({tableName:null,rowIndex:null,isDirty:!1}),setDirty:t=>e({isDirty:t})})),Wn=e=>{if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Wn).join(",")}]`;const t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${Wn(t[r])}`).join(",")}}`},jn=(e,t,r="global")=>{const s=e.id??e._id??Wn(e);return Wn([r,s,t])},qt=Dr()((e,t)=>({updates:new Map,setUpdate:(r,s,n,o,l)=>{e(i=>{const c=new Map(i.updates),d=jn(r,s,l);return n===o?c.delete(d):c.set(d,{scope:l??"global",rowData:r,columnName:s,newValue:n,originalValue:o}),{updates:c}})},clearUpdates:()=>e({updates:new Map}),clearUpdate:(r,s,n)=>{e(o=>{const l=new Map(o.updates);return l.delete(jn(r,s,n)),{updates:l}})},getUpdates:()=>Array.from(t().updates.values()),getUpdate:(r,s,n)=>{const{updates:o}=t();return o.size===0?null:o.get(jn(r,s,n))??null},hasUpdate:(r,s,n)=>{const{updates:o}=t();return o.size>0&&o.has(jn(r,s,n))},hasAnyUpdates:()=>t().updates.size>0,getUpdateCount:()=>t().updates.size})),ks=e=>{if(e===void 0)return"undefined";if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(ks).join(",")}]`;const t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${ks(t[r])}`).join(",")}}`},Fo=(e,t=[])=>t.length===1?String(e[t[0]]??""):t.length>1?ks(t.map(r=>e[r])):e.id!==void 0&&e.id!==null?String(e.id):e._id!==void 0&&e._id!==null?String(e._id):ks(e),Lx=(e,t)=>e===t?!0:typeof e=="object"&&typeof t=="object"&&e!==null&&t!==null?ks(e)===ks(t):!1,zx=(e,t,r=[])=>{if(!e||!t)return{hasVisibleChanges:!1,insertedRowIds:[],changedCellKeys:[]};const s=e.map(u=>Fo(u,r)),n=t.map(u=>Fo(u,r));let o=!1;(e.length!==t.length||s.some((u,h)=>u!==n[h]))&&(o=!0);const l=new Map;for(let u=0;u<e.length;u++)l.set(s[u],e[u]);const i=new Set(n),c=[],d=[];for(let u=0;u<t.length;u++){const h=n[u],m=t[u],p=l.get(h);if(!p)c.push(h),o=!0;else{const b=new Set([...Object.keys(p),...Object.keys(m)]);for(const w of b)Lx(p[w],m[w])||(d.push(`${h}:${w}`),o=!0)}}for(const u of s)if(!i.has(u)){o=!0;break}return{hasVisibleChanges:o,insertedRowIds:c,changedCellKeys:d}},$x=1e3,Vx=({tableName:e,tableCols:t,tableDataRows:r,refetchTableData:s,isEditingCell:n=!1})=>{const o=_r()?.liveMode??!1,{isLive:l,status:i,isPulsing:c,setLive:d,pauseLive:u,setStatus:h,triggerPulse:m,setHighlights:p,isRowHighlighted:b,isCellHighlighted:w,reset:x}=xr(),{selectedDatabase:N}=Me(),{updates:C}=qt(),{openOverlays:S}=je(),{isDirty:g}=ls(),v=C.size>0,y=S.some(z=>z.startsWith("records.")),R=g&&S.includes("tables.row-details"),I=n||v||y||R,k=(0,f.useMemo)(()=>t?.filter(z=>z.isPrimaryKey).map(z=>z.columnName)??[],[t]),T=(0,f.useRef)(null),D=(0,f.useRef)(s);D.current=s;const _=(0,f.useRef)(!1),O=(0,f.useRef)(e);O.current=e;const F=(0,f.useRef)(N);F.current=N,(0,f.useEffect)(()=>{l&&I&&u()},[l,I,u]),(0,f.useEffect)(()=>{if(l&&T.current!==null){const z=zx(T.current,r,k);z.hasVisibleChanges&&(m(),p(z.insertedRowIds,z.changedCellKeys))}T.current=r},[r,l,k,m,p]);const E=(0,f.useCallback)(async()=>{if(typeof document<"u"&&document.hidden)return;if(I){u();return}if(_.current)return;const z=xr.getState().generation,G=O.current,fe=F.current;_.current=!0;try{const Z=await D.current(),re=xr.getState();if(re.generation!==z||!re.isLive||O.current!==G||F.current!==fe)return;Z&&typeof Z=="object"&&"isError"in Z&&Z.isError?h("disconnected"):h("healthy")}catch{const Z=xr.getState();if(Z.generation!==z||!Z.isLive||O.current!==G||F.current!==fe)return;h("disconnected")}finally{_.current=!1}},[I,u,h]);return(0,f.useEffect)(()=>{if(!l||!o)return;E();const z=setInterval(()=>{E()},$x);return()=>{clearInterval(z)}},[l,o,E]),(0,f.useEffect)(()=>{if(!l||!o)return;const z=()=>{!document.hidden&&l&&E()};return document.addEventListener("visibilitychange",z),()=>{document.removeEventListener("visibilitychange",z)}},[l,o,E]),(0,f.useEffect)(()=>()=>{x()},[e,N,x]),{canLiveMode:o,isLive:l,status:i,isPulsing:c,isRowHighlighted:b,isCellHighlighted:w,toggleLive:(0,f.useCallback)(()=>{o&&(l?d(!1):d(!0,e))},[o,l,e,d])}};function Bx(e){if(!e||typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}var Vu=f.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),Ps=()=>{const e=f.useContext(Vu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};Bx(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
|
|
11
|
+
[data-state=closed]
|
|
12
|
+
){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function Ux(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function qx(){return Ui(/^Mac/)}function Wx(){return Ui(/^iPhone/)}function ec(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Kx(){return Ui(/^iPad/)||qx()&&navigator.maxTouchPoints>1}function Bu(){return Wx()||Kx()}function Ui(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}var Hx=24,Gx=typeof window<"u"?f.useLayoutEffect:f.useEffect;function tc(...e){return(...t)=>{for(let r of e)typeof r=="function"&&r(...t)}}var eo=typeof document<"u"&&window.visualViewport;function rc(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function Uu(e){for(rc(e)&&(e=e.parentElement);e&&!rc(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}var Yx=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]),In=0,sc;function Jx(e={}){let{isDisabled:t}=e;Gx(()=>{if(!t)return In++,In===1&&Bu()&&(sc=Qx()),()=>{In--,In===0&&sc?.()}},[t])}function Qx(){let e,t=0,r=h=>{e=Uu(h.target),!(e===document.documentElement&&e===document.body)&&(t=h.changedTouches[0].pageY)},s=h=>{if(!e||e===document.documentElement||e===document.body){h.preventDefault();return}let m=h.changedTouches[0].pageY,p=e.scrollTop,b=e.scrollHeight-e.clientHeight;b!==0&&((p<=0&&m>t||p>=b&&m<t)&&h.preventDefault(),t=m)},n=h=>{let m=h.target;Lo(m)&&m!==document.activeElement&&(h.preventDefault(),m.style.transform="translateY(-2000px)",m.focus(),requestAnimationFrame(()=>{m.style.transform=""}))},o=h=>{let m=h.target;Lo(m)&&(m.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{m.style.transform="",eo&&(eo.height<window.innerHeight?requestAnimationFrame(()=>{nc(m)}):eo.addEventListener("resize",()=>nc(m),{once:!0}))}))},l=()=>{window.scrollTo(0,0)},i=window.pageXOffset,c=window.pageYOffset,d=tc(Xx(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let u=tc(Ks(document,"touchstart",r,{passive:!1,capture:!0}),Ks(document,"touchmove",s,{passive:!1,capture:!0}),Ks(document,"touchend",n,{passive:!1,capture:!0}),Ks(document,"focus",o,!0),Ks(window,"scroll",l));return()=>{d(),u(),window.scrollTo(i,c)}}function Xx(e,t,r){let s=e.style[t];return e.style[t]=r,()=>{e.style[t]=s}}function Ks(e,t,r,s){return e.addEventListener(t,r,s),()=>{e.removeEventListener(t,r,s)}}function nc(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let r=Uu(e);if(r!==document.documentElement&&r!==document.body&&r!==e){let s=r.getBoundingClientRect().top,n=e.getBoundingClientRect().top;e.getBoundingClientRect().bottom>r.getBoundingClientRect().bottom+Hx&&(r.scrollTop+=n-s)}e=r.parentElement}}function Lo(e){return e instanceof HTMLInputElement&&!Yx.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function Zx(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function eS(...e){return t=>e.forEach(r=>Zx(r,t))}function qu(...e){return f.useCallback(eS(...e),e)}var Wu=new WeakMap;function Xe(e,t,r=!1){if(!e||!(e instanceof HTMLElement))return;let s={};Object.entries(t).forEach(([n,o])=>{if(n.startsWith("--")){e.style.setProperty(n,o);return}s[n]=e.style[n],e.style[n]=o}),!r&&Wu.set(e,s)}function tS(e,t){if(!e||!(e instanceof HTMLElement))return;let r=Wu.get(e);r&&(e.style[t]=r[t])}var We=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function Tn(e,t){if(!e)return null;const r=window.getComputedStyle(e),s=r.transform||r.webkitTransform||r.mozTransform;let n=s.match(/^matrix3d\((.+)\)$/);return n?parseFloat(n[1].split(", ")[We(t)?13:12]):(n=s.match(/^matrix\((.+)\)$/),n?parseFloat(n[1].split(", ")[We(t)?5:4]):null)}function rS(e){return 8*(Math.log(e+1)-2)}function to(e,t){if(!e)return()=>{};const r=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=r}}var ze={DURATION:.5,EASE:[.32,.72,0,1]},Ku=.4,sS=.25,nS=100,Hu=8,Rn=16,zo=26,ro="vaul-dragging";function Gu(e){const t=f.useRef(e);return f.useEffect(()=>{t.current=e}),f.useMemo(()=>(...r)=>t.current==null?void 0:t.current.call(t,...r),[])}function aS({defaultProp:e,onChange:t}){const r=f.useState(e),[s]=r,n=f.useRef(s),o=Gu(t);return f.useEffect(()=>{n.current!==s&&(o(s),n.current=s)},[s,n,o]),r}function Yu({prop:e,defaultProp:t,onChange:r=()=>{}}){const[s,n]=aS({defaultProp:t,onChange:r}),o=e!==void 0,l=o?e:s,i=Gu(r);return[l,f.useCallback(c=>{if(o){const d=typeof c=="function"?c(e):c;d!==e&&i(d)}else n(c)},[o,e,n,i])]}function oS({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:r,drawerRef:s,overlayRef:n,fadeFromIndex:o,onSnapPointChange:l,direction:i="bottom",container:c,snapToSequentialPoint:d}){const[u,h]=Yu({prop:e,defaultProp:r?.[0],onChange:t}),[m,p]=f.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);f.useEffect(()=>{function R(){p({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]);const b=f.useMemo(()=>u===r?.[r.length-1]||null,[r,u]),w=f.useMemo(()=>{var R;return(R=r?.findIndex(I=>I===u))!=null?R:null},[r,u]),x=r&&r.length>0&&(o||o===0)&&!Number.isNaN(o)&&r[o]===u||!r,N=f.useMemo(()=>{const R=c?{width:c.getBoundingClientRect().width,height:c.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var I;return(I=r?.map(k=>{const T=typeof k=="string";let D=0;if(T&&(D=parseInt(k,10)),We(i)){const O=T?D:m?k*R.height:0;return m?i==="bottom"?R.height-O:-R.height+O:O}const _=T?D:m?k*R.width:0;return m?i==="right"?R.width-_:-R.width+_:_}))!=null?I:[]},[r,m,c]),C=f.useMemo(()=>w!==null?N?.[w]:null,[N,w]),S=f.useCallback(R=>{var I;const k=(I=N?.findIndex(T=>T===R))!=null?I:null;l(k),Xe(s.current,{transition:`transform ${ze.DURATION}s cubic-bezier(${ze.EASE.join(",")})`,transform:We(i)?`translate3d(0, ${R}px, 0)`:`translate3d(${R}px, 0, 0)`}),N&&k!==N.length-1&&o!==void 0&&k!==o&&k<o?Xe(n.current,{transition:`opacity ${ze.DURATION}s cubic-bezier(${ze.EASE.join(",")})`,opacity:"0"}):Xe(n.current,{transition:`opacity ${ze.DURATION}s cubic-bezier(${ze.EASE.join(",")})`,opacity:"1"}),h(r?.[Math.max(k,0)])},[s.current,r,N,o,n,h]);f.useEffect(()=>{if(u||e){var R;const I=(R=r?.findIndex(k=>k===e||k===u))!=null?R:-1;N&&I!==-1&&typeof N[I]=="number"&&S(N[I])}},[u,e,r,N,S]);function g({draggedDistance:R,closeDrawer:I,velocity:k,dismissible:T}){if(o===void 0)return;const D=i==="bottom"||i==="right"?(C??0)-R:(C??0)+R,_=w===o-1,O=w===0,F=R>0;if(_&&Xe(n.current,{transition:`opacity ${ze.DURATION}s cubic-bezier(${ze.EASE.join(",")})`}),!d&&k>2&&!F){T?I():S(N[0]);return}if(!d&&k>2&&F&&N&&r){S(N[r.length-1]);return}const E=N?.reduce((G,fe)=>typeof G!="number"||typeof fe!="number"?G:Math.abs(fe-D)<Math.abs(G-D)?fe:G),z=We(i)?window.innerHeight:window.innerWidth;if(k>Ku&&Math.abs(R)<z*.4){const G=F?1:-1;if(G>0&&b&&r){S(N[r.length-1]);return}if(O&&G<0&&T&&I(),w===null)return;S(N[w+G]);return}S(E)}function v({draggedDistance:R}){if(C===null)return;const I=i==="bottom"||i==="right"?C-R:C+R;(i==="bottom"||i==="right")&&I<N[N.length-1]||(i==="top"||i==="left")&&I>N[N.length-1]||Xe(s.current,{transform:We(i)?`translate3d(0, ${I}px, 0)`:`translate3d(${I}px, 0, 0)`})}function y(R,I){if(!r||typeof w!="number"||!N||o===void 0)return null;const k=w===o-1;if(w>=o&&I)return 0;if(k&&!I)return 1;if(!x&&!k)return null;const T=k?w+1:w-1,D=k?N[T]-N[T-1]:N[T+1]-N[T],_=R/Math.abs(D);return k?1-_:_}return{isLastSnapPoint:b,activeSnapPoint:u,shouldFade:x,getPercentageDragged:y,setActiveSnapPoint:h,activeSnapPointIndex:w,onRelease:g,onDrag:v,snapPointsOffset:N}}function iS(){const{direction:e,isOpen:t,shouldScaleBackground:r,setBackgroundColorOnScale:s,noBodyStyles:n}=Ps(),o=f.useRef(null),l=(0,f.useMemo)(()=>document.body.style.backgroundColor,[]);function i(){return(window.innerWidth-zo)/window.innerWidth}f.useEffect(()=>{if(t&&r){o.current&&clearTimeout(o.current);const c=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!c)return;s&&!n&&to(document.body,{background:"black"}),to(c,{transformOrigin:We(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${ze.DURATION}s`,transitionTimingFunction:`cubic-bezier(${ze.EASE.join(",")})`});const d=to(c,{borderRadius:`${Hu}px`,overflow:"hidden",...We(e)?{transform:`scale(${i()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${i()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{d(),o.current=window.setTimeout(()=>{l?document.body.style.background=l:document.body.style.removeProperty("background")},ze.DURATION*1e3)}}},[t,r,l])}var Hs=null;function lS({isOpen:e,modal:t,nested:r,hasBeenOpened:s,preventScrollRestoration:n,noBodyStyles:o}){const[l,i]=f.useState(()=>typeof window<"u"?window.location.href:""),c=f.useRef(0),d=f.useCallback(()=>{if(ec()&&Hs===null&&e&&!o){Hs={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:h,innerHeight:m}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-c.current}px`,left:`${-h}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const p=m-window.innerHeight;p&&c.current>=m&&(document.body.style.top=`${-(c.current+p)}px`)}),300)}},[e]),u=f.useCallback(()=>{if(ec()&&Hs!==null&&!o){const h=-parseInt(document.body.style.top,10),m=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Hs),window.requestAnimationFrame(()=>{if(n&&l!==window.location.href){i(window.location.href);return}window.scrollTo(m,h)}),Hs=null}},[l]);return f.useEffect(()=>{function h(){c.current=window.scrollY}return h(),window.addEventListener("scroll",h),()=>{window.removeEventListener("scroll",h)}},[]),f.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||u()}},[t,u]),f.useEffect(()=>{r||!s||(e?(!window.matchMedia("(display-mode: standalone)").matches&&d(),t||window.setTimeout(()=>{u()},500)):u())},[e,s,l,t,r,d,u]),{restorePositionSetting:u}}function Ju({open:e,onOpenChange:t,children:r,onDrag:s,onRelease:n,snapPoints:o,shouldScaleBackground:l=!1,setBackgroundColorOnScale:i=!0,closeThreshold:c=sS,scrollLockTimeout:d=nS,dismissible:u=!0,handleOnly:h=!1,fadeFromIndex:m=o&&o.length-1,activeSnapPoint:p,setActiveSnapPoint:b,fixed:w,modal:x=!0,onClose:N,nested:C,noBodyStyles:S=!1,direction:g="bottom",defaultOpen:v=!1,disablePreventScroll:y=!0,snapToSequentialPoint:R=!1,preventScrollRestoration:I=!1,repositionInputs:k=!0,onAnimationEnd:T,container:D,autoFocus:_=!1}){var O,F;const[E=!1,z]=Yu({defaultProp:v,prop:e,onChange:se=>{t?.(se),!se&&!C&&M(),setTimeout(()=>{T?.(se)},ze.DURATION*1e3),se&&!x&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),se||(document.body.style.pointerEvents="auto")}}),[G,fe]=f.useState(!1),[Z,re]=f.useState(!1),[Ne,L]=f.useState(!1),$=f.useRef(null),ne=f.useRef(null),ee=f.useRef(null),pe=f.useRef(null),K=f.useRef(null),Ie=f.useRef(!1),Pe=f.useRef(null),pt=f.useRef(0),Ye=f.useRef(!1),st=f.useRef(!v),Zt=f.useRef(0),oe=f.useRef(null),he=f.useRef(((O=oe.current)==null?void 0:O.getBoundingClientRect().height)||0),ie=f.useRef(((F=oe.current)==null?void 0:F.getBoundingClientRect().width)||0),gt=f.useRef(0),{activeSnapPoint:Nt,activeSnapPointIndex:nt,setActiveSnapPoint:er,onRelease:Ue,snapPointsOffset:Kt,onDrag:de,shouldFade:j,getPercentageDragged:A}=oS({snapPoints:o,activeSnapPointProp:p,setActiveSnapPointProp:b,drawerRef:oe,fadeFromIndex:m,overlayRef:$,onSnapPointChange:f.useCallback(se=>{o&&se===Kt.length-1&&(ne.current=new Date)},[]),direction:g,container:D,snapToSequentialPoint:R});Jx({isDisabled:!E||Z||!x||Ne||!G||!k||!y});const{restorePositionSetting:M}=lS({isOpen:E,modal:x,nested:C??!1,hasBeenOpened:G,preventScrollRestoration:I,noBodyStyles:S});function W(){return(window.innerWidth-zo)/window.innerWidth}function H(se){var Se,Y;!u&&!o||oe.current&&!oe.current.contains(se.target)||(he.current=((Se=oe.current)==null?void 0:Se.getBoundingClientRect().height)||0,ie.current=((Y=oe.current)==null?void 0:Y.getBoundingClientRect().width)||0,re(!0),ee.current=new Date,Bu()&&window.addEventListener("touchend",()=>Ie.current=!1,{once:!0}),se.target.setPointerCapture(se.pointerId),pt.current=We(g)?se.pageY:se.pageX)}function U(se,Se){var Y;let Q=se;const te=(Y=window.getSelection())==null?void 0:Y.toString(),ye=oe.current?Tn(oe.current,g):null,le=new Date;if(Q.tagName==="SELECT"||Q.hasAttribute("data-vaul-no-drag")||Q.closest("[data-vaul-no-drag]"))return!1;if(g==="right"||g==="left")return!0;if(ne.current&&le.getTime()-ne.current.getTime()<500)return!1;if(ye!==null&&(g==="bottom"?ye>0:ye<0))return!0;if(te&&te.length>0)return!1;if(K.current&&le.getTime()-K.current.getTime()<d&&ye===0||Se)return K.current=le,!1;for(;Q;){if(Q.scrollHeight>Q.clientHeight){if(Q.scrollTop!==0)return K.current=new Date,!1;if(Q.getAttribute("role")==="dialog")return!0}Q=Q.parentNode}return!0}function J(se){if(oe.current&&Z){const Se=g==="bottom"||g==="right"?1:-1,Y=(pt.current-(We(g)?se.pageY:se.pageX))*Se,Q=Y>0,te=o&&!u&&!Q;if(te&&nt===0)return;const ye=Math.abs(Y),le=document.querySelector("[data-vaul-drawer-wrapper]");let Fe=ye/(g==="bottom"||g==="top"?he.current:ie.current);const ge=A(ye,Q);if(ge!==null&&(Fe=ge),te&&Fe>=1||!Ie.current&&!U(se.target,Q))return;if(oe.current.classList.add(ro),Ie.current=!0,Xe(oe.current,{transition:"none"}),Xe($.current,{transition:"none"}),o&&de({draggedDistance:Y}),Q&&!o){const ut=rS(Y),pr=Math.min(ut*-1,0)*Se;Xe(oe.current,{transform:We(g)?`translate3d(0, ${pr}px, 0)`:`translate3d(${pr}px, 0, 0)`});return}const ps=1-Fe;if((j||m&&nt===m-1)&&(s?.(se,Fe),Xe($.current,{opacity:`${ps}`,transition:"none"},!0)),le&&$.current&&l){const ut=Math.min(W()+Fe*(1-W()),1),pr=8-Fe*8,gs=Math.max(0,14-Fe*14);Xe(le,{borderRadius:`${pr}px`,transform:We(g)?`scale(${ut}) translate3d(0, ${gs}px, 0)`:`scale(${ut}) translate3d(${gs}px, 0, 0)`,transition:"none"},!0)}if(!o){const ut=ye*Se;Xe(oe.current,{transform:We(g)?`translate3d(0, ${ut}px, 0)`:`translate3d(${ut}px, 0, 0)`})}}}f.useEffect(()=>{window.requestAnimationFrame(()=>{st.current=!0})},[]),f.useEffect(()=>{var se;function Se(){if(!oe.current||!k)return;const Y=document.activeElement;if(Lo(Y)||Ye.current){var Q;const te=((Q=window.visualViewport)==null?void 0:Q.height)||0,ye=window.innerHeight;let le=ye-te;const Fe=oe.current.getBoundingClientRect().height||0,ge=Fe>ye*.8;gt.current||(gt.current=Fe);const ps=oe.current.getBoundingClientRect().top;if(Math.abs(Zt.current-le)>60&&(Ye.current=!Ye.current),o&&o.length>0&&Kt&&nt){const ut=Kt[nt]||0;le+=ut}if(Zt.current=le,Fe>te||Ye.current){const ut=oe.current.getBoundingClientRect().height;let pr=ut;ut>te&&(pr=te-(ge?ps:zo)),w?oe.current.style.height=`${ut-Math.max(le,0)}px`:oe.current.style.height=`${Math.max(pr,te-ps)}px`}else Ux()||(oe.current.style.height=`${gt.current}px`);o&&o.length>0&&!Ye.current?oe.current.style.bottom="0px":oe.current.style.bottom=`${Math.max(le,0)}px`}}return(se=window.visualViewport)==null||se.addEventListener("resize",Se),()=>{var Y;return(Y=window.visualViewport)==null?void 0:Y.removeEventListener("resize",Se)}},[nt,o,Kt]);function ae(se){Je(),N?.(),se||z(!1),setTimeout(()=>{o&&er(o[0])},ze.DURATION*1e3)}function xe(){if(!oe.current)return;const se=document.querySelector("[data-vaul-drawer-wrapper]"),Se=Tn(oe.current,g);Xe(oe.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${ze.DURATION}s cubic-bezier(${ze.EASE.join(",")})`}),Xe($.current,{transition:`opacity ${ze.DURATION}s cubic-bezier(${ze.EASE.join(",")})`,opacity:"1"}),l&&Se&&Se>0&&E&&Xe(se,{borderRadius:`${Hu}px`,overflow:"hidden",...We(g)?{transform:`scale(${W()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${W()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${ze.DURATION}s`,transitionTimingFunction:`cubic-bezier(${ze.EASE.join(",")})`},!0)}function Je(){!Z||!oe.current||(oe.current.classList.remove(ro),Ie.current=!1,re(!1),pe.current=new Date)}function vt(se){if(!Z||!oe.current)return;oe.current.classList.remove(ro),Ie.current=!1,re(!1),pe.current=new Date;const Se=Tn(oe.current,g);if(!se||!U(se.target,!1)||!Se||Number.isNaN(Se)||ee.current===null)return;const Y=pe.current.getTime()-ee.current.getTime(),Q=pt.current-(We(g)?se.pageY:se.pageX),te=Math.abs(Q)/Y;if(te>.05&&(L(!0),setTimeout(()=>{L(!1)},200)),o){Ue({draggedDistance:Q*(g==="bottom"||g==="right"?1:-1),closeDrawer:ae,velocity:te,dismissible:u}),n?.(se,!0);return}if(g==="bottom"||g==="right"?Q>0:Q<0){xe(),n?.(se,!0);return}if(te>Ku){ae(),n?.(se,!1);return}var ye;const le=Math.min((ye=oe.current.getBoundingClientRect().height)!=null?ye:0,window.innerHeight);var Fe;const ge=Math.min((Fe=oe.current.getBoundingClientRect().width)!=null?Fe:0,window.innerWidth);if(Math.abs(Se)>=(g==="left"||g==="right"?ge:le)*c){ae(),n?.(se,!1);return}n?.(se,!0),xe()}f.useEffect(()=>(E&&(Xe(document.documentElement,{scrollBehavior:"auto"}),ne.current=new Date),()=>{tS(document.documentElement,"scrollBehavior")}),[E]);function Ze(se){const Se=se?(window.innerWidth-Rn)/window.innerWidth:1,Y=se?-16:0;Pe.current&&window.clearTimeout(Pe.current),Xe(oe.current,{transition:`transform ${ze.DURATION}s cubic-bezier(${ze.EASE.join(",")})`,transform:We(g)?`scale(${Se}) translate3d(0, ${Y}px, 0)`:`scale(${Se}) translate3d(${Y}px, 0, 0)`}),!se&&oe.current&&(Pe.current=setTimeout(()=>{const Q=Tn(oe.current,g);Xe(oe.current,{transition:"none",transform:We(g)?`translate3d(0, ${Q}px, 0)`:`translate3d(${Q}px, 0, 0)`})},500))}function Ls(se,Se){if(Se<0)return;const Y=(window.innerWidth-Rn)/window.innerWidth,Q=Y+Se*(1-Y),te=-16+Se*Rn;Xe(oe.current,{transform:We(g)?`scale(${Q}) translate3d(0, ${te}px, 0)`:`scale(${Q}) translate3d(${te}px, 0, 0)`,transition:"none"})}function wr(se,Se){const Y=We(g)?window.innerHeight:window.innerWidth,Q=Se?(Y-Rn)/Y:1,te=Se?-16:0;Se&&Xe(oe.current,{transition:`transform ${ze.DURATION}s cubic-bezier(${ze.EASE.join(",")})`,transform:We(g)?`scale(${Q}) translate3d(0, ${te}px, 0)`:`scale(${Q}) translate3d(${te}px, 0, 0)`})}return f.useEffect(()=>{x||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[x]),f.createElement(ui,{defaultOpen:v,onOpenChange:se=>{!u&&!se||(se?fe(!0):ae(!0),z(se))},open:E},f.createElement(Vu.Provider,{value:{activeSnapPoint:Nt,snapPoints:o,setActiveSnapPoint:er,drawerRef:oe,overlayRef:$,onOpenChange:t,onPress:H,onRelease:vt,onDrag:J,dismissible:u,shouldAnimate:st,handleOnly:h,isOpen:E,isDragging:Z,shouldFade:j,closeDrawer:ae,onNestedDrag:Ls,onNestedOpenChange:Ze,onNestedRelease:wr,keyboardIsOpen:Ye,modal:x,snapPointsOffset:Kt,activeSnapPointIndex:nt,direction:g,shouldScaleBackground:l,setBackgroundColorOnScale:i,noBodyStyles:S,container:D,autoFocus:_}},r))}var Qu=f.forwardRef(function({...e},t){const{overlayRef:r,snapPoints:s,onRelease:n,shouldFade:o,isOpen:l,modal:i,shouldAnimate:c}=Ps(),d=qu(t,r),u=s&&s.length>0;if(!i)return null;const h=f.useCallback(m=>n(m),[n]);return f.createElement(hi,{onMouseUp:h,ref:d,"data-vaul-overlay":"","data-vaul-snap-points":l&&u?"true":"false","data-vaul-snap-points-overlay":l&&o?"true":"false","data-vaul-animate":c?.current?"true":"false",...e})});Qu.displayName="Drawer.Overlay";var Xu=f.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:r,...s},n){const{drawerRef:o,onPress:l,onRelease:i,onDrag:c,keyboardIsOpen:d,snapPointsOffset:u,activeSnapPointIndex:h,modal:m,isOpen:p,direction:b,snapPoints:w,container:x,handleOnly:N,shouldAnimate:C,autoFocus:S}=Ps(),[g,v]=f.useState(!1),y=qu(n,o),R=f.useRef(null),I=f.useRef(null),k=f.useRef(!1),T=w&&w.length>0;iS();const D=(O,F,E=0)=>{if(k.current)return!0;const z=Math.abs(O.y),G=Math.abs(O.x),fe=G>z,Z=["bottom","right"].includes(F)?1:-1;if(F==="left"||F==="right"){if(!(O.x*Z<0)&&G>=0&&G<=E)return fe}else if(!(O.y*Z<0)&&z>=0&&z<=E)return!fe;return k.current=!0,!0};f.useEffect(()=>{T&&window.requestAnimationFrame(()=>{v(!0)})},[]);function _(O){R.current=null,k.current=!1,i(O)}return f.createElement(mi,{"data-vaul-drawer-direction":b,"data-vaul-drawer":"","data-vaul-delayed-snap-points":g?"true":"false","data-vaul-snap-points":p&&T?"true":"false","data-vaul-custom-container":x?"true":"false","data-vaul-animate":C?.current?"true":"false",...s,ref:y,style:u&&u.length>0?{"--snap-point-height":`${u[h??0]}px`,...t}:t,onPointerDown:O=>{N||(s.onPointerDown==null||s.onPointerDown.call(s,O),R.current={x:O.pageX,y:O.pageY},l(O))},onOpenAutoFocus:O=>{r?.(O),S||O.preventDefault()},onPointerDownOutside:O=>{if(e?.(O),!m||O.defaultPrevented){O.preventDefault();return}d.current&&(d.current=!1)},onFocusOutside:O=>{if(!m){O.preventDefault();return}},onPointerMove:O=>{if(I.current=O,N||(s.onPointerMove==null||s.onPointerMove.call(s,O),!R.current))return;const F=O.pageY-R.current.y,E=O.pageX-R.current.x,z=O.pointerType==="touch"?10:2;D({x:E,y:F},b,z)?c(O):(Math.abs(E)>z||Math.abs(F)>z)&&(R.current=null)},onPointerUp:O=>{s.onPointerUp==null||s.onPointerUp.call(s,O),R.current=null,k.current=!1,i(O)},onPointerOut:O=>{s.onPointerOut==null||s.onPointerOut.call(s,O),_(I.current)},onContextMenu:O=>{s.onContextMenu==null||s.onContextMenu.call(s,O),I.current&&_(I.current)}})});Xu.displayName="Drawer.Content";var cS=250,dS=120,Zu=f.forwardRef(function({preventCycle:e=!1,children:t,...r},s){const{closeDrawer:n,isDragging:o,snapPoints:l,activeSnapPoint:i,setActiveSnapPoint:c,dismissible:d,handleOnly:u,isOpen:h,onPress:m,onDrag:p}=Ps(),b=f.useRef(null),w=f.useRef(!1);function x(){if(w.current){S();return}window.setTimeout(()=>{N()},dS)}function N(){if(o||e||w.current){S();return}if(S(),!l||l.length===0){d||n();return}if(i===l[l.length-1]&&d){n();return}const g=l.findIndex(y=>y===i);if(g===-1)return;const v=l[g+1];c(v)}function C(){b.current=window.setTimeout(()=>{w.current=!0},cS)}function S(){b.current&&window.clearTimeout(b.current),w.current=!1}return f.createElement("div",{onClick:x,onPointerCancel:S,onPointerDown:g=>{u&&m(g),C()},onPointerMove:g=>{u&&p(g)},ref:s,"data-vaul-drawer-visible":h?"true":"false","data-vaul-handle":"","aria-hidden":"true",...r},f.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});Zu.displayName="Drawer.Handle";function uS({onDrag:e,onOpenChange:t,open:r,...s}){const{onNestedDrag:n,onNestedOpenChange:o,onNestedRelease:l}=Ps();if(!n)throw new Error("Drawer.NestedRoot must be placed in another drawer");return f.createElement(Ju,{nested:!0,open:r,onClose:()=>{o(!1)},onDrag:(i,c)=>{n(i,c),e?.(i,c)},onOpenChange:i=>{i&&o(i),t?.(i)},onRelease:l,...s})}function fS(e){const t=Ps(),{container:r=t.container,...s}=e;return f.createElement(pi,{container:r,...s})}var Sn={Root:Ju,NestedRoot:uS,Content:Xu,Overlay:Qu,Trigger:Ap,Portal:fS,Handle:Zu,Close:fi,Title:id,Description:ud};function hS({...e}){return(0,a.jsx)(Sn.Root,{"data-slot":"drawer",...e})}function mS({...e}){return(0,a.jsx)(Sn.Portal,{"data-slot":"drawer-portal",...e})}function pS({className:e,...t}){return(0,a.jsx)(Sn.Overlay,{"data-slot":"drawer-overlay",className:V("fixed inset-0 z-50 bg-black/80 data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",e),...t})}function gS({className:e,children:t,...r}){return(0,a.jsxs)(mS,{"data-slot":"drawer-portal",children:[(0,a.jsx)(pS,{}),(0,a.jsx)(Sn.Content,{"data-slot":"drawer-content",className:V("group/drawer-content fixed z-50 flex h-auto flex-col bg-transparent p-2 text-xs/relaxed text-popover-foreground before:absolute before:inset-2 before:-z-10 before:rounded-xl before:border before:border-border before:bg-popover data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=left]:sm:max-w-sm data-[vaul-drawer-direction=right]:sm:max-w-sm",e),...r,children:(0,a.jsx)(fd.Provider,{value:!0,children:t})})]})}function vS({className:e,...t}){return(0,a.jsx)("div",{"data-slot":"drawer-header",className:V("flex flex-col gap-1 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:text-left",e),...t})}function yS({className:e,...t}){return(0,a.jsx)(Sn.Title,{"data-slot":"drawer-title",className:V("text-sm font-medium text-foreground",e),...t})}var ef=["shift","alt","meta","mod","ctrl","control"];function bS(){return typeof navigator>"u"?!1:/mac/i.test(navigator.userAgent)&&!/iphone|ipad|ipod/i.test(navigator.userAgent)}var xS={esc:"escape",return:"enter",left:"arrowleft",right:"arrowright",up:"arrowup",down:"arrowdown",ShiftLeft:"shift",ShiftRight:"shift",AltLeft:"alt",AltRight:"alt",MetaLeft:"meta",MetaRight:"meta",OSLeft:"meta",OSRight:"meta",ControlLeft:"ctrl",ControlRight:"ctrl"};function Tr(e){return(xS[e.trim()]||e.trim()).toLowerCase().replace(/key|digit|numpad/,"")}function tf(e){return ef.includes(e)}function so(e,t=","){return e.toLowerCase().split(t)}function no(e,t="+",r=">",s=!1,n,o){let l=[],i=!1;e=e.trim(),e.includes(r)?(i=!0,l=e.toLocaleLowerCase().split(r).map(u=>Tr(u))):l=e.toLocaleLowerCase().split(t).map(u=>Tr(u));const c={alt:l.includes("alt"),ctrl:l.includes("ctrl")||l.includes("control"),shift:l.includes("shift"),meta:l.includes("meta"),mod:l.includes("mod"),useKey:s},d=l.filter(u=>!ef.includes(u));return{...c,keys:d,description:n,isSequence:i,hotkey:e,metadata:o}}typeof document<"u"&&(document.addEventListener("keydown",e=>{e.code!==void 0&&rf([Tr(e.code)])}),document.addEventListener("keyup",e=>{e.code!==void 0&&sf([Tr(e.code)])})),typeof window<"u"&&(window.addEventListener("blur",()=>{Jt.clear()}),window.addEventListener("focus",()=>{Jt.clear()}),window.addEventListener("contextmenu",()=>{setTimeout(()=>{Jt.clear()},0)})),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{Jt.clear()});var Jt=new Set;function qi(e){return Array.isArray(e)}function SS(e,t=","){return(qi(e)?e:e.split(t)).every(r=>Jt.has(r.trim().toLowerCase()))}function rf(e){const t=Array.isArray(e)?e:[e];Jt.has("meta")&&Jt.forEach(r=>{tf(r)||Jt.delete(r.toLowerCase())}),t.forEach(r=>{Jt.add(r.toLowerCase())})}function sf(e){e==="meta"?Jt.clear():(Array.isArray(e)?e:[e]).forEach(t=>{Jt.delete(t.toLowerCase())})}function CS(e,t,r){(typeof r=="function"&&r(e,t)||r===!0)&&e.preventDefault()}function wS(e,t,r){return typeof r=="function"?r(e,t):r===!0||r===void 0}var NS=["input","textarea","select","searchbox","slider","spinbutton","menuitem","menuitemcheckbox","menuitemradio","option","radio","textbox"];function jS(e){return nf(e,NS)}function nf(e,t=!1){const{target:r,composed:s}=e;let n,o;return IS(r)&&s?(n=e.composedPath()[0]&&e.composedPath()[0].tagName,o=e.composedPath()[0]&&e.composedPath()[0].role):(n=r&&r.tagName,o=r&&r.role),qi(t)?!!(n&&t?.some(l=>l.toLowerCase()===n.toLowerCase()||l===o)):!!(n&&t&&t)}function IS(e){return!!e.tagName&&!e.tagName.startsWith("-")&&e.tagName.includes("-")}function TS(e,t){return e.length===0&&t?!1:t?e.some(r=>t.includes(r))||e.includes("*"):!0}var RS=(e,t,r=!1)=>{const{alt:s,meta:n,mod:o,shift:l,ctrl:i,keys:c,useKey:d}=t,{code:u,key:h,ctrlKey:m,metaKey:p,shiftKey:b,altKey:w}=e,x=Tr(u);if(d&&c?.length===1&&c.includes(h.toLowerCase()))return!0;if(!c?.includes(x)&&!["ctrl","control","unknown","meta","alt","shift","os"].includes(x))return!1;if(!r){if(s!==w&&x!=="alt"||l!==b&&x!=="shift")return!1;if(o){if(bS()?!p:!m)return!1}else if(n!==p&&x!=="meta"&&x!=="os"||i!==m&&x!=="ctrl"&&x!=="control")return!1}return c&&c.length===1&&c.includes(x)?!0:c&&c.length>0?c.includes(x)?SS(c):!1:!c||c.length===0},ES=(0,f.createContext)(void 0),kS=()=>(0,f.useContext)(ES);function af(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce((r,s)=>r&&af(e[s],t[s]),!0):e===t}var AS=(0,f.createContext)({hotkeys:[],activeScopes:[],toggleScope:()=>{},enableScope:()=>{},disableScope:()=>{}}),OS=()=>(0,f.useContext)(AS);function DS(e){const t=(0,f.useRef)(void 0);return af(t.current,e)||(t.current=e),t.current}var MS=e=>{e.stopPropagation(),e.preventDefault(),e.stopImmediatePropagation()},_S=typeof window<"u"?f.useLayoutEffect:f.useEffect;function PS(e){if(!e)return;const{enabled:t,preventDefault:r,ignoreEventWhen:s,...n}=e;return n}function Ar(e,t,r,s){const[n,o]=(0,f.useState)(null),l=(0,f.useCallback)(S=>(o(S),()=>o(null)),[]),i=(0,f.useRef)(!1),c=Array.isArray(r)?Array.isArray(s)?void 0:s:r,d=qi(e)?e.join(c?.delimiter):e,u=Array.isArray(r)?r:Array.isArray(s)?s:void 0,h=(0,f.useCallback)(t,u??[]),m=(0,f.useRef)(h);u?m.current=h:m.current=t;const p=DS(PS(c)),b=(0,f.useRef)(c?.enabled);b.current=c?.enabled;const w=(0,f.useRef)(c?.preventDefault);w.current=c?.preventDefault;const x=(0,f.useRef)(c?.ignoreEventWhen);x.current=c?.ignoreEventWhen;const{activeScopes:N}=OS(),C=kS();return _S(()=>{if(b.current===!1||!TS(N,p?.scopes))return;let S=[],g;const v=(k,T=!1)=>{if(!(jS(k)&&!nf(k,p?.enableOnFormTags))){if(n!==null){const D=n.getRootNode();if((D instanceof Document||D instanceof ShadowRoot)&&D.activeElement!==n&&!n.contains(D.activeElement)){MS(k);return}}k.target?.isContentEditable&&!p?.enableOnContentEditable||so(d,p?.delimiter).forEach(D=>{if(D.includes(p?.splitKey??"+")&&D.includes(p?.sequenceSplitKey??">")){console.warn(`Hotkey ${D} contains both ${p?.splitKey??"+"} and ${p?.sequenceSplitKey??">"} which is not supported.`);return}const _=no(D,p?.splitKey,p?.sequenceSplitKey,p?.useKey,p?.description,p?.metadata);if(_.isSequence){g=setTimeout(()=>{S=[]},p?.sequenceTimeoutMs??1e3);const O=_.useKey?k.key:Tr(k.code);if(tf(O.toLowerCase()))return;if(S.push(O),O!==_.keys?.[S.length-1]){S=[],g&&clearTimeout(g);return}S.length===_.keys?.length&&(m.current(k,_),g&&clearTimeout(g),S=[])}else if(RS(k,_,p?.ignoreModifiers)||_.keys?.includes("*")){if(x.current?.(k)||T&&i.current||(CS(k,_,w.current),!wS(k,_,b.current)))return;m.current(k,_),T||(i.current=!0)}})}},y=k=>{k.code!==void 0&&(rf(Tr(k.code)),(p?.keydown===void 0&&p?.keyup!==!0||p?.keydown)&&v(k))},R=k=>{k.code!==void 0&&(sf(Tr(k.code)),i.current=!1,p?.keyup&&v(k,!0))},I=n||c?.document||document;return I.addEventListener("keyup",R,c?.eventListenerOptions),I.addEventListener("keydown",y,c?.eventListenerOptions),C&&so(d,p?.delimiter).forEach(k=>{C.addHotkey(no(k,p?.splitKey,p?.sequenceSplitKey,p?.useKey,p?.description,p?.metadata))}),()=>{I.removeEventListener("keyup",R,c?.eventListenerOptions),I.removeEventListener("keydown",y,c?.eventListenerOptions),C&&so(d,p?.delimiter).forEach(k=>{C.removeHotkey(no(k,p?.splitKey,p?.sequenceSplitKey,p?.useKey,p?.description,p?.metadata))}),S=[],g&&clearTimeout(g)}},[n,p,N,d]),l}var FS=({referencedTable:e,referencedColumn:t,fkValue:r})=>{const{selectedDatabase:s}=Me(),{tableCols:n}=mt({tableName:e}),o=(0,f.useMemo)(()=>({columnName:t,operator:"=",value:r}),[t,r]),{data:l,isLoading:i}=Rr({queryKey:["fk-drawer",e,t,r,s],queryFn:async()=>(await Qp.get(`/tables/${e}/data`,{params:{db:s??"",limit:"50",filters:JSON.stringify([o])}})).data.data,enabled:!!e&&!!s&&r!==""}),c=(0,f.useMemo)(()=>n?.map(h=>({accessorKey:h.columnName,header:h.columnName,meta:{variant:h.enumValues?"enum":h.dataType,isPrimaryKey:h.isPrimaryKey,isForeignKey:h.isForeignKey,referencedTable:h.referencedTable,referencedColumn:h.referencedColumn,enumValues:h.enumValues,dataTypeLabel:h.dataTypeLabel},size:(h.columnName.length+(h.dataTypeLabel?.length||0))*5+100,minSize:100,maxSize:500}))??[],[n]),d=rd(),u=()=>{d({to:"/table/$table",params:{table:e},search:{filters:[o]}})};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(vS,{className:"flex flex-row items-center justify-between py-3",children:[(0,a.jsx)(yS,{children:e}),(0,a.jsxs)(B,{variant:"outline",size:"sm",onClick:u,children:[(0,a.jsx)(ip,{size:14}),"Open table"]})]}),(0,a.jsx)("div",{className:"flex flex-1 overflow-hidden border-t",children:i?(0,a.jsx)("div",{className:"flex items-center justify-center w-full text-sm text-muted-foreground",children:(0,a.jsx)(dn,{})}):(0,a.jsx)(eu,{columns:c,data:l?.data??[],renderCellAccessory:h=>(0,a.jsx)(Oi,{value:h})})})]})};function Pr({table:e,cell:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l,className:i,onClick:c,onKeyDown:d,...u}){const{getUpdate:h}=qt(),m=e.options.meta,p=t.row.original,b=!!h(p,s,e.options.meta?.editScope),w=(0,f.useCallback)(I=>{n||(I.preventDefault(),c?.(I),m?.onCellClick?.(r,s,I))},[m,r,s,n,c]),x=(0,f.useCallback)(I=>{n||m?.onCellContextMenu?.(r,s,I)},[m,r,s,n]),N=(0,f.useCallback)(I=>{n||m?.onCellMouseDown?.(r,s,I)},[m,r,s,n]),C=(0,f.useCallback)(I=>{n||m?.onCellMouseEnter?.(r,s,I)},[m,r,s,n]),S=(0,f.useCallback)(()=>{n||m?.onCellMouseUp?.()},[m,n]),g=(0,f.useCallback)(I=>{n||(I.preventDefault(),m?.onCellDoubleClick?.(r,s))},[m,r,s,n]),v=(0,f.useCallback)(I=>{if(d?.(I),!I.defaultPrevented&&!(I.key==="ArrowUp"||I.key==="ArrowDown"||I.key==="ArrowLeft"||I.key==="ArrowRight"||I.key==="Home"||I.key==="End"||I.key==="PageUp"||I.key==="PageDown"||I.key==="Tab")&&o&&!n){if(I.key==="F2"||I.key==="Enter"){I.preventDefault(),I.stopPropagation(),m?.onCellEditingStart?.(r,s);return}if(I.key===" "){I.preventDefault(),I.stopPropagation(),m?.onCellEditingStart?.(r,s);return}I.key.length===1&&!I.ctrlKey&&!I.metaKey&&(I.preventDefault(),I.stopPropagation(),m?.onCellEditingStart?.(r,s))}},[d,o,n,m,r,s]),{highlightedCellKeys:y}=xr(),R=y.has(`${t.row.id}:${s}`);return(0,a.jsx)("div",{role:"button","data-slot":"grid-cell-wrapper","data-editing":n?"":void 0,"data-focused":o?"":void 0,"data-selected":l?"":void 0,"data-has-update":b?"":void 0,tabIndex:o&&!n?0:-1,className:V("size-full px-2 py-1.5 text-left text-sm outline-none has-data-[slot=checkbox]:pt-2.5","**:data-[slot=grid-cell-content]:line-clamp-1",{"ring-1 ring-ring ring-inset":o,"bg-primary/10":l&&!n,"cursor-default":!n,"ring-2 ring-primary":b,"bg-emerald-500/20 dark:bg-emerald-500/25 transition-colors duration-1000 ease-in-out":R},i),onClick:w,onContextMenu:x,onDoubleClick:g,onMouseDown:N,onMouseEnter:C,onMouseUp:S,onKeyDown:v,...u})}var LS=(0,f.lazy)(()=>Ct(()=>import("./json-editor-C9dFqjTV.js").then(e=>({default:e.JsonEditor})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))),Wi=({active:e,open:t,onOpenChange:r,anchor:s,children:n})=>{const[o,l]=(0,f.useState)(e);return e&&!o&&l(!0),o?(0,a.jsxs)(Mr,{open:t,onOpenChange:r,children:[(0,a.jsx)(fg,{asChild:!0,children:s}),n]}):s},Fn=(0,f.memo)(({cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l})=>{const{setUpdate:i,clearUpdate:c,getUpdate:d}=qt(),u=e.getValue(),h=dr(u),[m,p]=(0,f.useState)(()=>h??""),[b,w]=(0,f.useState)(!1),x=(0,f.useRef)(null),N=(0,f.useRef)(null),C=t.options.meta,S=e.row.original,g=s,v=d(S,g,t.options.meta?.editScope),y=v?dr(v.newValue):h??"",R=(0,f.useCallback)(()=>{i(S,g,m,u,t.options.meta?.editScope),C?.onCellEditingStop?.(),w(!1)},[C,m,u,h,g,S,i]),I=(0,f.useCallback)(()=>{p(h??""),c(S,g,t.options.meta?.editScope),C?.onCellEditingStop?.(),w(!1)},[C,h,g,S,c,m]),k=(0,f.useCallback)(E=>{const z=E.target.value;p(z)},[g,m,h]),T=(0,f.useCallback)(E=>{w(E),E||(m!==h&&i(S,g,m,h,t.options.meta?.editScope),C?.onCellEditingStop?.())},[C,m,h,g,S,i]),D=(0,f.useCallback)(E=>{if(E.preventDefault(),x.current){x.current.focus();const z=x.current.value.length;x.current.setSelectionRange(z,z)}},[]),_=(0,f.useCallback)(E=>{n&&!b&&(E.key==="Escape"?(E.preventDefault(),C?.onCellEditingStop?.()):E.key==="Tab"&&(E.preventDefault(),C?.onCellEditingStop?.({direction:E.shiftKey?"left":"right"})))},[n,b,C]),O=(0,f.useCallback)(E=>{E.key==="Escape"?(E.preventDefault(),I()):E.key==="Enter"&&(E.ctrlKey||E.metaKey)&&(E.preventDefault(),R()),E.stopPropagation()},[I,R,m,h]),F=(0,f.useCallback)(()=>{m!==h&&i(S,g,m,h,t.options.meta?.editScope),C?.onCellEditingStop?.(),w(!1)},[C,m,h,g,S,i]);return(0,f.useEffect)(()=>{n&&!b?(p(y),w(!0)):!n&&b&&w(!1)},[n,b,y]),(0,f.useEffect)(()=>{o&&!n&&!C?.isScrolling&&N.current&&N.current.focus()},[o,n,C?.isScrolling]),Ar("enter",()=>R(),{enabled:b}),Ar("esc",()=>I(),{enabled:b}),(0,a.jsx)(Wi,{active:b||n,open:b,onOpenChange:T,anchor:(0,a.jsx)(Pr,{ref:N,cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l,onKeyDown:_,children:(0,a.jsx)("span",{"data-slot":"grid-cell-content",children:y})}),children:(0,a.jsxs)(ur,{"data-grid-cell-editor":"",align:"start",side:"bottom",sideOffset:0,className:"w-[400px] rounded-none p-0 gap-0",onOpenAutoFocus:D,children:[(0,a.jsx)(Sr,{ref:x,value:m,onChange:k,onKeyDown:O,onBlur:F,className:"min-h-[150px] resize-none rounded-none border-0 shadow-none focus-visible:ring-0",placeholder:"Enter text..."}),(0,a.jsxs)("div",{className:"flex flex-col border-t",children:[(0,a.jsxs)(B,{variant:"ghost",size:"sm",className:"rounded-none justify-start text-xs py-4 px-2",children:[(0,a.jsx)(et,{className:"text-xs font-normal",children:"⌘↵"}),(0,a.jsx)("span",{className:"ml-1 text-xs",children:"Save Changes"})]}),(0,a.jsxs)(B,{variant:"ghost",size:"sm",className:"rounded-none justify-start text-xs py-4 px-2",children:[(0,a.jsx)(et,{className:"text-xs font-normal",children:"esc"}),(0,a.jsx)("span",{className:"ml-1 text-xs",children:"Cancel Changes"})]})]})]})})});Fn.displayName="TableTextCell";var of=(0,f.memo)(({cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l})=>{const{setUpdate:i,clearUpdate:c,getUpdate:d}=qt(),u=e.getValue(),h=t.options.meta,m=e.row.original,p=s,b=d(m,p,h?.editScope),w=b?b.newValue:u,[x,N]=(0,f.useState)(w),[C,S]=(0,f.useState)(!1),g=(0,f.useRef)(null);n!==C&&(n&&N(w),S(n));const v=(0,f.useCallback)(()=>{i(m,p,x,u,t.options.meta?.editScope),S(!1),h?.onCellEditingStop?.()},[h,x,u,p,m,i]),y=(0,f.useCallback)(()=>{N(u),c(m,p,t.options.meta?.editScope),S(!1),h?.onCellEditingStop?.()},[h,u,p,m,c,x]),R=(0,f.useCallback)(D=>{const _=D.target.value;N(Number(_)),i(m,p,Number(_),u,t.options.meta?.editScope)},[p,x,u,m,i]),I=(0,f.useCallback)(D=>{D.key==="Escape"?(D.preventDefault(),y()):D.key==="Enter"&&(D.ctrlKey||D.metaKey)&&(D.preventDefault(),v()),D.stopPropagation()},[y,v,x,u]),k=(0,f.useCallback)(()=>{x!==u&&i(m,p,x,u,t.options.meta?.editScope),S(!1),h?.onCellEditingStop?.()},[h,x,u,p,m,i]),T=(0,f.useCallback)(D=>{if(!D)return;D.focus();const _=D.value;D.value="",D.value=_},[]);return(0,f.useEffect)(()=>{o&&!n&&!h?.isScrolling&&g.current&&g.current.focus()},[o,n,h?.isScrolling]),Ar("enter",()=>v(),{enabled:C}),Ar("esc",()=>y(),{enabled:C}),(0,a.jsx)(Pr,{ref:g,cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l,children:C?(0,a.jsx)(Ke,{type:"number",variant:"outline",ref:T,value:x??"",onChange:D=>R(D),onKeyDown:D=>I(D),onBlur:k,className:"size-full rounded-none border-none p-0 shadow-none hover:bg-transparent! focus-visible:ring-0 bg-transparent [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"}):(0,a.jsx)("span",{"data-slot":"grid-cell-content",children:dr(w)})})});of.displayName="TableNumberCell";var lf=(0,f.memo)(({cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l})=>{const{setUpdate:i,clearUpdate:c,getUpdate:d}=qt(),u=e.getValue(),[h,m]=(0,f.useState)(!1),p=(0,f.useRef)(null),b=(0,f.useRef)(null),w=(0,f.useRef)(n),x=t.options.meta;(0,f.useEffect)(()=>{w.current=n},[n]);const N=e.row.original,C=s,S=d(N,C,t.options.meta?.editScope),g=S?S.newValue:u,v=(0,f.useMemo)(()=>g==null?"null":g?"true":"false",[g]),y=(0,f.useCallback)(T=>{let D;T==="null"?D=null:D=T==="true",i(N,C,D,u,t.options.meta?.editScope),m(!1),x?.onCellEditingStop?.()},[C,N,u,i,x]),R=(0,f.useCallback)(()=>{c(N,C,t.options.meta?.editScope),m(!1),x?.onCellEditingStop?.()},[N,C,c,x]),I=(0,f.useCallback)(T=>{m(T),!T&&n&&x?.onCellEditingStop?.()},[n,x]),k=(0,f.useCallback)(T=>{n&&!h&&(T.key==="Escape"?(T.preventDefault(),R()):T.key==="Tab"&&(T.preventDefault(),R(),x?.onCellEditingStop?.({direction:T.shiftKey?"left":"right"})))},[n,h,x,R]);return(0,f.useEffect)(()=>{if(n){const T=setTimeout(()=>{w.current&&(m(!0),setTimeout(()=>{w.current&&b.current?.click()},0))},0);return()=>{clearTimeout(T),m(!1)}}},[n]),(0,f.useEffect)(()=>{o&&!n&&!x?.isScrolling&&p.current&&p.current.focus()},[o,n,x?.isScrolling]),(0,a.jsx)(Pr,{ref:p,cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l,onKeyDown:k,className:"p-0!",children:n?(0,a.jsxs)(dt,{value:v,onValueChange:y,open:h,onOpenChange:I,children:[(0,a.jsx)(lt,{ref:b,variant:"outline",className:"size-full px-2 py-1.5 rounded-none border-none p-0 shadow-none hover:bg-transparent! focus-visible:ring-0 bg-transparent [&_svg]:hidden",children:(0,a.jsx)(it,{})}),(0,a.jsxs)(ct,{"data-grid-cell-editor":"",alignOffset:-8,sideOffset:-8,className:"min-w-[calc(var(--radix-select-trigger-width)+16px)]",onEscapeKeyDown:R,onPointerDownOutside:T=>{T.preventDefault(),m(!1),x?.onCellEditingStop?.()},children:[(0,a.jsx)(ue,{value:"true",children:"true"}),(0,a.jsx)(ue,{value:"false",children:"false"}),(0,a.jsx)(ue,{value:"null",children:"NULL"})]})]}):(0,a.jsx)("span",{className:"flex items-center size-full px-2 py-1.5",children:g==null?"NULL":g?"true":"false"})})});lf.displayName="TableBooleanCell";var cf=(0,f.memo)(({cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l})=>{const{setUpdate:i,clearUpdate:c,getUpdate:d}=qt(),u=e.getValue(),[h,m]=(0,f.useState)(!1),p=(0,f.useRef)(null),b=(0,f.useRef)(null),w=(0,f.useRef)(n),x=t.options.meta,N=e.column.columnDef.meta?.enumValues;(0,f.useEffect)(()=>{w.current=n},[n]);const C=e.row.original,S=s,g=d(C,S,t.options.meta?.editScope),v=g?g.newValue:u,y=(0,f.useCallback)(T=>{i(C,S,T==="null"?null:T,u,t.options.meta?.editScope),m(!1),x?.onCellEditingStop?.()},[S,C,u,i,x]),R=(0,f.useCallback)(()=>{c(C,S,t.options.meta?.editScope),m(!1),x?.onCellEditingStop?.()},[C,S,c,x]),I=(0,f.useCallback)(T=>{m(T),!T&&n&&x?.onCellEditingStop?.()},[n,x]),k=(0,f.useCallback)(T=>{n&&!h&&(T.key==="Escape"?(T.preventDefault(),R()):T.key==="Tab"&&(T.preventDefault(),R(),x?.onCellEditingStop?.({direction:T.shiftKey?"left":"right"})))},[n,h,x,R]);return(0,f.useEffect)(()=>{if(n){const T=setTimeout(()=>{w.current&&(m(!0),setTimeout(()=>{w.current&&b.current?.click()},0))},0);return()=>{clearTimeout(T),m(!1)}}},[n]),(0,f.useEffect)(()=>{o&&!n&&!x?.isScrolling&&p.current&&p.current.focus()},[o,n,x?.isScrolling]),(0,a.jsx)(Pr,{ref:p,cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l,onKeyDown:k,className:"p-0!",children:n?(0,a.jsxs)(dt,{value:v===null?"null":v,onValueChange:y,open:h,onOpenChange:I,children:[(0,a.jsx)(lt,{ref:b,variant:"outline",className:"size-full px-2 py-1.5 rounded-none border-none p-0 shadow-none hover:bg-transparent! focus-visible:ring-0 bg-transparent [&_svg]:hidden",children:(0,a.jsx)(it,{})}),(0,a.jsxs)(ct,{"data-grid-cell-editor":"",alignOffset:-8,sideOffset:-8,className:"min-w-[calc(var(--radix-select-trigger-width)+16px)]",onEscapeKeyDown:R,onPointerDownOutside:T=>{T.preventDefault(),m(!1),x?.onCellEditingStop?.()},children:[N?.map(T=>(0,a.jsx)(ue,{value:T,children:T},T)),(0,a.jsx)(ue,{value:"null",children:"NULL"})]})]}):(0,a.jsx)("span",{className:"flex items-center size-full px-2 py-1.5 truncate",children:v??"NULL"})})});cf.displayName="TableEnumCell";var df=(0,f.memo)(({cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l})=>{const{setUpdate:i,clearUpdate:c,getUpdate:d}=qt(),u=e.getValue(),h=(0,f.useRef)(null),m=t.options.meta,p=e.row.original,b=s,w=d(p,b,t.options.meta?.editScope),x=w?w.newValue:u,N=(0,f.useCallback)(y=>{const R=y?y.toISOString():null;i(p,b,R,u,t.options.meta?.editScope),m?.onCellEditingStop?.()},[b,u,p,i,m]),C=(0,f.useCallback)(()=>{c(p,b,t.options.meta?.editScope),m?.onCellEditingStop?.()},[p,b,c,m,x,u]),S=(0,f.useCallback)(y=>{n&&(y.key==="Escape"||y.key==="Tab")&&(y.preventDefault(),C())},[n,C]),g=(0,f.useCallback)(y=>{y||m?.onCellEditingStop?.()},[m]);(0,f.useEffect)(()=>{o&&!n&&!m?.isScrolling&&h.current&&h.current.focus()},[o,n,m?.isScrolling]);const v=x?new Date(x):void 0;return(0,a.jsx)(Pr,{ref:h,cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l,onKeyDown:S,className:n?"p-0!":void 0,children:n?(0,a.jsx)(Ur,{isFormatted:!1,icon:!1,value:v,onChange:N,open:!0,onOpenChange:g,placeholder:"Pick a date",className:"size-full px-2! py-1.5! rounded-none border-none p-0 text-sm shadow-none hover:bg-transparent! focus-visible:ring-0 bg-transparent dark:bg-transparent! [&_svg]:hidden"}):(0,a.jsx)("span",{"data-slot":"grid-cell-content",className:V(!v&&"text-muted-foreground"),children:v&&!Number.isNaN(v.getTime())?lr(v,"yyyy-MM-dd"):"Pick a date"})})});df.displayName="TableDateCell";var uf=(0,f.memo)(({cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l})=>{const{setUpdate:i,clearUpdate:c,getUpdate:d}=qt(),{editor:u}=fn(),h=e.getValue();let m;if(typeof h=="string")try{m=JSON.parse(h),console.warn(`TableJsonCell ${s}: initialValue was a string, parsed it to object`,m)}catch(E){console.error(`TableJsonCell ${s}: Failed to parse initialValue string`,h,E),m={}}else m=h;const[p,b]=(0,f.useState)(()=>JSON.stringify(m,null,u.tabSize)??""),[w,x]=(0,f.useState)(!1),N=(0,f.useRef)(null),C=t.options.meta,S=e.row.original,g=s,v=d(S,g,t.options.meta?.editScope),y=v?v.newValue:m,R=JSON.stringify(y),I=(0,f.useMemo)(()=>{try{return JSON.parse(p),null}catch(E){return E instanceof Error?E.message:"Invalid JSON"}},[p]),k=(0,f.useCallback)(()=>{let E;try{E=JSON.parse(p)}catch{return!1}return JSON.stringify(E)===JSON.stringify(m)?c(S,g,t.options.meta?.editScope):i(S,g,E,m,t.options.meta?.editScope),!0},[p,m,g,S,i,c]),T=(0,f.useCallback)(()=>{k()&&(C?.onCellEditingStop?.(),x(!1))},[k,C]),D=(0,f.useCallback)(()=>{b(JSON.stringify(m,null,u.tabSize)??""),c(S,g,t.options.meta?.editScope),C?.onCellEditingStop?.(),x(!1)},[C,m,g,S,c,u.tabSize]),_=(0,f.useCallback)(E=>{x(E),E||(k(),C?.onCellEditingStop?.())},[k,C]),O=(0,f.useCallback)(E=>{E.preventDefault()},[]),F=(0,f.useCallback)(E=>{n&&!w&&(E.key==="Escape"?(E.preventDefault(),C?.onCellEditingStop?.()):E.key==="Tab"&&(E.preventDefault(),C?.onCellEditingStop?.({direction:E.shiftKey?"left":"right"})))},[n,w,C]);return(0,f.useEffect)(()=>{n&&!w?(b(JSON.stringify(y,null,u.tabSize)),x(!0)):!n&&w&&x(!1)},[n,w,y]),(0,f.useEffect)(()=>{o&&!n&&!C?.isScrolling&&N.current&&N.current.focus()},[o,n,C?.isScrolling]),Ar("enter",()=>T(),{enabled:w}),Ar("esc",()=>D(),{enabled:w}),(0,a.jsx)(Wi,{active:w||n,open:w,onOpenChange:_,anchor:(0,a.jsx)(Pr,{ref:N,cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l,onKeyDown:F,children:(0,a.jsx)("span",{"data-slot":"grid-cell-content",children:R})}),children:(0,a.jsxs)(ur,{"data-grid-cell-editor":"",align:"start",side:"bottom",sideOffset:0,className:"w-[440px] rounded-none p-0 gap-0",onOpenAutoFocus:O,children:[(0,a.jsx)(f.Suspense,{fallback:(0,a.jsx)("div",{className:"h-[240px]"}),children:(0,a.jsx)(LS,{value:p,onChange:b,onSave:T,onCancel:D,className:"h-[240px]"})}),I&&(0,a.jsx)("p",{className:"border-t px-2 py-1.5 text-xs text-destructive truncate",children:I}),(0,a.jsxs)("div",{className:"flex flex-col border-t",children:[(0,a.jsxs)(B,{variant:"ghost",size:"sm",disabled:!!I,onClick:T,className:"rounded-none justify-start text-xs py-4 px-2",children:[(0,a.jsx)(et,{className:"text-xs font-normal",children:"⌘↵"}),(0,a.jsx)("span",{className:"ml-1 text-xs",children:"Save Changes"})]}),(0,a.jsxs)(B,{variant:"ghost",size:"sm",onClick:D,className:"rounded-none justify-start text-xs py-4 px-2",children:[(0,a.jsx)(et,{className:"text-xs font-normal",children:"esc"}),(0,a.jsx)("span",{className:"ml-1 text-xs",children:"Cancel Changes"})]})]})]})})});uf.displayName="TableJsonCell";var ff=(0,f.memo)(({cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l})=>{const{setUpdate:i,clearUpdate:c,getUpdate:d}=qt(),u=e.getValue(),h=dr(u),[m,p]=(0,f.useState)(()=>h??""),[b,w]=(0,f.useState)(!1),[x,N]=(0,f.useState)(!1),[C,S]=(0,f.useState)(!1);x&&!C&&S(!0);const g=(0,f.useRef)(null),v=(0,f.useRef)(null),y=t.options.meta,R=e.column.columnDef.meta?.referencedTable,I=e.row.original,k=s,T=d(I,k,t.options.meta?.editScope),D=T?dr(T.newValue):h??"",_=(0,f.useCallback)(()=>{i(I,k,m,u,t.options.meta?.editScope),y?.onCellEditingStop?.(),w(!1)},[y,m,u,k,I,i]),O=(0,f.useCallback)(()=>{p(h??""),c(I,k,t.options.meta?.editScope),y?.onCellEditingStop?.(),w(!1)},[y,h,k,I,c]),F=(0,f.useCallback)(re=>{p(re.target.value)},[]),E=(0,f.useCallback)(re=>{w(re),re||(m!==h&&i(I,k,m,h,t.options.meta?.editScope),y?.onCellEditingStop?.())},[y,m,h,k,I,i]),z=(0,f.useCallback)(re=>{if(re.preventDefault(),g.current){g.current.focus();const Ne=g.current.value.length;g.current.setSelectionRange(Ne,Ne)}},[]),G=(0,f.useCallback)(re=>{n&&!b&&(re.key==="Escape"?(re.preventDefault(),y?.onCellEditingStop?.()):re.key==="Tab"&&(re.preventDefault(),y?.onCellEditingStop?.({direction:re.shiftKey?"left":"right"})))},[n,b,y]),fe=(0,f.useCallback)(re=>{re.key==="Escape"?(re.preventDefault(),O()):re.key==="Enter"&&(re.ctrlKey||re.metaKey)&&(re.preventDefault(),_()),re.stopPropagation()},[O,_]),Z=(0,f.useCallback)(()=>{m!==h&&i(I,k,m,h,t.options.meta?.editScope),y?.onCellEditingStop?.(),w(!1)},[y,m,h,k,I,i]);return(0,f.useEffect)(()=>{n&&!b?(p(D),w(!0)):!n&&b&&w(!1)},[n,b,D]),(0,f.useEffect)(()=>{o&&!n&&!y?.isScrolling&&v.current&&v.current.focus()},[o,n,y?.isScrolling]),(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(Wi,{active:b||n,open:b,onOpenChange:E,anchor:(0,a.jsx)(Pr,{ref:v,cell:e,table:t,rowIndex:r,columnId:s,isEditing:n,isFocused:o,isSelected:l,onKeyDown:G,children:D!==""&&(0,a.jsxs)("span",{className:"flex items-center gap-1.5 size-full overflow-hidden",children:[R&&(0,a.jsx)(Is,{variant:"outline",className:"shrink-0 cursor-pointer hover:bg-muted",onClick:re=>{re.stopPropagation(),N(!0)},children:R}),(0,a.jsx)("span",{className:"truncate text-muted-foreground",children:D})]})}),children:(0,a.jsxs)(ur,{"data-grid-cell-editor":"",align:"start",side:"bottom",sideOffset:0,className:"w-[400px] rounded-none p-0 gap-0",onOpenAutoFocus:z,children:[(0,a.jsx)(Sr,{ref:g,value:m,onChange:F,onKeyDown:fe,onBlur:Z,className:"min-h-[150px] resize-none rounded-none border-0 shadow-none focus-visible:ring-0",placeholder:"Enter value..."}),(0,a.jsxs)("div",{className:"flex flex-col border-t",children:[(0,a.jsxs)(B,{variant:"ghost",size:"sm",className:"rounded-none justify-start text-xs py-4 px-2",children:[(0,a.jsx)(et,{className:"text-xs font-normal",children:"⌘↵"}),(0,a.jsx)("span",{className:"ml-1 text-xs",children:"Save Changes"})]}),(0,a.jsxs)(B,{variant:"ghost",size:"sm",className:"rounded-none justify-start text-xs py-4 px-2",children:[(0,a.jsx)(et,{className:"text-xs font-normal",children:"esc"}),(0,a.jsx)("span",{className:"ml-1 text-xs",children:"Cancel Changes"})]})]})]})}),C&&(0,a.jsx)(hS,{open:x,onOpenChange:N,children:(0,a.jsx)(gS,{className:"h-[70vh]",children:R&&(0,a.jsx)(FS,{referencedTable:R,referencedColumn:e.column.columnDef.meta?.referencedColumn??"id",fkValue:D})})})]})});ff.displayName="TableForeignKeyCell";var zS=({cell:e,table:t})=>{const r=t.options.meta,s=t.getRowModel().rows,n=(0,f.useMemo)(()=>{const m=s.findIndex(p=>p.original===e.row.original);return m>=0?m:e.row.index},[s,e.row.original,e.row.index]),o=e.column.id,l=r?.focusedCell?.rowIndex===n&&r?.focusedCell?.columnId===o,i=r?.editingCell?.rowIndex===n&&r?.editingCell?.columnId===o,c=r?.getIsCellSelected?.(n,o)??!1,d=e.column.columnDef.meta?.variant,u=e.column.columnDef.meta?.isForeignKey,h=e.column.columnDef.meta?.referencedTable;if(r?.canMutateRows===!1){const m=e.getValue();return(0,a.jsx)(Pr,{cell:e,table:t,rowIndex:n,columnId:o,isEditing:!1,isFocused:l,isSelected:c,"aria-readonly":"true",title:r.rowMutationReason,className:"pr-7",children:(0,a.jsx)("span",{"data-slot":"grid-cell-content",children:dr(m)})})}if(u&&h)return(0,a.jsx)(ff,{cell:e,table:t,rowIndex:n,columnId:o,isEditing:i,isFocused:l,isSelected:c});switch(d){case"text":return(0,a.jsx)(Fn,{cell:e,table:t,rowIndex:n,columnId:o,isEditing:i,isFocused:l,isSelected:c});case"boolean":return(0,a.jsx)(lf,{cell:e,table:t,rowIndex:n,columnId:o,isEditing:i,isFocused:l,isSelected:c});case"number":return(0,a.jsx)(of,{cell:e,table:t,rowIndex:n,columnId:o,isEditing:i,isFocused:l,isSelected:c});case"enum":return(0,a.jsx)(cf,{cell:e,table:t,rowIndex:n,columnId:o,isEditing:i,isFocused:l,isSelected:c});case"date":return(0,a.jsx)(df,{cell:e,table:t,rowIndex:n,columnId:o,isEditing:i,isFocused:l,isSelected:c});case"json":return(0,a.jsx)(uf,{cell:e,table:t,rowIndex:n,columnId:o,isEditing:i,isFocused:l,isSelected:c});case"array":return(0,a.jsx)(Fn,{cell:e,table:t,rowIndex:n,columnId:o,isEditing:i,isFocused:l,isSelected:c});default:return(0,a.jsx)(Fn,{cell:e,table:t,rowIndex:n,columnId:o,isEditing:i,isFocused:l,isSelected:c})}},$S=()=>({id:"select",accessorKey:"select",header:({table:e})=>(0,a.jsx)("div",{className:"w-full h-full flex items-center justify-center",children:(0,a.jsx)(kr,{checked:e.getIsAllRowsSelected(),onCheckedChange:()=>e.toggleAllRowsSelected()})}),cell:({row:e})=>(0,a.jsx)("div",{className:"w-full h-full flex items-center justify-center",children:(0,a.jsx)(kr,{checked:e.getIsSelected(),onCheckedChange:()=>e.toggleSelected()})}),size:20,enableSorting:!1}),hf={order:[],hidden:[]},ac=(e,t)=>e.order.length===t.order.length&&e.hidden.length===t.hidden.length&&e.order.every((r,s)=>r===t.order[s])&&e.hidden.every((r,s)=>r===t.hidden[s]),Kn=({dbType:e,database:t,tableName:r})=>JSON.stringify([e,t,r]),mf=e=>{const t=e??{};return{order:Array.isArray(t.order)?t.order.filter(r=>typeof r=="string"):[],hidden:Array.isArray(t.hidden)?t.hidden.filter(r=>typeof r=="string"):[]}},VS=e=>!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,mf(r)])),pf=Dr()(Cd(e=>({prefsByTable:{},setColumnPrefs:(t,r)=>e(s=>({prefsByTable:{...s.prefsByTable,[Kn(t)]:mf(r)}})),clearColumnPrefs:t=>e(r=>{const{[Kn(t)]:s,...n}=r.prefsByTable;return{prefsByTable:n}})}),{name:"dbstudio-column-preferences",partialize:e=>({prefsByTable:e.prefsByTable}),merge:(e,t)=>({...t,prefsByTable:VS(e?.prefsByTable)})})),ao=e=>pf.getState().prefsByTable[Kn(e)]??hf,en=(e,t)=>{const r=new Set(e),s=new Set,n=[];for(const o of t.order)r.has(o)&&!s.has(o)&&(n.push(o),s.add(o));for(const o of e)s.has(o)||(n.push(o),s.add(o));return{order:n,hidden:t.hidden.filter(o=>r.has(o)&&typeof o=="string")}},BS=(e,t)=>{const{order:r,hidden:s}=en(e,t),n=new Set(s);return[...r.filter(o=>!n.has(o))].sort((o,l)=>r.indexOf(o)-r.indexOf(l))},$o=(e,t,r,s)=>{if(t===r)return e;const n=e.indexOf(t),o=e.indexOf(r);if(n===-1||o===-1)return e;const l=[...e];l.splice(n,1);const i=l.indexOf(r),c=(s??(n<o?"after":"before"))==="after"?i+1:i;return l.splice(c,0,t),l},gf=({tableName:e,tableCols:t})=>{const{dbType:r,selectedDatabase:s}=Me(),{prefsByTable:n,setColumnPrefs:o,clearColumnPrefs:l}=pf(),i=(0,f.useMemo)(()=>(t??[]).map(S=>S.columnName),[t]),c=(0,f.useMemo)(()=>i.join(`
|
|
13
|
+
`),[i]),d=(0,f.useMemo)(()=>({dbType:r??"",database:s??"",tableName:e}),[r,s,e]),u=n[Kn(d)]??hf,h=(0,f.useRef)(i);(0,f.useLayoutEffect)(()=>{h.current=i},[i]),(0,f.useEffect)(()=>{if(c.length===0)return;const S=ao(d),g=en(h.current,S);ac(S,g)||o(d,g)},[d,c,o]);const m=(0,f.useCallback)(S=>{const g=en(h.current,S);ac(ao(d),g)||o(d,g)},[d,o]),p=(0,f.useCallback)(()=>en(h.current,ao(d)),[d]),b=(0,f.useCallback)(S=>{const g=p(),v=new Set(g.hidden);v.has(S)?v.delete(S):v.add(S),m({...g,hidden:[...v]})},[p,m]),w=(0,f.useCallback)((S,g,v)=>{const y=p(),R=v??y.order,I=R.indexOf(S),k=I+g;if(I===-1||k<0||k>=R.length)return;const T=R[k],D=$o(y.order,S,T,g===-1?"before":"after");m({...y,order:D})},[p,m]),x=(0,f.useCallback)((S,g,v)=>{const y=p(),R=$o(y.order,S,g,v);m({...y,order:R})},[p,m]),N=(0,f.useCallback)(()=>{const S=p();m({...S,hidden:[]})},[p,m]),C=(0,f.useCallback)(()=>{l(d)},[d,l]);return{orderedColumns:(0,f.useMemo)(()=>en(i,u).order,[i,u]),visibleColumns:(0,f.useMemo)(()=>BS(i,u),[i,u]),toggleColumn:b,moveColumn:w,reorderColumn:x,showAllColumns:N,resetColumns:C}},Ki=()=>{const e=_r();return{canMutateRows:e?.rowMutation??!0,rowMutationReason:e?.rowMutation===!1?e.rowMutationReason:void 0}},US=({tableName:e,tableCols:t,tableDataRows:r,isRowHighlighted:s,isCellHighlighted:n})=>{const[o]=ve(ce.COLUMN_NAME),[l]=ve(ce.TABLE_STATE_KEYS.ORDER),{canMutateRows:i,rowMutationReason:c}=Ki(),[d,u]=(0,f.useState)({}),[h,m]=(0,f.useState)({}),[p,b]=(0,f.useState)(null),[w,x]=(0,f.useState)(null),{visibleColumns:N}=gf({tableName:e,tableCols:t}),C=(0,f.useMemo)(()=>{if(!t)return;const z=new Map(t.map(G=>[G.columnName,G]));return N.map(G=>z.get(G)).filter(G=>!!G)},[t,N]),S=(0,f.useMemo)(()=>$S(),[]),g=(0,f.useMemo)(()=>[S,...C?.map(z=>({accessorKey:z.columnName,header:z.columnName,meta:{variant:z.enumValues?"enum":z.dataType,isPrimaryKey:z.isPrimaryKey,isForeignKey:z.isForeignKey,referencedTable:z.referencedTable,referencedColumn:z.referencedColumn,enumValues:z.enumValues,dataTypeLabel:z.dataTypeLabel},size:(z.columnName.length+(z.dataTypeLabel?.length||0))*5+100,minSize:100,maxSize:500}))||[]],[C,S]);(0,f.useEffect)(()=>{u({})},[e]),(0,f.useEffect)(()=>{i||x(null)},[i]);const v=(0,f.useMemo)(()=>o&&l?[{id:o,desc:l==="desc"}]:[],[o,l]),y=(0,f.useCallback)((z,G)=>{b({rowIndex:z,columnId:G})},[]),R=(0,f.useCallback)((z,G)=>{i&&x({rowIndex:z,columnId:G})},[i]),I=(0,f.useCallback)((z,G)=>{i&&x({rowIndex:z,columnId:G})},[i]),k=(0,f.useCallback)(()=>{x(null)},[]),T=(0,f.useCallback)(()=>{},[]),D=(0,f.useCallback)(()=>!1,[]),_=(0,f.useMemo)(()=>t?.filter(z=>z.isPrimaryKey).map(z=>z.columnName)??[],[t]),O=(0,f.useCallback)(z=>Fo(z,_),[_]),F=(0,f.useMemo)(()=>({editScope:e,canMutateRows:i,rowMutationReason:c,focusedCell:p,editingCell:w,onCellClick:y,onCellDoubleClick:R,onCellEditingStart:I,onCellEditingStop:k,onDataUpdate:T,getIsCellSelected:D,isRowHighlighted:s??(z=>xr.getState().isRowHighlighted(z)),isCellHighlighted:n??((z,G)=>xr.getState().isCellHighlighted(z,G))}),[e,i,c,p,w,y,R,I,k,T,D,s,n]),E=si({data:r,columns:g,defaultColumn:{cell:zS,size:50,minSize:100,maxSize:500},getRowId:O,getCoreRowModel:ri(),getSortedRowModel:Rm(),state:{sorting:v,rowSelection:d,columnSizing:h},manualSorting:!1,enableRowSelection:!0,enableMultiRowSelection:!0,enableColumnResizing:!0,columnResizeMode:"onChange",onRowSelectionChange:u,onColumnSizingChange:m,meta:F});return{table:E,selectedRows:E.getSelectedRowModel().rows,setRowSelection:u,isEditingCell:!!w}},vf=({tableName:e})=>{const t=St(),{tableCols:r}=mt({tableName:e}),{selectedDatabase:s,dbType:n}=Me(),{mutateAsync:o,isPending:l,reset:i,error:c}=ht({mutationFn:async({rowData:h,force:m=!1})=>{if(!e)throw new Error("No active table selected");if(!r||r.length===0)throw new Error("No table columns found");return await qS(e,r,h,m,s||void 0)},onSuccess:async h=>(await Promise.all([t.invalidateQueries({queryKey:Ee.dataByTable(e),exact:!1}),t.invalidateQueries({queryKey:Ee.lists()})]),n&&cr.capture("record_deleted",{db_type:n}),h)});return{deleteCells:async h=>{const m=o({rowData:h,force:!1});return we.promise(m,{loading:"Deleting records...",success:p=>`Deleted ${p.deletedCount} records from "${e}"`,error:p=>p.message||"Failed to delete records"}),m},forceDeleteCells:async h=>{const m=o({rowData:h,force:!0});return we.promise(m,{loading:"Deleting records...",success:p=>`Deleted ${p.deletedCount} records from "${e}"`,error:p=>p.message||"Failed to delete records"}),m},isDeletingCells:l,resetDeleteResult:i,deleteCellsError:c}},qS=async(e,t,r,s,n)=>{const o=t.find(i=>i.isPrimaryKey);if(!o)throw new Error("No primary key found for this table");const l={tableName:e,primaryKeys:r.map(i=>({columnName:o.columnName,value:i[o.columnName]}))};try{const i=await Lp({...l,force:s,db:n});return{deletedCount:i.data.data.deletedCount,fkViolation:i.data.data.fkViolation,relatedRecords:i.data.data.relatedRecords}}catch(i){const c=i;if(c.response?.status===409)return{deletedCount:c.response.data.deletedCount};throw i}},WS=["nextval(","next_value","auto_increment","autoincrement","identity","uuid_generate","gen_random_uuid","newid(","newsequentialid("],KS=e=>{const t=e.columnDefault?.toLowerCase()??"";return WS.some(r=>t.includes(r))},Hi=e=>e?.filter(t=>t.isPrimaryKey)??[],HS=e=>Hi(e)[0],yf=e=>{const t=Hi(e);if(t.length>0)return t.map(s=>s.columnName);const r=e?.find(s=>s.columnName==="id");return r?[r.columnName]:[]},GS=(e,t)=>{if(!e||!t)return;const r=t.filter(n=>n.isPrimaryKey);if(r.length>0)return JSON.stringify(r.map(n=>[n.columnName,String(e[n.columnName])]));const s=t.find(n=>n.columnName==="id");if(s&&e[s.columnName]!==void 0&&e[s.columnName]!==null)return JSON.stringify([s.columnName,String(e[s.columnName])])},oo=(e,t)=>{const r={};if(!e||!t)return r;for(const s of t){const n=e[s.columnName];if(n==null)r[s.columnName]="";else if(typeof n=="boolean")r[s.columnName]=n?"true":"false";else if(typeof n=="object")try{r[s.columnName]=JSON.stringify(n)}catch{r[s.columnName]=String(n)}else r[s.columnName]=String(n)}return r},YS=(e,t)=>Object.keys(e).filter(r=>e[r]).map(r=>({columnName:r,value:t[r]??""})),JS=async e=>{await navigator.clipboard.writeText(e)},QS=({tableName:e,tableCols:t,row:r,rowIndex:s})=>{const{setDirty:n}=ls(),o=(0,f.useMemo)(()=>HS(t),[t]),l=(0,f.useMemo)(()=>Hi(t),[t]),i=(0,f.useMemo)(()=>yf(t),[t]),c=(0,f.useMemo)(()=>JSON.stringify((t??[]).map(C=>C.columnName)),[t]),d=Ms({defaultValues:(0,f.useMemo)(()=>oo(r,t),[r,t])}),{formState:u}=d,h=u.isDirty;(0,f.useEffect)(()=>{n(h)},[h,n]);const m=l.some(C=>!!u.dirtyFields[C.columnName]),p=(0,f.useRef)(void 0),b=(0,f.useRef)(void 0),w=(0,f.useRef)(null),x=(0,f.useRef)(null),N=(0,f.useRef)(c);return(0,f.useEffect)(()=>{const C=GS(r,t);if(!(e===x.current&&s===w.current&&c===N.current)){x.current=e,w.current=s,N.current=c,p.current=r,b.current=C,d.reset(oo(r,t));return}if(r===p.current)return;p.current=r;const S=oo(r,t);if(!h){b.current=C,d.reset(S);return}C!==void 0&&b.current!==void 0&&C===b.current?d.reset(S,{keepDirtyValues:!0}):(b.current=C,d.reset(S))},[r,t,e,s,c,d,h]),{methods:d,isDirty:h,pkDirty:m,primaryKeyColumn:o,identityColumnNames:i}},XS=({tableName:e})=>{const t=St(),{selectedDatabase:r,dbType:s}=Me(),{mutateAsync:n,isPending:o}=ht({mutationFn:async({rowData:i,updates:c,primaryKey:d,primaryKeys:u})=>{if(!e)throw new Error("No table selected");if(c.length===0)throw new Error("At least one field is required");return(await pd({tableName:e,updates:c.map(h=>({rowData:i,...h})),...d?{primaryKey:d}:{},...u?.length?{primaryKeys:u}:{},db:r})).data.data},onSuccess:async()=>{await Promise.all([t.invalidateQueries({queryKey:Ee.dataByTable(e),exact:!1}),t.invalidateQueries({queryKey:Ee.lists()})]),s&&cr.capture("record_updated",{db_type:s})}});return{updateRecord:async({rowData:i,updates:c,primaryKey:d,primaryKeys:u})=>{if(c.length===0)throw new Error("At least one field is required");return we.promise(n({rowData:i,updates:c,primaryKey:d,primaryKeys:u}),{loading:"Saving changes...",success:h=>h||"Record updated successfully",error:h=>h.message||"Failed to update record"}).unwrap()},isUpdatingRecord:o}},ZS=({value:e})=>{const[t,r]=(0,f.useState)(!1);return(0,f.useEffect)(()=>{if(!t)return;const s=window.setTimeout(()=>r(!1),1200);return()=>window.clearTimeout(s)},[t]),e?(0,a.jsx)("button",{type:"button","aria-label":t?"Copied":"Copy value",className:"inline-flex size-7 shrink-0 items-center justify-center rounded-md border border-input bg-background text-muted-foreground transition-colors hover:text-foreground",onClick:()=>{JS(e).then(()=>r(!0)).catch(()=>{})},children:t?(0,a.jsx)(Os,{className:"size-3.5"}):(0,a.jsx)(ni,{className:"size-3.5"})}):null},eC=({column:e,displayValue:t,readOnly:r})=>{const{watch:s,formState:n}=Ge(),o=s(e.columnName)??"",l=!!n.dirtyFields[e.columnName];return(0,a.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,a.jsxs)("div",{className:"col-span-1 flex flex-col gap-1",children:[(0,a.jsxs)("span",{className:"text-sm font-medium",children:[e.columnName,l&&(0,a.jsx)("span",{className:"ml-1.5 inline-block size-1.5 rounded-full bg-primary",children:(0,a.jsx)("span",{className:"sr-only",children:"(modified)"})})]}),(0,a.jsxs)("span",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.dataTypeLabel,e.isPrimaryKey&&(0,a.jsx)("span",{className:"rounded border border-border bg-muted px-1 font-mono text-[10px]",children:"PK"})]})]}),(0,a.jsxs)("div",{className:"col-span-2 flex w-full items-start gap-2",children:[(0,a.jsx)("div",{className:"min-w-0 flex-1",children:r?(0,a.jsx)("div",{role:"group","aria-label":e.columnName,className:"break-all rounded-md border border-input bg-muted/40 px-3 py-2 text-sm",children:t||(0,a.jsx)("span",{className:"text-muted-foreground",children:"NULL"})}):(0,a.jsx)(zu,{...e,hideLabel:!0})}),(0,a.jsx)(ZS,{value:r?t:dr(o)})]})]})},tC=({tableName:e,rows:t})=>{const{openOverlay:r,closeOverlay:s,isOverlayOpen:n}=je(),{rowIndex:o,selectRowDetails:l,clearRowDetails:i}=ls(),{tableCols:c,isLoadingTableCols:d}=mt({tableName:e}),{canMutateRows:u,rowMutationReason:h}=Ki(),{updateRecord:m,isUpdatingRecord:p}=XS({tableName:e}),{deleteCells:b,isDeletingCells:w}=vf({tableName:e}),[x,N]=(0,f.useState)(null),[C,S]=(0,f.useState)(null),g=K=>{N(K),r("tables.row-discard-changes")},v=()=>{N(null),s("tables.row-discard-changes")},y=n("tables.row-details")&&o!==null,R=o===null?void 0:t[o],I=p||w,{methods:k,isDirty:T,pkDirty:D,primaryKeyColumn:_,identityColumnNames:O}=QS({tableName:e,tableCols:c,row:R,rowIndex:o}),{formState:F,reset:E,handleSubmit:z}=k;(0,f.useEffect)(()=>{y&&o!==null&&!t[o]&&(T?g("close"):(i(),s("tables.row-details")))},[y,o,t,T,i,s]);const G=()=>{i(),s("tables.row-change-primary-key"),s("tables.row-delete-record"),s("tables.row-discard-changes"),s("tables.row-details")},fe=()=>{I||(T?g("close"):G())},Z=K=>{I||K===o||K<0||K>=t.length||(T?g(K):l(K))},re=()=>{I||!u||(T?g("delete"):r("tables.row-delete-record"))},Ne=()=>{const K=x;v(),K==="close"?G():K==="delete"?r("tables.row-delete-record"):typeof K=="number"&&l(K)},L=async K=>{if(!R||!u)return;const Ie=YS(F.dirtyFields,K);if(Ie.length!==0)try{await m({rowData:R,updates:Ie,primaryKey:O[0],primaryKeys:O}),E(K),G()}catch{}},$=K=>{if(u){if(D){S(K),r("tables.row-change-primary-key");return}L(K)}},ne=async()=>{if(!(!R||!u)){s("tables.row-delete-record");try{(await b([R])).deletedCount>0&&G()}catch{}}},ee=o!==null&&o>0,pe=o!==null&&o<t.length-1;return Ar("up, down",K=>{o!==null&&(K.preventDefault(),Z(K.key==="ArrowUp"?o-1:o+1))},{enabled:y&&!I},[y,I,o,t.length,T]),(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(Ut,{title:"Row details",description:o!==null?`${e} · Row ${o+1} of ${t.length}`:e,cta:(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.jsx)(B,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"Previous row",disabled:!ee||I,onClick:()=>o!==null&&Z(o-1),children:(0,a.jsx)(ii,{className:"size-4"})}),(0,a.jsx)(B,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"Next row",disabled:!pe||I,onClick:()=>o!==null&&Z(o+1),children:(0,a.jsx)(us,{className:"size-4"})})]}),closeButton:!1,modal:!1,onFocusOutside:K=>K.preventDefault(),onPointerDownOutside:K=>{K.target?.closest("table, [role=alertdialog]")&&K.preventDefault()},open:y,onOpenChange:K=>{K||fe()},children:c&&c.length>0&&R?(0,a.jsxs)(Ds,{...k,children:[(0,a.jsxs)("form",{onSubmit:z($),className:"flex flex-col h-full",children:[(0,a.jsxs)("div",{className:"space-y-6",children:[h&&(0,a.jsx)(rt,{variant:"info",title:"Row editing unavailable",message:h}),c.map(K=>(0,a.jsx)(eC,{column:K,displayValue:dr(R[K.columnName]),readOnly:!u||KS(K)},K.columnName))]}),(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2 py-6",children:[(0,a.jsxs)(B,{type:"button",variant:"destructive",size:"lg",disabled:I||!u||!_,title:h??(_?void 0:"Records in tables without a primary key can't be deleted"),onClick:re,children:[(0,a.jsx)(li,{className:"size-4"}),"Delete"]}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(B,{type:"button",variant:"outline",size:"lg",disabled:I,onClick:fe,children:"Close"}),(0,a.jsx)(B,{type:"submit",size:"lg",disabled:I||!u||!T||O.length===0,title:h??(O.length>0?void 0:"Saving needs a primary key or an id column to address the record"),children:"Save changes"})]})]})]}),(0,a.jsx)($u,{})]}):(0,a.jsx)("div",{className:"flex flex-col h-full",children:(0,a.jsx)("div",{className:"space-y-6",children:d?(0,a.jsx)("p",{className:"text-sm text-muted-foreground",children:"Loading row details..."}):(0,a.jsx)(rt,{variant:"info",title:"No columns found",message:"Please add at least one column to the table before viewing records."})})})}),(0,a.jsx)(Qr,{open:n("tables.row-discard-changes"),onOpenChange:K=>{K||v()},children:(0,a.jsxs)(Jr,{children:[(0,a.jsxs)(Yr,{children:[(0,a.jsx)(Xr,{children:"Discard unsaved changes?"}),(0,a.jsx)(es,{children:"This record has unsaved changes. Discard them and continue?"})]}),(0,a.jsxs)(Gr,{children:[(0,a.jsx)(Hr,{children:"Keep editing"}),(0,a.jsx)(Zr,{onClick:Ne,children:"Discard changes"})]})]})}),(0,a.jsx)(Qr,{open:n("tables.row-change-primary-key"),onOpenChange:K=>{K||(s("tables.row-change-primary-key"),S(null))},children:(0,a.jsxs)(Jr,{children:[(0,a.jsxs)(Yr,{children:[(0,a.jsx)(Xr,{children:"Change the primary key?"}),(0,a.jsx)(es,{children:"Changing the primary key changes the identity of this record. Existing references to the old key may break. Are you sure?"})]}),(0,a.jsxs)(Gr,{children:[(0,a.jsx)(Hr,{children:"Cancel"}),(0,a.jsx)(Zr,{onClick:()=>{s("tables.row-change-primary-key"),C&&(L(C),S(null))},children:"Change primary key"})]})]})}),(0,a.jsx)(Qr,{open:n("tables.row-delete-record"),onOpenChange:K=>{K||s("tables.row-delete-record")},children:(0,a.jsxs)(Jr,{children:[(0,a.jsxs)(Yr,{children:[(0,a.jsx)(Xr,{children:"Delete record"}),(0,a.jsxs)(es,{children:['Are you sure you want to delete this record from "',e,'"? This action cannot be undone.']})]}),(0,a.jsxs)(Gr,{children:[(0,a.jsx)(Hr,{children:"Cancel"}),(0,a.jsx)(Zr,{variant:"destructive",onClick:()=>{ne()},children:"Delete"})]})]})})]})};function P(){return P=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)({}).hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},P.apply(null,arguments)}function be(e,t){if(e==null)return{};var r={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(t.indexOf(s)!==-1)continue;r[s]=e[s]}return r}var bf={},xf=(0,f.createContext)(bf),rC=(e,t)=>P({},e,t),sC=()=>(0,f.useContext)(xf),Gi=(0,f.createContext)(()=>{});Gi.displayName="JVR.DispatchShowTools";function nC(){return(0,f.useReducer)(rC,bf)}function Sf(){return(0,f.useContext)(Gi)}var Cf=e=>{var{initial:t,dispatch:r,children:s}=e;return(0,a.jsx)(xf.Provider,{value:t,children:(0,a.jsx)(Gi.Provider,{value:r,children:s})})};Cf.displayName="JVR.ShowTools";var wf={},Nf=(0,f.createContext)(wf),aC=(e,t)=>P({},e,t),xa=()=>(0,f.useContext)(Nf),Yi=(0,f.createContext)(()=>{});Yi.displayName="JVR.DispatchExpands";function oC(){return(0,f.useReducer)(aC,wf)}function iC(){return(0,f.useContext)(Yi)}var jf=e=>{var{initial:t,dispatch:r,children:s}=e;return(0,a.jsx)(Nf.Provider,{value:t,children:(0,a.jsx)(Yi.Provider,{value:r,children:s})})};jf.displayName="JVR.Expands";var If={Str:{as:"span","data-type":"string",style:{color:"var(--w-rjv-type-string-color, #cb4b16)"},className:"w-rjv-type",children:"string"},Url:{as:"a",style:{color:"var(--w-rjv-type-url-color, #0969da)"},"data-type":"url",className:"w-rjv-type",children:"url"},Undefined:{style:{color:"var(--w-rjv-type-undefined-color, #586e75)"},as:"span","data-type":"undefined",className:"w-rjv-type",children:"undefined"},Null:{style:{color:"var(--w-rjv-type-null-color, #d33682)"},as:"span","data-type":"null",className:"w-rjv-type",children:"null"},Map:{style:{color:"var(--w-rjv-type-map-color, #268bd2)",marginRight:3},as:"span","data-type":"map",className:"w-rjv-type",children:"Map"},Nan:{style:{color:"var(--w-rjv-type-nan-color, #859900)"},as:"span","data-type":"nan",className:"w-rjv-type",children:"NaN"},Bigint:{style:{color:"var(--w-rjv-type-bigint-color, #268bd2)"},as:"span","data-type":"bigint",className:"w-rjv-type",children:"bigint"},Int:{style:{color:"var(--w-rjv-type-int-color, #268bd2)"},as:"span","data-type":"int",className:"w-rjv-type",children:"int"},Set:{style:{color:"var(--w-rjv-type-set-color, #268bd2)",marginRight:3},as:"span","data-type":"set",className:"w-rjv-type",children:"Set"},Float:{style:{color:"var(--w-rjv-type-float-color, #859900)"},as:"span","data-type":"float",className:"w-rjv-type",children:"float"},True:{style:{color:"var(--w-rjv-type-boolean-color, #2aa198)"},as:"span","data-type":"bool",className:"w-rjv-type",children:"bool"},False:{style:{color:"var(--w-rjv-type-boolean-color, #2aa198)"},as:"span","data-type":"bool",className:"w-rjv-type",children:"bool"},Date:{style:{color:"var(--w-rjv-type-date-color, #268bd2)"},as:"span","data-type":"date",className:"w-rjv-type",children:"date"}},Tf=(0,f.createContext)(If),lC=(e,t)=>P({},e,t),_e=()=>(0,f.useContext)(Tf),Ji=(0,f.createContext)(()=>{});Ji.displayName="JVR.DispatchTypes";function cC(){return(0,f.useReducer)(lC,If)}function dC(){return(0,f.useContext)(Ji)}function Rf(e){var{initial:t,dispatch:r,children:s}=e;return(0,a.jsx)(Tf.Provider,{value:t,children:(0,a.jsx)(Ji.Provider,{value:r,children:s})})}Rf.displayName="JVR.Types";var uC=["style"];function Ef(e){var{style:t}=e,r=be(e,uC),s=P({cursor:"pointer",height:"1em",width:"1em",userSelect:"none",display:"inline-flex"},t);return(0,a.jsx)("svg",P({viewBox:"0 0 24 24",fill:"var(--w-rjv-arrow-color, currentColor)",style:s},r,{children:(0,a.jsx)("path",{d:"M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z"})}))}Ef.displayName="JVR.TriangleArrow";var kf={Arrow:{as:"span",className:"w-rjv-arrow",style:{transform:"rotate(0deg)",transition:"all 0.3s"},children:(0,a.jsx)(Ef,{})},Colon:{as:"span",style:{color:"var(--w-rjv-colon-color, var(--w-rjv-color))",marginLeft:0,marginRight:2},className:"w-rjv-colon",children:":"},Quote:{as:"span",style:{color:"var(--w-rjv-quotes-color, #236a7c)"},className:"w-rjv-quotes",children:'"'},ValueQuote:{as:"span",style:{color:"var(--w-rjv-quotes-string-color, #cb4b16)"},className:"w-rjv-quotes",children:'"'},BracketsLeft:{as:"span",style:{color:"var(--w-rjv-brackets-color, #236a7c)"},className:"w-rjv-brackets-start",children:"["},BracketsRight:{as:"span",style:{color:"var(--w-rjv-brackets-color, #236a7c)"},className:"w-rjv-brackets-end",children:"]"},BraceLeft:{as:"span",style:{color:"var(--w-rjv-curlybraces-color, #236a7c)"},className:"w-rjv-curlybraces-start",children:"{"},BraceRight:{as:"span",style:{color:"var(--w-rjv-curlybraces-color, #236a7c)"},className:"w-rjv-curlybraces-end",children:"}"}},Af=(0,f.createContext)(kf),fC=(e,t)=>P({},e,t),wt=()=>(0,f.useContext)(Af),Qi=(0,f.createContext)(()=>{});Qi.displayName="JVR.DispatchSymbols";function hC(){return(0,f.useReducer)(fC,kf)}function mC(){return(0,f.useContext)(Qi)}var Of=e=>{var{initial:t,dispatch:r,children:s}=e;return(0,a.jsx)(Af.Provider,{value:t,children:(0,a.jsx)(Qi.Provider,{value:r,children:s})})};Of.displayName="JVR.Symbols";var Df={Copied:{className:"w-rjv-copied",style:{height:"1em",width:"1em",cursor:"pointer",verticalAlign:"middle",marginLeft:5}},CountInfo:{as:"span",className:"w-rjv-object-size",style:{color:"var(--w-rjv-info-color, #0000004d)",paddingLeft:8,fontStyle:"italic"}},CountInfoExtra:{as:"span",className:"w-rjv-object-extra",style:{paddingLeft:8}},Ellipsis:{as:"span",style:{cursor:"pointer",color:"var(--w-rjv-ellipsis-color, #cb4b16)",userSelect:"none"},className:"w-rjv-ellipsis",children:"..."},Row:{as:"div",className:"w-rjv-line"},KeyName:{as:"span",className:"w-rjv-object-key"}},Mf=(0,f.createContext)(Df),pC=(e,t)=>P({},e,t),Wt=()=>(0,f.useContext)(Mf),Xi=(0,f.createContext)(()=>{});Xi.displayName="JVR.DispatchSection";function gC(){return(0,f.useReducer)(pC,Df)}function vC(){return(0,f.useContext)(Xi)}var _f=e=>{var{initial:t,dispatch:r,children:s}=e;return(0,a.jsx)(Mf.Provider,{value:t,children:(0,a.jsx)(Xi.Provider,{value:r,children:s})})};_f.displayName="JVR.Section";var Pf={objectSortKeys:!1,indentWidth:15},Zi=(0,f.createContext)(Pf);Zi.displayName="JVR.Context";var Ff=(0,f.createContext)(()=>{});Ff.displayName="JVR.DispatchContext";function yC(e,t){return P({},e,t)}var ms=()=>(0,f.useContext)(Zi),Lf=e=>{var{children:t,initialState:r,initialTypes:s}=e,[n,o]=(0,f.useReducer)(yC,Object.assign({},Pf,r)),[l,i]=nC(),[c,d]=oC(),[u,h]=cC(),[m,p]=hC(),[b,w]=gC();return(0,f.useEffect)(()=>o(P({},r)),[r]),(0,a.jsx)(Zi.Provider,{value:n,children:(0,a.jsx)(Ff.Provider,{value:o,children:(0,a.jsx)(Cf,{initial:l,dispatch:i,children:(0,a.jsx)(jf,{initial:c,dispatch:d,children:(0,a.jsx)(Rf,{initial:P({},u,s),dispatch:h,children:(0,a.jsx)(Of,{initial:m,dispatch:p,children:(0,a.jsx)(_f,{initial:b,dispatch:w,children:t})})})})})})})};Lf.displayName="JVR.Provider";function bC(e){if(e==null)throw new TypeError("Cannot destructure "+e)}var xC=["isNumber","value","parentValue","keyName","keys"],SC=["as","render"],CC=["as","render"],wC=["as","render"],NC=["as","style","render"],jC=["as","render"],IC=["as","render"],TC=["as","render"],RC=["as","render"],Vo=e=>{var{Quote:t={}}=wt(),{isNumber:r,value:s,parentValue:n,keyName:o,keys:l}=e,i=be(e,xC);if(r)return null;var{as:c,render:d}=t,u=be(t,SC),h=c||"span",m=P({},i,u);typeof m.children=="string"&&(m.children=m.children.trim()||void 0);var p=d&&typeof d=="function"&&d(m,{value:s,parentValue:n,keyName:o,keys:l||(o?[o]:[])});return p||(0,a.jsx)(h,P({},m))};Vo.displayName="JVR.Quote";var ln=e=>{var{ValueQuote:t={}}=wt(),r=P({},(bC(e),e)),{as:s,render:n}=t,o=be(t,CC),l=s||"span",i=P({},r,o),c=n&&typeof n=="function"&&n(i,{});return c||(0,a.jsx)(l,P({},i))};ln.displayName="JVR.ValueQuote";var zf=e=>{var{value:t,parentValue:r,keyName:s,keys:n}=e,{Colon:o={}}=wt(),{as:l,render:i}=o,c=be(o,wC),d=l||"span",u=i&&typeof i=="function"&&i(c,{value:t,parentValue:r,keyName:s,keys:n||(s?[s]:[])});return u||(0,a.jsx)(d,P({},c))};zf.displayName="JVR.Colon";var $f=e=>{var{Arrow:t={}}=wt(),r=xa(),{expandKey:s,style:n,value:o,parentValue:l,keyName:i,keys:c}=e,d=!!r[s],{as:u,style:h,render:m}=t,p=be(t,NC),b=u||"span",w=m&&typeof m=="function",x=P({},p,{"data-expanded":d,style:P({},h,n)}),N=w&&m(x,{value:o,parentValue:l,keyName:i,keys:c||(i?[i]:[])});return N||(0,a.jsx)(b,P({},p,{style:P({},h,n)}))};$f.displayName="JVR.Arrow";var Vf=e=>{var{isBrackets:t,value:r,parentValue:s,keyName:n,keys:o}=e,{BracketsLeft:l={},BraceLeft:i={}}=wt(),c={value:r,parentValue:s,keyName:n,keys:o||(n?[n]:[])};if(t){var{as:d,render:u}=l,h=be(l,jC),m=d||"span",p=u&&typeof u=="function"&&u(h,c);return p||(0,a.jsx)(m,P({},h))}var{as:b,render:w}=i,x=be(i,IC),N=b||"span",C=w&&typeof w=="function"&&w(x,c);return C||(0,a.jsx)(N,P({},x))};Vf.displayName="JVR.BracketsOpen";var el=e=>{var{isBrackets:t,isVisiable:r,value:s,parentValue:n,keyName:o,keys:l}=e,i={value:s,parentValue:n,keyName:o,keys:l||(o?[o]:[])};if(!r)return null;var{BracketsRight:c={},BraceRight:d={}}=wt();if(t){var{as:u,render:h}=c,m=be(c,TC),p=u||"span",b=h&&typeof h=="function"&&h(m,i);return b||(0,a.jsx)(p,P({},m))}var{as:w,render:x}=d,N=be(d,RC),C=w||"span",S=x&&typeof x=="function"&&x(N,i);return S||(0,a.jsx)(C,P({},N))};el.displayName="JVR.BracketsClose";var Bf=e=>{var t,{keyName:r,value:s,expandKey:n,parentValue:o,level:l,keys:i=[]}=e,c=xa(),{collapsed:d,shouldExpandNodeInitially:u}=ms(),h=typeof d=="boolean"?d:typeof d=="number"?l>d:!1,m=(t=c[n])!=null?t:u?!1:h,p=u&&u(!m,{value:s,keys:i,level:l,keyName:r,parentValue:o});if(u&&d===!1){if(c[n]===void 0&&!p)return null}else if(c[n]===void 0&&p)return null;var b=Object.keys(s).length;if(m||b===0)return null;var w={paddingLeft:4},x={keyName:r,value:s,keys:i,parentValue:o},N=Array.isArray(s),C=s instanceof Set;return(0,a.jsx)("div",{style:w,children:(0,a.jsx)(el,P({isBrackets:N||C},x,{isVisiable:!0}))})};Bf.displayName="JVR.NestedClose";var EC=["as","render"],kC=["as","render"],AC=["as","render"],OC=["as","render"],DC=["as","render"],MC=["as","render"],_C=["as","render"],PC=["as","render"],FC=["as","render"],LC=["as","render"],zC=["as","render"],$C=["as","render"],VC=["as","render"],Bo=e=>{if(e===void 0)return"0n";if(typeof e=="string")try{e=BigInt(e)}catch{return"0n"}return e?e.toString()+"n":"0n"},Uf=e=>{var{value:t,keyName:r}=e,{Set:s={},displayDataTypes:n}=_e();if(!(t instanceof Set)||!n)return null;var{as:o,render:l}=s,i=be(s,EC),c=l&&typeof l=="function"&&l(i,{type:"type",value:t,keyName:r});return c||(0,a.jsx)(o||"span",P({},i))};Uf.displayName="JVR.SetComp";var qf=e=>{var{value:t,keyName:r}=e,{Map:s={},displayDataTypes:n}=_e();if(!(t instanceof Map)||!n)return null;var{as:o,render:l}=s,i=be(s,kC),c=l&&typeof l=="function"&&l(i,{type:"type",value:t,keyName:r});return c||(0,a.jsx)(o||"span",P({},i))};qf.displayName="JVR.MapComp";var Xt={opacity:.75,paddingRight:4},Wf=e=>{var{children:t="",keyName:r,keys:s}=e,{Str:n={},displayDataTypes:o}=_e(),{shortenTextAfterLength:l=30,stringEllipsis:i="..."}=ms(),{as:c,render:d}=n,u=be(n,AC),h=t,[m,p]=(0,f.useState)(l&&h.length>l);(0,f.useEffect)(()=>p(l&&h.length>l),[l]);var b=c||"span",w=P({},Xt,n.style||{});l>0&&(u.style=P({},u.style,{cursor:h.length<=l?"initial":"pointer"}),h.length>l&&(u.onClick=()=>{p(!m)}));var x=m?""+h.slice(0,l)+i:h,N=d&&typeof d=="function",C=N&&d(P({},u,{style:w}),{type:"type",value:t,keyName:r,keys:s}),S=m?"w-rjv-value w-rjv-value-short":"w-rjv-value",g=N&&d(P({},u,{children:x,className:S}),{type:"value",value:t,keyName:r,keys:s});return(0,a.jsxs)(f.Fragment,{children:[o&&(C||(0,a.jsx)(b,P({},u,{style:w}))),g||(0,a.jsxs)(f.Fragment,{children:[(0,a.jsx)(ln,{}),(0,a.jsx)(b,P({},u,{className:S,children:x})),(0,a.jsx)(ln,{})]})]})};Wf.displayName="JVR.TypeString";var Kf=e=>{var{children:t,keyName:r,keys:s}=e,{True:n={},displayDataTypes:o}=_e(),{as:l,render:i}=n,c=be(n,OC),d=l||"span",u=P({},Xt,n.style||{}),h=i&&typeof i=="function",m=h&&i(P({},c,{style:u}),{type:"type",value:t,keyName:r,keys:s}),p=h&&i(P({},c,{children:t,className:"w-rjv-value"}),{type:"value",value:t,keyName:r,keys:s});return(0,a.jsxs)(f.Fragment,{children:[o&&(m||(0,a.jsx)(d,P({},c,{style:u}))),p||(0,a.jsx)(d,P({},c,{className:"w-rjv-value",children:t?.toString()}))]})};Kf.displayName="JVR.TypeTrue";var Hf=e=>{var{children:t,keyName:r,keys:s}=e,{False:n={},displayDataTypes:o}=_e(),{as:l,render:i}=n,c=be(n,DC),d=l||"span",u=P({},Xt,n.style||{}),h=i&&typeof i=="function",m=h&&i(P({},c,{style:u}),{type:"type",value:t,keyName:r,keys:s}),p=h&&i(P({},c,{children:t,className:"w-rjv-value"}),{type:"value",value:t,keyName:r,keys:s});return(0,a.jsxs)(f.Fragment,{children:[o&&(m||(0,a.jsx)(d,P({},c,{style:u}))),p||(0,a.jsx)(d,P({},c,{className:"w-rjv-value",children:t?.toString()}))]})};Hf.displayName="JVR.TypeFalse";var Gf=e=>{var{children:t,keyName:r,keys:s}=e,{Float:n={},displayDataTypes:o}=_e(),{as:l,render:i}=n,c=be(n,MC),d=l||"span",u=P({},Xt,n.style||{}),h=i&&typeof i=="function",m=h&&i(P({},c,{style:u}),{type:"type",value:t,keyName:r,keys:s}),p=h&&i(P({},c,{children:t,className:"w-rjv-value"}),{type:"value",value:t,keyName:r,keys:s});return(0,a.jsxs)(f.Fragment,{children:[o&&(m||(0,a.jsx)(d,P({},c,{style:u}))),p||(0,a.jsx)(d,P({},c,{className:"w-rjv-value",children:t?.toString()}))]})};Gf.displayName="JVR.TypeFloat";var Yf=e=>{var{children:t,keyName:r,keys:s}=e,{Int:n={},displayDataTypes:o}=_e(),{as:l,render:i}=n,c=be(n,_C),d=l||"span",u=P({},Xt,n.style||{}),h=i&&typeof i=="function",m=h&&i(P({},c,{style:u}),{type:"type",value:t,keyName:r,keys:s}),p=h&&i(P({},c,{children:t,className:"w-rjv-value"}),{type:"value",value:t,keyName:r,keys:s});return(0,a.jsxs)(f.Fragment,{children:[o&&(m||(0,a.jsx)(d,P({},c,{style:u}))),p||(0,a.jsx)(d,P({},c,{className:"w-rjv-value",children:t?.toString()}))]})};Yf.displayName="JVR.TypeInt";var Jf=e=>{var{children:t,keyName:r,keys:s}=e,{Bigint:n={},displayDataTypes:o}=_e(),{as:l,render:i}=n,c=be(n,PC),d=l||"span",u=P({},Xt,n.style||{}),h=i&&typeof i=="function",m=h&&i(P({},c,{style:u}),{type:"type",value:t,keyName:r,keys:s}),p=h&&i(P({},c,{children:t,className:"w-rjv-value"}),{type:"value",value:t,keyName:r,keys:s});return(0,a.jsxs)(f.Fragment,{children:[o&&(m||(0,a.jsx)(d,P({},c,{style:u}))),p||(0,a.jsx)(d,P({},c,{className:"w-rjv-value",children:Bo(t?.toString())}))]})};Jf.displayName="JVR.TypeFloat";var Qf=e=>{var{children:t,keyName:r,keys:s}=e,{Url:n={},displayDataTypes:o}=_e(),{as:l,render:i}=n,c=be(n,FC),d=l||"span",u=P({},Xt,n.style),h=i&&typeof i=="function",m=h&&i(P({},c,{style:u}),{type:"type",value:t,keyName:r,keys:s}),p=h&&i(P({},c,{children:t?.href,className:"w-rjv-value"}),{type:"value",value:t,keyName:r,keys:s});return(0,a.jsxs)(f.Fragment,{children:[o&&(m||(0,a.jsx)(d,P({},c,{style:u}))),p||(0,a.jsxs)("a",P({href:t?.href,target:"_blank"},c,{className:"w-rjv-value",children:[(0,a.jsx)(ln,{}),t?.href,(0,a.jsx)(ln,{})]}))]})};Qf.displayName="JVR.TypeUrl";var Xf=e=>{var{children:t,keyName:r,keys:s}=e,{Date:n={},displayDataTypes:o}=_e(),{as:l,render:i}=n,c=be(n,LC),d=l||"span",u=P({},Xt,n.style||{}),h=i&&typeof i=="function",m=h&&i(P({},c,{style:u}),{type:"type",value:t,keyName:r,keys:s}),p=t instanceof Date?t.toLocaleString():t,b=h&&i(P({},c,{children:p,className:"w-rjv-value"}),{type:"value",value:t,keyName:r,keys:s});return(0,a.jsxs)(f.Fragment,{children:[o&&(m||(0,a.jsx)(d,P({},c,{style:u}))),b||(0,a.jsx)(d,P({},c,{className:"w-rjv-value",children:p}))]})};Xf.displayName="JVR.TypeDate";var Zf=e=>{var{children:t,keyName:r,keys:s}=e,{Undefined:n={},displayDataTypes:o}=_e(),{as:l,render:i}=n,c=be(n,zC),d=l||"span",u=P({},Xt,n.style||{}),h=i&&typeof i=="function",m=h&&i(P({},c,{style:u}),{type:"type",value:t,keyName:r,keys:s}),p=h&&i(P({},c,{children:t,className:"w-rjv-value"}),{type:"value",value:t,keyName:r,keys:s});return(0,a.jsxs)(f.Fragment,{children:[o&&(m||(0,a.jsx)(d,P({},c,{style:u}))),p||(0,a.jsx)(d,P({},c,{className:"w-rjv-value",children:"undefined"}))]})};Zf.displayName="JVR.TypeUndefined";var eh=e=>{var{children:t,keyName:r,keys:s}=e,{Null:n={},displayDataTypes:o}=_e(),{as:l,render:i}=n,c=be(n,$C),d=l||"span",u=P({},Xt,n.style||{}),h=i&&typeof i=="function",m=h&&i(P({},c,{style:u}),{type:"type",value:t,keyName:r,keys:s}),p=h&&i(P({},c,{children:t,className:"w-rjv-value"}),{type:"value",value:t,keyName:r,keys:s});return(0,a.jsxs)(f.Fragment,{children:[o&&(m||(0,a.jsx)(d,P({},c,{style:u}))),p||(0,a.jsx)(d,P({},c,{className:"w-rjv-value",children:"null"}))]})};eh.displayName="JVR.TypeNull";var th=e=>{var{children:t,keyName:r,keys:s}=e,{Nan:n={},displayDataTypes:o}=_e(),{as:l,render:i}=n,c=be(n,VC),d=l||"span",u=P({},Xt,n.style||{}),h=i&&typeof i=="function",m=h&&i(P({},c,{style:u}),{type:"type",value:t,keyName:r,keys:s}),p=h&&i(P({},c,{children:t?.toString(),className:"w-rjv-value"}),{type:"value",value:t,keyName:r,keys:s});return(0,a.jsxs)(f.Fragment,{children:[o&&(m||(0,a.jsx)(d,P({},c,{style:u}))),p||(0,a.jsx)(d,P({},c,{className:"w-rjv-value",children:"NaN"}))]})};th.displayName="JVR.TypeNan";var BC=e=>Number(e)===e&&e%1!==0||isNaN(e),rh=e=>{var{value:t,keyName:r,keys:s}=e,n={keyName:r,keys:s};return t instanceof URL?(0,a.jsx)(Qf,P({},n,{children:t})):typeof t=="string"?(0,a.jsx)(Wf,P({},n,{children:t})):t===!0?(0,a.jsx)(Kf,P({},n,{children:t})):t===!1?(0,a.jsx)(Hf,P({},n,{children:t})):t===null?(0,a.jsx)(eh,P({},n,{children:t})):t===void 0?(0,a.jsx)(Zf,P({},n,{children:t})):t instanceof Date?(0,a.jsx)(Xf,P({},n,{children:t})):typeof t=="number"&&isNaN(t)?(0,a.jsx)(th,P({},n,{children:t})):typeof t=="number"&&BC(t)?(0,a.jsx)(Gf,P({},n,{children:t})):typeof t=="bigint"?(0,a.jsx)(Jf,P({},n,{children:t})):typeof t=="number"?(0,a.jsx)(Yf,P({},n,{children:t})):null};rh.displayName="JVR.Value";function Fr(e,t,r){var s=mC(),n=[e.className,t.className].filter(Boolean).join(" "),o=P({},e,t,{className:n,style:P({},e.style,t.style),children:t.children||e.children});(0,f.useEffect)(()=>s({[r]:o}),[t])}function Dt(e,t,r){var s=dC(),n=[e.className,t.className].filter(Boolean).join(" "),o=P({},e,t,{className:n,style:P({},e.style,t.style),children:t.children||e.children});(0,f.useEffect)(()=>s({[r]:o}),[t])}function Fs(e,t,r){var s=vC(),n=[e.className,t.className].filter(Boolean).join(" "),o=P({},e,t,{className:n,style:P({},e.style,t.style),children:t.children||e.children});(0,f.useEffect)(()=>s({[r]:o}),[t])}var UC=["as","render"],sh=e=>{var{KeyName:t={}}=Wt();return Fs(t,e,"KeyName"),null};sh.displayName="JVR.KeyName";var nh=e=>{var{children:t,value:r,parentValue:s,keyName:n,keys:o}=e,l={color:typeof t=="number"?"var(--w-rjv-key-number, #268bd2)":"var(--w-rjv-key-string, #002b36)"},{KeyName:i={}}=Wt(),{as:c,render:d}=i,u=be(i,UC);u.style=P({},u.style,l);var h=c||"span",m=d&&typeof d=="function"&&d(P({},u,{children:t}),{value:r,parentValue:s,keyName:n,keys:o||(n?[n]:[])});return m||(0,a.jsx)(h,P({},u,{children:t}))};nh.displayName="JVR.KeyNameComp";var qC=["children","value","parentValue","keyName","keys"],WC=["as","render","children"],ah=e=>{var{Row:t={}}=Wt();return Fs(t,e,"Row"),null};ah.displayName="JVR.Row";var oh=e=>{var{children:t,value:r,parentValue:s,keyName:n,keys:o}=e,l=be(e,qC),{Row:i={}}=Wt(),{as:c,render:d}=i,u=be(i,WC),h=c||"div",m=d&&typeof d=="function"&&d(P({},l,u,{children:t}),{value:r,keyName:n,parentValue:s,keys:o});return m||(0,a.jsx)(h,P({},l,u,{children:t}))};oh.displayName="JVR.RowComp";function KC(e){var t=(0,f.useRef)();return(0,f.useEffect)(()=>{t.current=e}),t.current}function HC(e){var{value:t,highlightUpdates:r,highlightContainer:s}=e,n=KC(t),o=(0,f.useMemo)(()=>{if(!r||n===void 0)return!1;if(typeof t!=typeof n)return!0;if(typeof t=="number")return isNaN(t)&&isNaN(n)?!1:t!==n;if(Array.isArray(t)!==Array.isArray(n))return!0;if(typeof t=="object"||typeof t=="function")return!1;if(t!==n)return!0},[r,t]);(0,f.useEffect)(()=>{s&&s.current&&o&&"animate"in s.current&&s.current.animate([{backgroundColor:"var(--w-rjv-update-color, #ebcb8b)"},{backgroundColor:""}],{duration:1e3,easing:"ease-in"})},[o,t,s])}var GC=["keyName","value","parentValue","expandKey","keys","beforeCopy"],YC=["as","render"],tl=e=>{var{keyName:t,value:r,parentValue:s,expandKey:n,keys:o,beforeCopy:l}=e,i=be(e,GC),{onCopied:c,enableClipboard:d,beforeCopy:u}=ms(),h=sC()[n],[m,p]=(0,f.useState)(!1),{Copied:b={}}=Wt(),w=b?.beforeCopy;if(d===!1||!h)return null;var x=y=>{y.stopPropagation();var R="";typeof r=="number"&&r===1/0?R="Infinity":typeof r=="number"&&isNaN(r)?R="NaN":typeof r=="bigint"?R=Bo(r):r instanceof Date?R=r.toLocaleString():R=JSON.stringify(r,(k,T)=>typeof T=="bigint"?Bo(T):T,2);var I=l||w||u;I&&typeof I=="function"&&(R=I(R,t,r,s,n,o)),c&&c(R,r),p(!0),(navigator.clipboard||{writeText(k){return new Promise((T,D)=>{var _=document.createElement("textarea");_.style.position="absolute",_.style.opacity="0",_.style.left="-99999999px",_.value=k,document.body.appendChild(_),_.select(),document.execCommand("copy")?T():D(),_.remove()})}}).writeText(R).then(()=>{var k=setTimeout(()=>{p(!1),clearTimeout(k)},3e3)}).catch(k=>{})},N={style:{display:"inline-flex"},fill:m?"var(--w-rjv-copied-success-color, #28a745)":"var(--w-rjv-copied-color, currentColor)",onClick:x},{render:C}=b,S=be(b,YC),g=P({},S,i,N,{style:P({},S.style,i.style,N.style)}),v=C&&typeof C=="function"&&C(P({},g,{"data-copied":m}),{value:r,keyName:t,keys:o,parentValue:s});return v||(m?(0,a.jsx)("svg",P({viewBox:"0 0 32 36"},g,{children:(0,a.jsx)("path",{d:"M27.5,33 L2.5,33 L2.5,12.5 L27.5,12.5 L27.5,15.2249049 C29.1403264,13.8627542 29.9736597,13.1778155 30,13.1700887 C30,11.9705278 30,10.0804982 30,7.5 C30,6.1 28.9,5 27.5,5 L20,5 C20,2.2 17.8,0 15,0 C12.2,0 10,2.2 10,5 L2.5,5 C1.1,5 0,6.1 0,7.5 L0,33 C0,34.4 1.1,36 2.5,36 L27.5,36 C28.9,36 30,34.4 30,33 L30,26.1114493 L27.5,28.4926435 L27.5,33 Z M7.5,7.5 L10,7.5 C10,7.5 12.5,6.4 12.5,5 C12.5,3.6 13.6,2.5 15,2.5 C16.4,2.5 17.5,3.6 17.5,5 C17.5,6.4 18.8,7.5 20,7.5 L22.5,7.5 C22.5,7.5 25,8.6 25,10 L5,10 C5,8.5 6.1,7.5 7.5,7.5 Z M5,27.5 L10,27.5 L10,25 L5,25 L5,27.5 Z M28.5589286,16 L32,19.6 L21.0160714,30.5382252 L13.5303571,24.2571429 L17.1303571,20.6571429 L21.0160714,24.5428571 L28.5589286,16 Z M17.5,15 L5,15 L5,17.5 L17.5,17.5 L17.5,15 Z M10,20 L5,20 L5,22.5 L10,22.5 L10,20 Z"})})):(0,a.jsx)("svg",P({viewBox:"0 0 32 36"},g,{children:(0,a.jsx)("path",{d:"M27.5,33 L2.5,33 L2.5,12.5 L27.5,12.5 L27.5,20 L30,20 L30,7.5 C30,6.1 28.9,5 27.5,5 L20,5 C20,2.2 17.8,0 15,0 C12.2,0 10,2.2 10,5 L2.5,5 C1.1,5 0,6.1 0,7.5 L0,33 C0,34.4 1.1,36 2.5,36 L27.5,36 C28.9,36 30,34.4 30,33 L30,29 L27.5,29 L27.5,33 Z M7.5,7.5 L10,7.5 C10,7.5 12.5,6.4 12.5,5 C12.5,3.6 13.6,2.5 15,2.5 C16.4,2.5 17.5,3.6 17.5,5 C17.5,6.4 18.8,7.5 20,7.5 L22.5,7.5 C22.5,7.5 25,8.6 25,10 L5,10 C5,8.5 6.1,7.5 7.5,7.5 Z M5,27.5 L10,27.5 L10,25 L5,25 L5,27.5 Z M22.5,21.5 L22.5,16.5 L12.5,24 L22.5,31.5 L22.5,26.5 L32,26.5 L32,21.5 L22.5,21.5 Z M17.5,15 L5,15 L5,17.5 L17.5,17.5 L17.5,15 Z M10,20 L5,20 L5,22.5 L10,22.5 L10,20 Z"})})))};tl.displayName="JVR.Copied";function ih(){var e=(0,f.useRef)(null);return e.current===null&&(e.current="custom-id-"+Math.random().toString(36).substr(2,9)),e.current}var lh=e=>{var t,{keyName:r,value:s,expandKey:n="",level:o,keys:l=[],parentValue:i}=e,c=xa(),{objectSortKeys:d,indentWidth:u,collapsed:h,shouldExpandNodeInitially:m}=ms(),p=typeof h=="boolean"?h:typeof h=="number"?o>h:!1,b=(t=c[n])!=null?t:m?!1:p,w=m&&m(!b,{value:s,keys:l,level:o,keyName:r,parentValue:i});if(m&&h===!1){if(c[n]===void 0&&!w)return null}else if(c[n]===void 0&&w)return null;if(b)return null;var x=Array.isArray(s)?Object.entries(s).map(N=>[Number(N[0]),N[1]]):Object.entries(s);return d&&(x=d===!0?x.sort((N,C)=>{var[S]=N,[g]=C;return typeof S=="string"&&typeof g=="string"?S.localeCompare(g):0}):x.sort((N,C)=>{var[S,g]=N,[v,y]=C;return typeof S=="string"&&typeof v=="string"?d(S,v,g,y):0})),(0,a.jsx)("div",{className:"w-rjv-wrap",style:{borderLeft:"var(--w-rjv-border-left-width, 1px) var(--w-rjv-line-style, solid) var(--w-rjv-line-color, #ebebeb)",paddingLeft:u,marginLeft:6},children:x.map((N,C)=>{var[S,g]=N;return(0,a.jsx)(ch,{parentValue:s,keyName:S,keys:[...l,S],value:g,level:o},C)})})};lh.displayName="JVR.KeyValues";var rl=e=>{var{keyName:t,parentValue:r,keys:s,value:n}=e,{highlightUpdates:o}=ms(),l=typeof t=="number",i=(0,f.useRef)(null);HC({value:n,highlightUpdates:o,highlightContainer:i});var c={keyName:t,value:n,keys:s,parentValue:r};return(0,a.jsxs)(f.Fragment,{children:[(0,a.jsxs)("span",{ref:i,children:[(0,a.jsx)(Vo,P({isNumber:l,"data-placement":"left"},c)),(0,a.jsx)(nh,P({},c,{children:t})),(0,a.jsx)(Vo,P({isNumber:l,"data-placement":"right"},c))]}),(0,a.jsx)(zf,P({},c))]})};rl.displayName="JVR.KayName";var ch=e=>{var{keyName:t,value:r,parentValue:s,level:n=0,keys:o=[]}=e,l=Sf(),i=ih(),c=Array.isArray(r),d=r instanceof Set,u=r instanceof Map,h=r instanceof Date,m=r instanceof URL;if(r&&typeof r=="object"&&!c&&!d&&!u&&!h&&!m||c||d||u){var p=d?Array.from(r):u?Object.fromEntries(r):r;return(0,a.jsx)(sl,{keyName:t,value:p,parentValue:s,initialValue:r,keys:o,level:n+1})}return(0,a.jsxs)(oh,P({className:"w-rjv-line",value:r,keyName:t,keys:o,parentValue:s},{onMouseEnter:()=>l({[i]:!0}),onMouseLeave:()=>l({[i]:!1})},{children:[(0,a.jsx)(rl,{keyName:t,value:r,keys:o,parentValue:s}),(0,a.jsx)(rh,{keyName:t,value:r,keys:o}),(0,a.jsx)(tl,{keyName:t,value:r,keys:o,parentValue:s,expandKey:i})]}))};ch.displayName="JVR.KeyValuesItem";var JC=["value","keyName"],QC=["as","render"],dh=e=>{var{CountInfoExtra:t={}}=Wt();return Fs(t,e,"CountInfoExtra"),null};dh.displayName="JVR.CountInfoExtra";var uh=e=>{var{value:t={},keyName:r}=e,s=be(e,JC),{CountInfoExtra:n={}}=Wt(),{as:o,render:l}=n,i=be(n,QC);if(!l&&!i.children)return null;var c=o||"span",d=l&&typeof l=="function",u=P({},i,s),h=d&&l(u,{value:t,keyName:r});return h||(0,a.jsx)(c,P({},u))};uh.displayName="JVR.CountInfoExtraComps";var XC=["value","keyName"],ZC=["as","render"],fh=e=>{var{CountInfo:t={}}=Wt();return Fs(t,e,"CountInfo"),null};fh.displayName="JVR.CountInfo";var hh=e=>{var{value:t={},keyName:r}=e,s=be(e,XC),{displayObjectSize:n}=ms(),{CountInfo:o={}}=Wt();if(!n)return null;var{as:l,render:i}=o,c=be(o,ZC),d=l||"span";c.style=P({},c.style,e.style);var u=Object.keys(t).length;c.children||(c.children=u+" item"+(u===1?"":"s"));var h=P({},c,s),m=i&&typeof i=="function"&&i(P({},h,{"data-length":u}),{value:t,keyName:r});return m||(0,a.jsx)(d,P({},h))};hh.displayName="JVR.CountInfoComp";var ew=["as","render"],mh=e=>{var{Ellipsis:t={}}=Wt();return Fs(t,e,"Ellipsis"),null};mh.displayName="JVR.Ellipsis";var ph=e=>{var{isExpanded:t,value:r,keyName:s}=e,{Ellipsis:n={}}=Wt(),{as:o,render:l}=n,i=be(n,ew),c=o||"span",d=l&&typeof l=="function"&&l(P({},i,{"data-expanded":t}),{value:r,keyName:s});return d||(!t||typeof r=="object"&&Object.keys(r).length==0?null:(0,a.jsx)(c,P({},i)))};ph.displayName="JVR.EllipsisComp";var gh=e=>{var t,{keyName:r,expandKey:s,keys:n=[],initialValue:o,value:l,parentValue:i,level:c}=e,d=xa(),u=iC(),{onExpand:h,collapsed:m,shouldExpandNodeInitially:p}=ms(),b=typeof m=="boolean"?m:typeof m=="number"?c>m:!1,w=(t=d[s])!=null?t:p?!1:b,x=p&&p(!w,{value:l,keys:n,level:c,keyName:r,parentValue:i});d[s]===void 0&&p&&(w=!x);var N=()=>{var D={expand:!w,value:l,keyid:s,keyName:r};h&&h(D),u({[s]:D.expand})},C={display:"inline-flex",alignItems:"center"},S={transform:"rotate("+(w?"-90":"0")+"deg)",transition:"all 0.3s"},g=Object.keys(l).length,v=typeof l=="object",y=Array.isArray(l),R=l instanceof Set,I=g!==0&&(y||R||v),k={style:C};I&&(k.onClick=N);var T={keyName:r,value:l,keys:n,parentValue:i};return(0,a.jsxs)("span",P({},k,{children:[I&&(0,a.jsx)($f,P({style:S,expandKey:s},T)),(r||typeof r=="number")&&(0,a.jsx)(rl,P({},T)),(0,a.jsx)(Uf,{value:o,keyName:r}),(0,a.jsx)(qf,{value:o,keyName:r}),(0,a.jsx)(Vf,P({isBrackets:y||R},T)),(0,a.jsx)(ph,{keyName:r,value:l,isExpanded:w}),(0,a.jsx)(el,P({isVisiable:w||!I,isBrackets:y||R},T)),(0,a.jsx)(hh,{value:l,keyName:r}),(0,a.jsx)(uh,{value:l,keyName:r}),(0,a.jsx)(tl,{keyName:r,value:l,expandKey:s,parentValue:i,keys:n})]}))};gh.displayName="JVR.NestedOpen";var tw=["className","children","parentValue","keyid","level","value","initialValue","keys","keyName"],sl=(0,f.forwardRef)((e,t)=>{var{className:r="",parentValue:s,level:n=1,value:o,initialValue:l,keys:i,keyName:c}=e,d=be(e,tw),u=Sf(),h=ih(),m=[r,"w-rjv-inner"].filter(Boolean).join(" ");return(0,a.jsxs)("div",P({className:m,ref:t},d,{onMouseEnter:()=>u({[h]:!0}),onMouseLeave:()=>u({[h]:!1})},{children:[(0,a.jsx)(gh,{expandKey:h,value:o,level:n,keys:i,parentValue:s,keyName:c,initialValue:l}),(0,a.jsx)(lh,{expandKey:h,value:o,level:n,keys:i,parentValue:s,keyName:c}),(0,a.jsx)(Bf,{expandKey:h,value:o,level:n,keys:i,parentValue:s,keyName:c})]}))});sl.displayName="JVR.Container";var vh=e=>{var{BraceLeft:t={}}=wt();return Fr(t,e,"BraceLeft"),null};vh.displayName="JVR.BraceLeft";var yh=e=>{var{BraceRight:t={}}=wt();return Fr(t,e,"BraceRight"),null};yh.displayName="JVR.BraceRight";var bh=e=>{var{BracketsLeft:t={}}=wt();return Fr(t,e,"BracketsLeft"),null};bh.displayName="JVR.BracketsLeft";var xh=e=>{var{BracketsRight:t={}}=wt();return Fr(t,e,"BracketsRight"),null};xh.displayName="JVR.BracketsRight";var Sh=e=>{var{Arrow:t={}}=wt();return Fr(t,e,"Arrow"),null};Sh.displayName="JVR.Arrow";var Ch=e=>{var{Colon:t={}}=wt();return Fr(t,e,"Colon"),null};Ch.displayName="JVR.Colon";var wh=e=>{var{Quote:t={}}=wt();return Fr(t,e,"Quote"),null};wh.displayName="JVR.Quote";var Nh=e=>{var{ValueQuote:t={}}=wt();return Fr(t,e,"ValueQuote"),null};Nh.displayName="JVR.ValueQuote";var jh=e=>{var{Bigint:t={}}=_e();return Dt(t,e,"Bigint"),null};jh.displayName="JVR.Bigint";var Ih=e=>{var{Date:t={}}=_e();return Dt(t,e,"Date"),null};Ih.displayName="JVR.Date";var Th=e=>{var{False:t={}}=_e();return Dt(t,e,"False"),null};Th.displayName="JVR.False";var Rh=e=>{var{Float:t={}}=_e();return Dt(t,e,"Float"),null};Rh.displayName="JVR.Float";var Eh=e=>{var{Int:t={}}=_e();return Dt(t,e,"Int"),null};Eh.displayName="JVR.Int";var kh=e=>{var{Map:t={}}=_e();return Dt(t,e,"Map"),null};kh.displayName="JVR.Map";var Ah=e=>{var{Nan:t={}}=_e();return Dt(t,e,"Nan"),null};Ah.displayName="JVR.Nan";var Oh=e=>{var{Null:t={}}=_e();return Dt(t,e,"Null"),null};Oh.displayName="JVR.Null";var Dh=e=>{var{Set:t={}}=_e();return Dt(t,e,"Set"),null};Dh.displayName="JVR.Set";var Mh=e=>{var{Str:t={}}=_e();return Dt(t,e,"Str"),null};Mh.displayName="JVR.StringText";var _h=e=>{var{True:t={}}=_e();return Dt(t,e,"True"),null};_h.displayName="JVR.True";var Ph=e=>{var{Undefined:t={}}=_e();return Dt(t,e,"Undefined"),null};Ph.displayName="JVR.Undefined";var Fh=e=>{var{Url:t={}}=_e();return Dt(t,e,"Url"),null};Fh.displayName="JVR.Url";var Lh=e=>{var{Copied:t={}}=Wt();return Fs(t,e,"Copied"),null};Lh.displayName="JVR.Copied";var rw=["className","style","value","children","collapsed","shouldExpandNodeInitially","indentWidth","displayObjectSize","shortenTextAfterLength","stringEllipsis","highlightUpdates","enableClipboard","displayDataTypes","objectSortKeys","onExpand","onCopied","beforeCopy"],ke=(0,f.forwardRef)((e,t)=>{var{className:r="",style:s,value:n,children:o,collapsed:l=!1,shouldExpandNodeInitially:i,indentWidth:c=15,displayObjectSize:d=!0,shortenTextAfterLength:u=30,stringEllipsis:h,highlightUpdates:m=!0,enableClipboard:p=!0,displayDataTypes:b=!0,objectSortKeys:w=!1,onExpand:x,onCopied:N,beforeCopy:C}=e,S=be(e,rw),g=P({lineHeight:1.4,fontFamily:"var(--w-rjv-font-family, Menlo, monospace)",color:"var(--w-rjv-color, #002b36)",backgroundColor:"var(--w-rjv-background-color, #00000000)",fontSize:13},s),v=["w-json-view-container","w-rjv",r].filter(Boolean).join(" ");return(0,a.jsxs)(Lf,{initialState:{value:n,objectSortKeys:w,indentWidth:c,shouldExpandNodeInitially:l===!1?i:void 0,displayObjectSize:d,collapsed:l,enableClipboard:p,shortenTextAfterLength:u,stringEllipsis:h,highlightUpdates:m,onCopied:N,onExpand:x,beforeCopy:C},initialTypes:{displayDataTypes:b},children:[(0,a.jsx)(sl,P({value:n},S,{ref:t,className:v,style:g})),o]})});ke.Bigint=jh;ke.Date=Ih;ke.False=Th;ke.Float=Rh;ke.Int=Eh;ke.Map=kh;ke.Nan=Ah;ke.Null=Oh;ke.Set=Dh;ke.String=Mh;ke.True=_h;ke.Undefined=Ph;ke.Url=Fh;ke.ValueQuote=Nh;ke.Arrow=Sh;ke.Colon=Ch;ke.Quote=wh;ke.Ellipsis=mh;ke.BraceLeft=vh;ke.BraceRight=yh;ke.BracketsLeft=bh;ke.BracketsRight=xh;ke.Copied=Lh;ke.CountInfo=fh;ke.CountInfoExtra=dh;ke.KeyName=sh;ke.Row=ah;ke.displayName="JVR.JsonView";var sw={"--w-rjv-font-family":"monospace","--w-rjv-color":"#6f42c1","--w-rjv-key-string":"#6f42c1","--w-rjv-background-color":"#ffffff","--w-rjv-line-color":"#ddd","--w-rjv-arrow-color":"#6e7781","--w-rjv-edit-color":"var(--w-rjv-color)","--w-rjv-info-color":"#0000004d","--w-rjv-update-color":"#ebcb8b","--w-rjv-copied-color":"#002b36","--w-rjv-copied-success-color":"#28a745","--w-rjv-curlybraces-color":"#6a737d","--w-rjv-colon-color":"#24292e","--w-rjv-brackets-color":"#6a737d","--w-rjv-quotes-color":"var(--w-rjv-key-string)","--w-rjv-quotes-string-color":"var(--w-rjv-type-string-color)","--w-rjv-type-string-color":"#032f62","--w-rjv-type-int-color":"#005cc5","--w-rjv-type-float-color":"#005cc5","--w-rjv-type-bigint-color":"#005cc5","--w-rjv-type-boolean-color":"#d73a49","--w-rjv-type-date-color":"#005cc5","--w-rjv-type-url-color":"#0969da","--w-rjv-type-null-color":"#d73a49","--w-rjv-type-nan-color":"#859900","--w-rjv-type-undefined-color":"#005cc5"},nw={"--w-rjv-font-family":"monospace","--w-rjv-color":"#9cdcfe","--w-rjv-key-string":"#9cdcfe","--w-rjv-background-color":"#1e1e1e","--w-rjv-line-color":"#36334280","--w-rjv-arrow-color":"#838383","--w-rjv-edit-color":"var(--w-rjv-color)","--w-rjv-info-color":"#9c9c9c7a","--w-rjv-update-color":"#9cdcfe","--w-rjv-copied-color":"#9cdcfe","--w-rjv-copied-success-color":"#28a745","--w-rjv-curlybraces-color":"#d4d4d4","--w-rjv-colon-color":"#d4d4d4","--w-rjv-brackets-color":"#d4d4d4","--w-rjv-quotes-color":"var(--w-rjv-key-string)","--w-rjv-quotes-string-color":"var(--w-rjv-type-string-color)","--w-rjv-type-string-color":"#ce9178","--w-rjv-type-int-color":"#b5cea8","--w-rjv-type-float-color":"#b5cea8","--w-rjv-type-bigint-color":"#b5cea8","--w-rjv-type-boolean-color":"#569cd6","--w-rjv-type-date-color":"#b5cea8","--w-rjv-type-url-color":"#3b89cf","--w-rjv-type-null-color":"#569cd6","--w-rjv-type-nan-color":"#859900","--w-rjv-type-undefined-color":"#569cd6"};function aw({className:e,...t}){return(0,a.jsx)("nav",{"aria-label":"pagination","data-slot":"pagination",className:V("mx-auto flex w-full justify-center",e),...t})}function ow({className:e,...t}){return(0,a.jsx)("ul",{"data-slot":"pagination-content",className:V("flex flex-row items-center gap-1",e),...t})}function oc({...e}){return(0,a.jsx)("li",{"data-slot":"pagination-item",...e})}var zh=({tableName:e,variant:t="row"})=>{const{sidebar:{isPinned:r,width:s}}=fn(),[n,o]=ve(ce.TABLE_STATE_KEYS.LIMIT),[,l]=ve(ce.TABLE_STATE_KEYS.CURSOR),[,i]=ve(ce.TABLE_STATE_KEYS.DIRECTION),{tableData:c,prefetchPage:d}=va({tableName:e}),u=c?.meta?.total??0,h=c?.data?.length??0,m=t==="document"?"documents":"rows",p=t==="document"?"Documents per page":"Rows per page",b=n??"50",w=(0,f.useRef)(null),x=y=>{const R=parseInt(y,10);if(Number.isNaN(R)||R<1)return;const I=Math.min(R,1e4).toString();o(I),l(null),i(null)},N=()=>{c?.meta?.nextCursor&&(l(c.meta.nextCursor),i("asc"))},C=()=>{c?.meta?.prevCursor&&(l(c.meta.prevCursor),i("desc"))},S=()=>{c?.meta?.prevCursor&&d(c.meta.prevCursor,"desc")},g=()=>{c?.meta?.nextCursor&&d(c.meta.nextCursor,"asc")},v=()=>{l(null),i(null)};return(0,a.jsxs)("footer",{className:"fixed bottom-0 left-0 right-0 h-9 border-t border-border flex items-center justify-between bg-background px-2 text-foreground",style:{marginLeft:r?`${s}px`:"0"},children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(me,{className:"text-xs text-muted-foreground whitespace-nowrap",children:p}),(0,a.jsxs)("div",{className:"flex items-center h-6 rounded-sm border border-transparent hover:border-border focus-within:border-ring transition-colors",children:[(0,a.jsx)("input",{ref:w,type:"number",min:1,max:1e4,defaultValue:b,onBlur:y=>x(y.target.value),onKeyDown:y=>{y.key==="Enter"&&w.current?.blur()},className:"w-12 min-w-8 px-1 field-sizing-content supports-[field-sizing:content]:w-auto h-full bg-transparent text-xs text-center text-foreground outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"},b),(0,a.jsxs)(gn,{children:[(0,a.jsx)(vn,{asChild:!0,children:(0,a.jsx)("button",{type:"button",className:"flex items-center h-full px-0.5 text-muted-foreground hover:text-foreground transition-colors focus:outline-none","aria-label":"Choose preset row count",children:(0,a.jsx)(us,{className:"size-3"})})}),(0,a.jsx)(yn,{align:"start",className:"min-w-16 border-border",children:Hp.map(y=>(0,a.jsx)($t,{onSelect:()=>x(y.toString()),className:"text-xs justify-center",children:y},y))})]})]})]}),(0,a.jsx)("div",{className:"flex items-center justify-center text-xs text-muted-foreground",children:(0,a.jsxs)("p",{className:"whitespace-nowrap","aria-live":"polite",children:["Showing ",(0,a.jsx)("span",{className:"text-foreground font-medium",children:h})," of"," ",(0,a.jsxs)("span",{className:"text-foreground font-medium",children:[c?.meta?.totalEstimated&&"~",u]})," ",m]})}),(0,a.jsxs)("div",{className:"flex items-center gap-0.5",children:[(0,a.jsx)(B,{size:"sm",variant:"ghost",className:"size-6 disabled:opacity-30",onClick:v,disabled:!c?.meta?.hasPreviousPage||u===0,"aria-label":"Go to first page",children:(0,a.jsx)(Zm,{"aria-hidden":"true"})}),(0,a.jsx)(aw,{children:(0,a.jsxs)(ow,{className:"gap-0.5",children:[(0,a.jsx)(oc,{children:(0,a.jsx)(B,{size:"icon-sm",variant:"ghost",className:"size-6 disabled:opacity-30",onClick:C,onPointerEnter:S,onFocus:S,disabled:!c?.meta?.hasPreviousPage||u===0,"aria-label":"Go to previous page",children:(0,a.jsx)(oi,{"aria-hidden":"true"})})}),(0,a.jsx)(oc,{children:(0,a.jsx)(B,{size:"icon-sm",variant:"ghost",className:"size-6 disabled:opacity-30",onClick:N,onPointerEnter:g,onFocus:g,disabled:!c?.meta?.hasNextPage||u===0,"aria-label":"Go to next page",children:(0,a.jsx)(ci,{"aria-hidden":"true"})})})]})})]})]})};function iw(e){if(typeof window>"u"||!window.matchMedia)return()=>{};const t=window.matchMedia(wd);return typeof t.addEventListener=="function"?(t.addEventListener("change",e),()=>{t.removeEventListener("change",e)}):typeof t.addListener=="function"?(t.addListener(e),()=>{t.removeListener(e)}):()=>{}}function lw(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia(wd).matches}function cw(){return!1}function nl(){const{theme:e,setTheme:t,toggleTheme:r}=fn(),s=(0,f.useSyncExternalStore)(iw,lw,cw),n=e==="system"?s?"dark":"light":e,o=n==="dark";return(0,f.useEffect)(()=>{const l=window.document.documentElement;o?(l.classList.add("dark"),l.classList.remove("light"),document.querySelector('meta[name="theme-color"]')?.setAttribute("content","#09090b")):(l.classList.remove("dark"),l.classList.add("light"),document.querySelector('meta[name="theme-color"]')?.setAttribute("content","#ffffff"))},[o]),{theme:e,resolvedTheme:n,isDark:o,setTheme:t,toggleTheme:r}}var dw=({tableName:e,rows:t})=>{const{isDark:r}=nl();return(0,a.jsxs)("div",{className:"flex-1 w-full flex flex-col overflow-hidden pb-9",children:[(0,a.jsx)("div",{className:"flex-1 overflow-auto bg-background p-3",children:(0,a.jsx)(ke,{value:t,keyName:e,objectSortKeys:!1,displayObjectSize:!0,displayDataTypes:!1,indentWidth:14,collapsed:1,shortenTextAfterLength:120,highlightUpdates:!1,style:r?nw:sw,enableClipboard:!0,className:"size-full"})}),(0,a.jsx)(zh,{tableName:e,variant:"document"})]})},uw=()=>{const{openOverlay:e}=je();return(0,a.jsxs)(gn,{children:[(0,a.jsx)(vn,{asChild:!0,children:(0,a.jsxs)(B,{type:"button",variant:"default",className:"h-8! border-l-0 border-y-0 border-r border-border rounded-none flex items-center gap-2","aria-label":"Add records to the table",children:[(0,a.jsx)(Ln,{className:"size-4"}),"Add Record"]})}),(0,a.jsxs)(yn,{align:"start",className:"w-48",children:[(0,a.jsx)($t,{onClick:()=>e("records.add-record"),children:"Add Record"}),(0,a.jsx)($t,{onClick:()=>e("records.bulk-insert-csv"),children:"Add data from CSV"}),(0,a.jsx)($t,{onClick:()=>e("records.bulk-insert-excel"),children:"Add data from Excel"}),(0,a.jsx)($t,{onClick:()=>e("records.bulk-insert-json"),children:"Add data from JSON"})]})]})},fw=()=>Ct(()=>import("./_table-CXzhHR9S.js"),__vite__mapDeps([14,3,1,2])),al=At("/_pathlessLayout/table/$table")({component:kt(fw,"component")}),$h=()=>{const e=St(),{table:t}=al.useParams(),{clearUpdates:r,getUpdateCount:s}=qt(),{selectedDatabase:n}=Me(),{tableCols:o}=mt({tableName:t}),{mutateAsync:l,isPending:i}=ht({mutationFn:async d=>{if(!t)throw new Error("No table selected");const u=yf(o),h={tableName:t,updates:d.map(m=>({rowData:m.rowData,columnName:m.columnName,value:m.newValue})),...u.length>0?{primaryKey:u[0],primaryKeys:u}:{}};return(await pd({...h,db:n})).data.data},onSuccess:async()=>{r(),await Promise.all([e.invalidateQueries({queryKey:Ee.dataByTable(t),exact:!1})])}});return{updateCell:async d=>{const u=s();return we.promise(l(d),{loading:"Saving changes...",success:h=>h||`${u} ${u===1?"change":"changes"} saved successfully`,error:h=>h.message||"Failed to save changes"})},isUpdatingCell:i}},hw=()=>{const{getUpdateCount:e,clearUpdates:t}=qt(),{isUpdatingCell:r}=$h(),s=(0,f.useCallback)(()=>{t()},[t]);return e()===0?null:(0,a.jsx)(B,{type:"button",variant:"secondary",className:"h-8! border-l-0 border-y-0 border-r border-border rounded-none",onClick:s,"aria-label":"Clear changes to the table",disabled:r,children:"Clear Changes"})},mw=({tableName:e})=>{const[t,r]=(0,f.useState)(""),[s,n]=(0,f.useState)(null),o=(0,f.useRef)(null),{tableCols:l}=mt({tableName:e}),{orderedColumns:i,visibleColumns:c,toggleColumn:d,moveColumn:u,reorderColumn:h,showAllColumns:m,resetColumns:p}=gf({tableName:e,tableCols:l}),b=(0,f.useMemo)(()=>{const v=t.trim().toLowerCase();return v?i.filter(y=>y.toLowerCase().includes(v)):i},[i,t]),w=s?.order??b,x=()=>{if(!s)return;const v=s.order.indexOf(s.name);v>0?h(s.name,s.order[v-1],"after"):s.order.length>1&&h(s.name,s.order[1],"before")},N=(0,f.useMemo)(()=>new Set(c),[c]),C=l?.length??0,S=C-c.length,g=S>0||i.some((v,y)=>(l??[])[y]?.columnName!==v);return(0,a.jsxs)(Mr,{children:[(0,a.jsx)(fs,{asChild:!0,children:(0,a.jsx)(B,{type:"button",variant:"ghost",className:V("size-8! aspect-square border-l-0 border-y-0 border-r border-border rounded-none text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors",g&&"text-foreground"),"aria-label":"Manage columns","data-active":g,children:(0,a.jsx)(tp,{className:"size-4"})})}),(0,a.jsxs)(ur,{align:"start",className:"w-72 gap-0 p-0",onOpenAutoFocus:v=>{v.preventDefault(),o.current?.focus()},children:[(0,a.jsxs)("div",{className:"flex items-center gap-2 p-2",children:[(0,a.jsxs)("div",{className:"relative flex-1",children:[(0,a.jsx)(ai,{className:"absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground pointer-events-none"}),(0,a.jsx)("input",{ref:o,type:"text",placeholder:"Search columns...",value:t,onChange:v=>r(v.target.value),className:"w-full h-8 pl-7 pr-2 text-sm bg-transparent rounded-md border border-border focus:outline-none focus:ring-1 focus:ring-ring","aria-label":"Search columns"})]}),(0,a.jsxs)("span",{className:"text-xs text-muted-foreground tabular-nums whitespace-nowrap",title:`${c.length} of ${C} columns shown`,children:[c.length,"/",C]})]}),(0,a.jsx)(Vn,{className:"my-0"}),(0,a.jsxs)("div",{className:"max-h-72 overflow-y-auto py-1",role:"list","aria-label":"Database columns",onDragOver:v=>{s&&(v.preventDefault(),v.dataTransfer.dropEffect="move")},onDrop:v=>{v.preventDefault(),x()},children:[w.map((v,y)=>{const R=N.has(v);return(0,a.jsxs)("div",{role:"listitem",draggable:!0,onDragStart:I=>{I.dataTransfer.effectAllowed="move",I.dataTransfer.setData("text/plain",v),n({name:v,order:b})},onDragEnter:()=>n(I=>I&&I.name!==v?{...I,order:$o(I.order,I.name,v)}:I),onDragEnd:()=>n(null),className:V("group flex items-center gap-1.5 px-2 py-1 rounded-md",s?.name===v&&"bg-muted text-muted-foreground"),children:[(0,a.jsx)("span",{role:"button",tabIndex:0,"aria-label":`Reorder ${v}`,"aria-roledescription":"sortable",title:"Drag, or focus and press ArrowUp or ArrowDown to move",className:"cursor-grab active:cursor-grabbing text-muted-foreground/70 hover:text-muted-foreground focus-visible:outline focus-visible:outline-1 focus-visible:outline-ring rounded-sm",onKeyDown:I=>{I.key==="ArrowUp"?(I.preventDefault(),I.stopPropagation(),u(v,-1,b)):I.key==="ArrowDown"&&(I.preventDefault(),I.stopPropagation(),u(v,1,b))},children:(0,a.jsx)(Hm,{className:"size-4"})}),(0,a.jsx)(kr,{checked:R,onCheckedChange:()=>d(v),"aria-label":`Show ${v}`}),(0,a.jsx)("span",{className:"text-sm flex-1 cursor-pointer select-none truncate",onClick:()=>d(v),children:v}),(0,a.jsxs)("span",{className:"flex flex-col opacity-0 group-hover:opacity-100 focus-within:opacity-100",children:[(0,a.jsx)("button",{type:"button",tabIndex:0,disabled:y===0,"aria-label":`Move ${v} up`,className:"text-muted-foreground/70 hover:text-foreground disabled:opacity-30 disabled:pointer-events-none",onClick:()=>u(v,-1,b),children:(0,a.jsx)(ii,{className:"size-3.5"})}),(0,a.jsx)("button",{type:"button",tabIndex:0,disabled:y===w.length-1,"aria-label":`Move ${v} down`,className:"text-muted-foreground/70 hover:text-foreground disabled:opacity-30 disabled:pointer-events-none",onClick:()=>u(v,1,b),children:(0,a.jsx)(us,{className:"size-3.5"})})]})]},v)}),b.length===0&&(0,a.jsxs)("p",{className:"text-sm text-muted-foreground text-center py-4 px-2",children:['No columns match "',t,'"']})]}),(0,a.jsx)(Vn,{className:"my-0"}),(0,a.jsxs)("div",{className:"p-2 flex gap-2",children:[(0,a.jsxs)(B,{variant:"outline",size:"sm",className:"flex-1 text-xs",disabled:S===0,onClick:m,children:[(0,a.jsx)(ap,{className:"size-3.5"}),"Show all"]}),(0,a.jsxs)(B,{variant:"outline",size:"sm",className:"flex-1 text-xs",disabled:!g,onClick:p,children:[(0,a.jsx)(Qm,{className:"size-3.5"}),"Reset"]})]})]})]})},pw=({isOpenFkDialog:e,handleDialogClose:t,relatedRecords:r,handleCancelForceDelete:s,handleForceDelete:n,isDeletingCells:o})=>(0,a.jsx)(ta,{open:e,onOpenChange:t,children:(0,a.jsxs)(ra,{className:"max-w-2xl z-500",children:[(0,a.jsxs)(sa,{children:[(0,a.jsx)(na,{children:"Cannot Delete - Foreign Key Constraint"}),(0,a.jsx)(aa,{children:"The selected records cannot be deleted because they are referenced by records in other tables. You can either cancel the operation or force delete, which will also delete all related records."})]}),(0,a.jsx)(gw,{relatedRecords:r}),(0,a.jsxs)(bi,{className:"gap-2",children:[(0,a.jsx)(B,{variant:"outline",onClick:s,disabled:o,children:"Cancel"}),(0,a.jsx)(B,{variant:"destructive",onClick:n,disabled:o,children:o?"Deleting...":"Force Delete All"})]})]})}),gw=({relatedRecords:e})=>(0,a.jsx)("div",{className:"space-y-4 max-h-64 overflow-y-auto",children:e.map((t,r)=>(0,a.jsxs)("div",{className:"border border-border rounded-md p-3",children:[(0,a.jsxs)("div",{className:"font-medium text-sm mb-2",children:["Table: ",(0,a.jsx)("span",{className:"text-primary",children:t.tableName}),(0,a.jsxs)("span",{className:"text-muted-foreground ml-2",children:["(",t.records.length," record",t.records.length!==1?"s":"",")"]})]}),(0,a.jsxs)("div",{className:"text-xs text-muted-foreground mb-2",children:["References column: ",t.columnName]}),(0,a.jsx)("div",{className:"bg-muted rounded p-2 text-xs overflow-x-auto",children:(0,a.jsxs)("pre",{className:"whitespace-pre-wrap",children:[JSON.stringify(t.records.slice(0,5),null,2),t.records.length>5&&(0,a.jsxs)("div",{className:"text-muted-foreground mt-2",children:["... and ",t.records.length-5," more"]})]})})]},`${t.tableName}-${t.columnName}-${r}`))}),vw=({selectedRows:e,setRowSelection:t,tableName:r,disabledReason:s})=>{const{deleteCells:n,forceDeleteCells:o,isDeletingCells:l,resetDeleteResult:i}=vf({tableName:r}),[c,d]=(0,f.useState)([]),[u,h]=(0,f.useState)(!1),[m,p]=(0,f.useState)(!1),[b,w]=(0,f.useState)([]),x=(0,f.useCallback)(()=>{s||p(!0)},[s]),N=(0,f.useCallback)(async()=>{if(s)return;const v=e.map(y=>y.original);p(!1);try{await n(v),t({})}catch{d(v),w([]),h(!0)}},[s,n,e,t]),C=async()=>{s||c.length===0||(await o(c))?.deletedCount>0&&(h(!1),d([]),w([]),i(),t({}))},S=(0,f.useCallback)(()=>{h(!1),d([]),w([]),i()},[i]),g=v=>{l||(v?h(v):S())};return e?.length===0?null:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(B,{type:"button",variant:"destructive",className:"h-8! border-l-0 border-y-0 border-r border-border text-white rounded-none",onClick:x,"aria-label":"Delete the selected record",disabled:l||!!s,title:s,children:["Delete Record",e?.length>1&&(0,a.jsx)("span",{className:"ml-1.5 px-1.5 text-[10px] bg-white/20 border border-white/20 rounded",children:e?.length})]}),(0,a.jsx)(Qr,{open:m,onOpenChange:p,children:(0,a.jsxs)(Jr,{children:[(0,a.jsxs)(Yr,{children:[(0,a.jsxs)(Xr,{children:["Delete ",e.length===1?"Record":"Records"]}),(0,a.jsxs)(es,{children:["Are you sure you want to delete"," ",e.length===1?"this record":`${e.length} records`," ",'from "',r,'"? This action cannot be undone.']})]}),(0,a.jsxs)(Gr,{children:[(0,a.jsx)(Hr,{children:"Cancel"}),(0,a.jsx)(Zr,{variant:"destructive",onClick:N,children:"Delete"})]})]})}),(0,a.jsx)(pw,{isOpenFkDialog:u,handleDialogClose:g,relatedRecords:b,handleCancelForceDelete:S,handleForceDelete:C,isDeletingCells:l})]})},yw=({tableName:e})=>{const[t,r]=ve(ce.TABLE_STATE_KEYS.FILTERS,Es(S=>S).withDefault([]).withOptions({history:"push"})),[,s]=ve(ce.TABLE_STATE_KEYS.CURSOR),[,n]=ve(ce.TABLE_STATE_KEYS.DIRECTION),{tableCols:o}=mt({tableName:e}),[l,i]=(0,f.useState)(!1),[c,d]=(0,f.useState)([]),u=()=>{const S=o?.[0]?.columnName??"";d(g=>[...g,{columnName:S,operator:"=",value:""}])},h=S=>{d(c.filter((g,v)=>v!==S))},m=(S,g)=>{d(c.map((v,y)=>y===S?{...v,columnName:g}:v))},p=(S,g)=>{d(c.map((v,y)=>y===S?{...v,value:g}:v))},b=(S,g)=>{d(c.map((v,y)=>y===S?{...v,operator:g}:v))},w=()=>{d([]),r([]),s(null),n(null),i(!1)},x=()=>{const S=c.filter(g=>g.columnName&&g.operator&&g.value!=="");r(S),s(null),n(null),i(!1)},N=t.length>0,C=S=>{S&&d(t),i(S)};return(0,a.jsxs)(Mr,{open:l,onOpenChange:C,children:[(0,a.jsx)(fs,{asChild:!0,children:(0,a.jsx)(B,{type:"button",variant:"ghost",className:"size-8! aspect-square border-l-0 border-y-0 border-r border-border rounded-none text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors","aria-label":"Filter table data","data-active":N,children:(0,a.jsx)(ad,{className:"size-4"})})}),(0,a.jsxs)(ur,{className:"w-md space-y-2",align:"start",children:[(0,a.jsx)("div",{className:"flex items-center gap-4",children:(0,a.jsxs)(B,{variant:"outline",size:"lg",className:"text-sm",onClick:u,children:["Add filter",c&&c.length>0&&(0,a.jsx)(et,{className:"text-xs font-normal text-primary bg-primary/10 border border-primary/30 px-1.5 py-0.5",children:c.length})]})}),(0,a.jsx)("div",{className:"flex flex-col gap-4",children:c.length>0?c.map((S,g)=>(0,a.jsxs)("div",{className:"flex-1 flex h-9 gap-2",children:[(0,a.jsxs)(dt,{value:S.columnName,onValueChange:v=>m(g,v),children:[(0,a.jsx)(lt,{className:"w-full flex-1",children:(0,a.jsx)(it,{placeholder:"Select column"})}),(0,a.jsx)(ct,{children:o?.map(v=>(0,a.jsx)(ue,{value:v.columnName,children:v.columnName},v.columnName))})]}),(0,a.jsxs)(dt,{value:S.operator,onValueChange:v=>b(g,v),children:[(0,a.jsx)(lt,{children:(0,a.jsx)(it,{placeholder:"Op"})}),(0,a.jsxs)(ct,{children:[(0,a.jsx)(ue,{value:"=",children:"="}),(0,a.jsx)(ue,{value:"!=",children:"!="}),(0,a.jsx)(ue,{value:">",children:">"}),(0,a.jsx)(ue,{value:">=",children:">="}),(0,a.jsx)(ue,{value:"<",children:"<"}),(0,a.jsx)(ue,{value:"<=",children:"<="}),(0,a.jsx)(ue,{value:"is",children:"is"}),(0,a.jsx)(ue,{value:"is not",children:"is not"}),(0,a.jsx)(ue,{value:"like",children:"like"}),(0,a.jsx)(ue,{value:"not like",children:"not like"}),(0,a.jsx)(ue,{value:"ilike",children:"ilike"}),(0,a.jsx)(ue,{value:"not ilike",children:"not ilike"})]})]}),(0,a.jsx)(Ke,{type:"text",placeholder:"Value",value:S.value,onChange:v=>p(g,v.target.value)}),(0,a.jsx)(B,{variant:"ghost",size:"icon",className:"text-xs",onClick:()=>h(g),children:(0,a.jsx)(As,{className:"size-4"})})]},`${S.columnName}-${g}`)):(0,a.jsx)("div",{className:"flex-1 flex h-9 gap-2 items-center justify-center",children:(0,a.jsx)("p",{className:"text-sm text-muted-foreground text-center",children:"No filters applied"})})}),(0,a.jsxs)("div",{className:"gap-2 flex justify-end",children:[(0,a.jsx)(B,{variant:"outline",size:"lg",className:"text-sm",onClick:w,children:"Reset"}),(0,a.jsx)(B,{variant:"default",size:"lg",className:"text-sm",onClick:x,children:"Apply"})]})]})]})},bw=({tableName:e})=>{const{isLive:t,status:r,isPulsing:s,setLive:n}=xr(),o=(0,f.useCallback)(()=>{n(!t,e)},[t,e,n]);let l="Live mode: Automatic updates (Off)";return r==="paused"?l="Live mode paused while editing. Click to resume.":t&&r==="healthy"?l="Live mode: Active":t&&r==="disconnected"&&(l="Live mode: Disconnected. Attempting to reconnect..."),(0,a.jsxs)(ir,{children:[(0,a.jsx)(ar,{asChild:!0,children:(0,a.jsxs)(B,{type:"button",variant:"ghost",onClick:o,"aria-label":"Toggle Live mode","aria-pressed":t,"data-active":t,className:V("h-8! px-2.5 border-l-0 border-y-0 border-r border-border rounded-none text-xs font-medium gap-1.5 flex items-center text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors",t&&"text-foreground"),children:[(0,a.jsxs)("span",{className:"relative flex size-2 items-center justify-center",children:[t&&r==="healthy"&&s&&(0,a.jsx)("span",{"data-testid":"live-pulse-indicator",className:"absolute inline-flex size-3.5 rounded-full bg-emerald-400 opacity-75 animate-ping"}),(0,a.jsx)("span",{"data-testid":"live-status-dot",className:V("relative inline-flex size-2 rounded-full transition-colors",{"bg-emerald-500":t&&r==="healthy","bg-amber-500":t&&r==="disconnected","bg-amber-400":!t&&r==="paused","bg-muted-foreground/40":!t&&r!=="paused"})})]}),(0,a.jsx)("span",{children:"Live"}),r==="paused"&&(0,a.jsx)("span",{className:"text-[10px] text-amber-500 font-normal",children:"(Paused)"})]})}),(0,a.jsx)(or,{side:"bottom",children:l})]})},xw=({tableName:e})=>{const{refetchTableData:t,isRefetchingTableData:r}=va({tableName:e}),{refetchTableCols:s,isRefetchingTableCols:n}=mt({tableName:e}),o=(0,f.useCallback)(()=>{Promise.all([t(),s()])},[t,s]);return(0,a.jsx)(B,{type:"button",variant:"ghost",className:"size-8! aspect-square border-l-0 border-y-0 border-r border-border rounded-none text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors",onClick:o,"aria-label":"Refetch table data and columns",disabled:r||n,children:(0,a.jsx)(di,{className:"size-4"})})},Sw=({setRowSelection:e,disabledReason:t})=>{const{getUpdates:r,getUpdateCount:s}=qt(),{updateCell:n,isUpdatingCell:o}=$h(),l=(0,f.useCallback)(async()=>{if(t)return;const c=r();if(c.length!==0)try{await n(c),e({})}catch(d){console.error("Failed to save updates:",d)}},[t,r,n,e]);if(s()===0)return null;const i=s();return(0,a.jsxs)(B,{type:"button",variant:"default",className:"h-8! border-l-0 border-y-0 border-r border-border rounded-none bg-green-700 text-white hover:bg-green-800",onClick:l,"aria-label":"Save changes to the table",disabled:o||!!t,title:t,children:["Save Changes",i>0&&(0,a.jsx)("span",{className:"ml-1.5 px-1.5 text-[10px] bg-white/20 border border-white/20 rounded",children:i})]})},Vh=({selectedRows:e,setRowSelection:t,tableName:r})=>{const s=ha(),n=_r()?.liveMode??!1,{rowMutationReason:o}=Ki();return(0,a.jsx)("header",{className:"max-h-8 overflow-hidden border-b border-border w-full flex items-center justify-between bg-background sticky top-0 left-0 right-0 z-0",children:(0,a.jsxs)("div",{className:"flex items-center ",children:[(0,a.jsx)(xw,{tableName:r}),n&&(0,a.jsx)(bw,{tableName:r}),!s&&(0,a.jsx)(yw,{tableName:r}),(0,a.jsx)(mw,{tableName:r}),(0,a.jsx)(uw,{}),(0,a.jsx)(Sw,{setRowSelection:t,disabledReason:o}),(0,a.jsx)(hw,{}),(0,a.jsx)(vw,{tableName:r,selectedRows:e,setRowSelection:t,disabledReason:o})]})})},Cw=({tableName:e,selectedRows:t,setRowSelection:r})=>(0,a.jsxs)("div",{className:"size-full flex flex-col items-center justify-center",children:[(0,a.jsx)(Vh,{selectedRows:t,setRowSelection:r,tableName:e}),(0,a.jsxs)("div",{className:"text-sm text-muted-foreground flex-1 flex items-center justify-center",children:['No data available for "',e,'" table']})]}),ww=({tableName:e,errorTableData:t,errorTableCols:r})=>{const s=t||r,n=s?.message||"",o=n.includes("does not exist")||n.includes("404")||s?.status===404,l=n.includes("Network Error")||n.includes("Failed to fetch");let i="Something went wrong",c=n||"An unexpected error occurred";return o?(i="Table not found",c=n||`The table "${e}" does not exist or has been deleted`):l&&(i="Connection failed",c="Unable to connect to the database server. Please check your connection."),(0,a.jsx)("div",{className:"size-full flex flex-col items-center justify-center",children:(0,a.jsxs)("div",{className:"flex-1 flex flex-col items-center justify-center gap-2",children:[(0,a.jsx)("div",{className:"text-sm font-medium",children:i}),(0,a.jsx)("div",{className:"text-sm text-muted-foreground",children:c})]})})};var Nw=(e=250)=>{const t=(0,f.useRef)(null);return(0,f.useEffect)(()=>()=>{t.current!==null&&window.clearTimeout(t.current)},[]),{schedule:(0,f.useCallback)(r=>{t.current!==null&&window.clearTimeout(t.current),t.current=window.setTimeout(()=>{t.current=null,r()},e)},[e]),cancel:(0,f.useCallback)(()=>{t.current!==null&&(window.clearTimeout(t.current),t.current=null)},[])}},jw=(0,f.memo)(function({row:t,tableName:r,virtualColumns:s,virtualPaddingLeft:n,virtualPaddingRight:o,virtualRow:l}){const i=t.getVisibleCells(),{schedule:c,cancel:d}=Nw(),{highlightedRowIds:u}=xr(),h=u.has(t.id),m=()=>{ls.getState().setRowDetails(r,l.index),je.getState().openOverlay("tables.row-details")};return(0,a.jsxs)("tr",{"data-index":l.index,className:V("flex absolute w-fit border-b items-center justify-between text-sm hover:bg-accent/20 data-[state=open]:bg-accent/40 [&_svg]:size-4",h&&"bg-emerald-500/15 dark:bg-emerald-500/20 transition-colors duration-1000 ease-in-out"),style:{transform:`translateY(${l.start}px)`},onClick:p=>{p.target.closest("button, a, input, textarea, select, [role=checkbox], [role=listbox], [role=dialog], [data-grid-cell-editor]")||c(m)},onDoubleClick:d,children:[n?(0,a.jsx)("td",{style:{display:"flex",width:n}}):null,s.map(p=>{const b=i[p.index];return(0,a.jsxs)("td",{className:"group relative flex border-r border-border h-8",style:{width:p.index===0?"40px":b.column.getSize()},children:[rs(b.column.columnDef.cell,b.getContext()),(0,a.jsx)(Oi,{value:b.getValue()})]},b.id)}),o?(0,a.jsx)("td",{style:{display:"flex",width:o}}):null]},t.id)}),Iw=33,Tw=({columnVirtualizer:e,table:t,tableName:r,tableContainerRef:s,virtualPaddingLeft:n,virtualPaddingRight:o})=>{const{rows:l}=t.getRowModel(),i=Qn({count:l.length,estimateSize:()=>Iw,getScrollElement:()=>s.current,overscan:5}),c=i.getVirtualItems(),d=e.getVirtualItems();return(0,a.jsx)("tbody",{style:{display:"grid",height:`${i.getTotalSize()}px`,position:"relative"},children:c.map(u=>{const h=l[u.index];return(0,a.jsx)(jw,{row:h,tableName:r,tableState:t.getState(),tableMeta:t.options.meta,virtualColumns:d,virtualPaddingLeft:n,virtualPaddingRight:o,virtualRow:u},h.id)})})},Rw=(0,f.memo)(Ew,(e,t)=>{const r=e.header.column,s=t.header.column;return!(r.getIsResizing()!==s.getIsResizing()||r.getSize()!==s.getSize()||e.label!==t.label)});function Ew({header:e,table:t,label:r}){const s=t._getDefaultColumnDef(),n=(0,f.useCallback)(()=>{t.setColumnSizing(o=>{const l={...o};return delete l[e.column.id],l})},[e.column.id,t]);return(0,a.jsx)("div",{role:"separator","aria-orientation":"vertical","aria-label":`Resize ${r} column`,"aria-valuenow":e.column.getSize(),"aria-valuemin":s.minSize,"aria-valuemax":s.maxSize,tabIndex:0,className:V("after:-translate-x-1/2 -right-px absolute top-0 z-50 h-full w-0.5 cursor-ew-resize touch-none select-none bg-border transition-opacity after:absolute after:inset-y-0 after:left-1/2 after:h-full after:w-[18px] after:content-[''] hover:bg-primary focus:bg-primary focus:outline-none",e.column.getIsResizing()?"bg-primary":"opacity-0 hover:opacity-100"),onDoubleClick:n,onMouseDown:e.getResizeHandler(),onTouchStart:e.getResizeHandler()})}var kw=({columnVirtualizer:e,headerGroup:t,virtualPaddingLeft:r,virtualPaddingRight:s,table:n})=>{const{table:o}=al.useParams(),l=ha(),[i,c]=(0,f.useState)(!1),[d,u]=(0,f.useState)(null),[h,m]=(0,f.useState)(!1),{deleteColumn:p}=Zd(),[,b]=ve(ce.COLUMN_NAME),[,w]=ve(ce.TABLE_STATE_KEYS.SORT),[,x]=ve(ce.TABLE_STATE_KEYS.ORDER),[,N]=ve(ce.TABLE_STATE_KEYS.CURSOR),[,C]=ve(ce.TABLE_STATE_KEYS.DIRECTION),S=e.getVirtualItems(),g=n.getState().columnSizingInfo.isResizingColumn,v=(0,f.useCallback)(T=>D=>{D===null?(b(null),w(null),x(null)):(b(T),w(T),x(D==="desc"?"desc":"asc")),N(null),C(null)},[b,w,x,N,C]),y=(0,f.useCallback)(T=>{u(T),m(!1),c(!0)},[]),R=(0,f.useCallback)(T=>{c(T),T||(u(null),m(!1))},[]),I=(0,f.useCallback)(async()=>{!d||!o||(await p({db:o,tableName:o,columnName:d,cascade:h}),c(!1),u(null),m(!1))},[d,o,p,h]),k=(0,f.useCallback)(()=>{c(!1),u(null),m(!1)},[]);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("tr",{className:V("flex w-fit bg-muted/40 border-b border-border items-center justify-between text-sm data-[state=open]:bg-accent/40 [&_svg]:size-4",g&&"pointer-events-none"),children:[r?(0,a.jsx)("th",{style:{display:"flex",width:r}}):null,S.map(T=>{const D=t.headers[T.index],_=D.column.columnDef.meta?.isPrimaryKey,O=D.column.columnDef.meta?.isForeignKey,F=D.column.columnDef.meta?.dataTypeLabel;return(0,a.jsx)("th",{className:"h-full flex z-100! relative",style:{display:"flex",width:T.index===0?"40px":D.getSize()},children:(0,a.jsx)("div",{className:V("relative w-full h-full flex items-center justify-between gap-2 text-sm hover:bg-accent/20 data-[state=open]:bg-accent/40 [&_svg]:size-4","border-r border-border",D.column.getCanSort()?"cursor-pointer select-none":""),children:T.index===0?rs(D.column.columnDef.header,D.getContext()):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(gn,{children:[(0,a.jsx)(vn,{asChild:!0,children:(0,a.jsxs)(B,{variant:"outline",className:"relative border-none w-full h-full bg-transparent! rounded-none justify-between",children:[(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[_&&(0,a.jsxs)(ir,{children:[(0,a.jsx)(ar,{asChild:!0,children:(0,a.jsx)("span",{className:"inline-flex",children:(0,a.jsx)(Vm,{size:20,className:"text-primary"})})}),(0,a.jsx)(or,{className:"text-[10px]",children:"primary key"})]}),O&&(0,a.jsxs)(ir,{children:[(0,a.jsx)(ar,{asChild:!0,children:(0,a.jsx)("span",{className:"inline-flex",children:(0,a.jsx)(Xn,{size:20,className:"text-primary"})})}),(0,a.jsx)(or,{className:"text-[10px]",children:"foreign key"})]}),rs(D.column.columnDef.header,D.getContext())]}),(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[F&&(0,a.jsx)("span",{className:"text-xs leading-none text-muted-foreground",children:F}),(0,a.jsx)("span",{className:"text-xs leading-none text-muted-foreground",children:{asc:(0,a.jsx)(us,{}),desc:(0,a.jsx)(ii,{})}[D.column.getIsSorted()]??null})]})]})}),(0,a.jsxs)(yn,{className:"w-44",align:"start",children:[!l&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(tu,{children:[(0,a.jsxs)($t,{onClick:()=>v(D.column.id)("asc"),children:[(0,a.jsx)(hp,{}),"Sort ascending"]}),(0,a.jsxs)($t,{onClick:()=>v(D.column.id)("desc"),children:[(0,a.jsx)(_m,{}),"Sort descending"]}),D.column.getIsSorted()&&(0,a.jsxs)($t,{onClick:()=>v(D.column.id)(null),children:[(0,a.jsx)(As,{}),"Remove sort"]})]}),(0,a.jsx)(ru,{})]}),(0,a.jsxs)($t,{variant:"destructive",disabled:l,onClick:()=>y(D.column.id),children:[(0,a.jsx)(li,{}),"Delete column"]})]})]}),D.column.getCanResize()&&(0,a.jsx)(Rw,{header:D,table:n,label:D.column.id})]})})},D.id)}),s?(0,a.jsx)("th",{style:{display:"flex",width:s}}):null]},t.id),(0,a.jsx)(Qr,{open:i,onOpenChange:R,children:(0,a.jsxs)(Jr,{children:[(0,a.jsxs)(Yr,{children:[(0,a.jsx)(Xr,{children:"Delete Column"}),(0,a.jsxs)(es,{children:['Are you sure you want to delete the column "',d,'"? This action cannot be undone and will permanently remove all data in this column.']})]}),(0,a.jsxs)("div",{className:"flex gap-2 py-2",children:[(0,a.jsx)(kr,{id:"cascade-delete",checked:h,onCheckedChange:T=>m(T===!0)}),(0,a.jsx)(me,{htmlFor:"cascade-delete",className:"text-xs text-muted-foreground cursor-pointer",children:"Drop with CASCADE (also remove dependent indexes, constraints, and foreign key references)"})]}),(0,a.jsxs)(Gr,{children:[(0,a.jsx)(Hr,{onClick:k,children:"Cancel"}),(0,a.jsx)(Zr,{variant:"destructive",onClick:I,children:"Delete"})]})]})})]})},Aw=({columnVirtualizer:e,table:t,virtualPaddingLeft:r,virtualPaddingRight:s})=>(0,a.jsx)("thead",{className:"h-9 grid sticky top-0 z-10 supports-backdrop-filter:backdrop-blur-sm",children:t.getHeaderGroups().map(n=>(0,a.jsx)(kw,{columnVirtualizer:e,headerGroup:n,table:t,virtualPaddingLeft:r,virtualPaddingRight:s},n.id))}),Ow=({table:e,tableName:t,pageKey:r})=>{const s=e.getVisibleLeafColumns(),n=(0,f.useRef)(null);(0,f.useLayoutEffect)(()=>{n.current?.scrollTo({top:0})},[r]);const o=Qn({count:s.length,estimateSize:d=>s[d].getSize(),getScrollElement:()=>n.current,horizontal:!0,overscan:3}),l=o.getVirtualItems();let i,c;return o&&l?.length&&(i=l[0]?.start??0,c=o.getTotalSize()-(l[l.length-1]?.end??0)),(0,a.jsx)("div",{className:"w-full flex-1 overflow-auto bg-background text-foreground",ref:n,style:{position:"relative"},children:(0,a.jsxs)("table",{style:{display:"grid"},className:"text-foreground",children:[(0,a.jsx)(Aw,{columnVirtualizer:o,table:e,virtualPaddingLeft:i,virtualPaddingRight:c}),(0,a.jsx)(Tw,{columnVirtualizer:o,table:e,tableName:t,tableContainerRef:n,virtualPaddingLeft:i,virtualPaddingRight:c})]})})},Dw=({table:e,tableName:t,pageKey:r,selectedRows:s,setRowSelection:n})=>(0,a.jsxs)("div",{className:V("flex-1 w-full flex flex-col overflow-hidden pb-9"),children:[(0,a.jsx)(Vh,{selectedRows:s,setRowSelection:n,tableName:t}),(0,a.jsx)(Ow,{table:e,tableName:t,pageKey:r}),(0,a.jsx)(zh,{tableName:t})]}),Mw=()=>(0,a.jsx)("div",{className:"size-full flex items-center justify-center",children:(0,a.jsx)(dn,{size:"size-7"})}),_w=()=>{const{clearRowDetails:e}=ls(),{closeOverlay:t}=je(),{status:r,proceed:s,reset:n}=wm({shouldBlockFn:()=>ls.getState().isDirty,withResolver:!0});return{isBlocked:r==="blocked",discardAndContinue:()=>{e(),t("tables.row-details"),s?.()},keepEditing:()=>n?.()}},Pw=()=>{const{isBlocked:e,discardAndContinue:t,keepEditing:r}=_w();return(0,a.jsx)(Qr,{open:e,onOpenChange:s=>{s||r()},children:(0,a.jsxs)(Jr,{children:[(0,a.jsxs)(Yr,{children:[(0,a.jsx)(Xr,{children:"Discard unsaved changes?"}),(0,a.jsx)(es,{children:"This record has unsaved changes. Leaving discards them. Continue?"})]}),(0,a.jsxs)(Gr,{children:[(0,a.jsx)(Hr,{children:"Keep editing"}),(0,a.jsx)(Zr,{onClick:t,children:"Discard changes"})]})]})})},Fw=({tableName:e})=>{const t=_r(),{tableData:r,pageKey:s,isLoadingTableData:n,errorTableData:o,refetchTableData:l}=va({tableName:e}),{tableCols:i,isLoadingTableCols:c,errorTableCols:d}=mt({tableName:e}),u=(0,f.useMemo)(()=>r?.data||[],[r?.data]),{table:h,selectedRows:m,setRowSelection:p,isEditingCell:b}=US({tableName:e,tableCols:i,tableDataRows:u}),w=h.getRowModel(),x=(0,f.useMemo)(()=>w.rows.map(N=>N.original),[w]);return(0,f.useEffect)(()=>()=>{ls.getState().clearRowDetails();const{closeOverlay:N}=je.getState();N("tables.row-change-primary-key"),N("tables.row-delete-record"),N("tables.row-discard-changes"),N("tables.row-details")},[e]),Vx({tableName:e,tableCols:i,tableDataRows:u,refetchTableData:l,isEditingCell:b}),n||c?(0,a.jsx)(Mw,{}):!r&&o||!i&&d?(0,a.jsx)(ww,{tableName:e,errorTableData:o,errorTableCols:d}):!r?.data||r.data.length===0?(0,a.jsx)(Cw,{tableName:e,selectedRows:m,setRowSelection:p}):t?.dataModel==="document"?(0,a.jsx)(dw,{tableName:e,rows:u}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(Dw,{table:h,tableName:e,pageKey:s,selectedRows:m,setRowSelection:p}),(0,a.jsx)(tC,{tableName:e,rows:x}),(0,a.jsx)(Pw,{})]})},Lw=Fw,vR=({tableName:e})=>(0,a.jsxs)("main",{className:"flex-1 flex flex-col overflow-hidden",children:[(0,a.jsx)(Lw,{tableName:e}),(0,a.jsx)(Ex,{tableName:e}),(0,a.jsx)(Fx,{tableName:e}),(0,a.jsx)(Mx,{tableName:e}),(0,a.jsx)(_x,{tableName:e}),(0,a.jsx)(Px,{tableName:e})]},e),zw=({index:e})=>{const[t,r]=(0,f.useState)(!1),{tablesList:s,isLoadingTablesList:n}=ou(),{control:o,watch:l,setValue:i,getValues:c}=Ge(),d=l(`fields.${e}.columnName`),u=()=>{const h=c("foreignKeys")||[];if(!h[e]){const m=[...h];m.push({columnName:"",referencedTable:"",referencedColumn:"",onUpdate:"NO ACTION",onDelete:"NO ACTION"}),i("foreignKeys",m)}};return(0,a.jsx)(Ot,{control:o,name:`foreignKeys.${e}`,render:({field:h})=>(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(me,{htmlFor:"referencedTable",children:"Select a table to reference to"}),(0,a.jsxs)(Mr,{modal:!0,onOpenChange:m=>{m&&u(),r(m)},open:t,children:[(0,a.jsx)(fs,{asChild:!0,children:(0,a.jsxs)(B,{"aria-expanded":t,"aria-controls":"referencedTable-listbox",className:"w-full justify-between border-input bg-background px-3 font-normal outline-none outline-offset-0 hover:bg-background focus-visible:outline-[3px]",id:"referencedTable",role:"combobox",variant:"outline",disabled:n,children:[(0,a.jsx)("span",{className:V("truncate",!h.value?.referencedTable&&"text-muted-foreground"),children:h.value?.referencedTable||"---"}),(0,a.jsx)(us,{"aria-hidden":"true",className:"shrink-0 text-muted-foreground/80",size:16})]})}),(0,a.jsx)(ur,{id:"referencedTable-listbox",align:"start",className:"w-full min-w-(--radix-popper-anchor-width) border-input p-0",children:(0,a.jsxs)(xi,{children:[(0,a.jsx)(Si,{placeholder:"Search table..."}),(0,a.jsxs)(Ci,{children:[(0,a.jsx)(wi,{children:"No table found."}),(0,a.jsx)(vr,{children:s?.map(m=>(0,a.jsxs)(Ae,{onSelect:()=>{h.onChange({...h.value,referencedTable:m.tableName}),i(`foreignKeys.${e}.columnName`,d),r(!1)},value:m.tableName,children:[m.tableName,h.value?.referencedTable===m.tableName&&(0,a.jsx)(Os,{className:"ml-auto",size:16})]},m.tableName))})]})]})})]})]})})},$w=({index:e})=>{const{closeOverlay:t,isOverlayOpen:r}=je(),{control:s}=Ge(),{remove:n}=Do({control:s,name:"foreignKeys"}),o=()=>{n(e),t(`table-builder.add-foreign-key-${e}`)};return(0,a.jsx)(rg,{open:r(`table-builder.add-foreign-key-${e}`),onOpenChange:l=>{l||t(`table-builder.add-foreign-key-${e}`)},children:(0,a.jsxs)(eg,{className:"max-w-lg!",children:[(0,a.jsx)(Xp,{children:(0,a.jsx)(sg,{children:"Add foreign key relationship"})}),(0,a.jsxs)("div",{className:"flex flex-col justify-between px-5 py-6 h-full flex-1",children:[(0,a.jsxs)("div",{className:"space-y-6 flex-1",children:[(0,a.jsx)(zw,{index:e}),(0,a.jsx)(yy,{index:e})]}),(0,a.jsx)(B,{type:"button",variant:"outline",size:"sm",onClick:o,children:(0,a.jsx)("span",{className:"text-xs",children:"Reset Foreign Key"})})]})]})})},ic=({index:e,onRemove:t,canRemove:r})=>{const{control:s}=Ge(),n=Ft({control:s,name:`fields.${e}.isPrimaryKey`});return(0,a.jsxs)("div",{className:"grid grid-cols-4 gap-4",children:[(0,a.jsx)(nu,{index:e}),(0,a.jsx)(ua,{index:e}),(0,a.jsx)(Di,{index:e}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(au,{index:e}),(0,a.jsx)(su,{index:e,isDisabled:!!n}),(0,a.jsx)("div",{className:"flex items-end justify-center",children:(0,a.jsx)(B,{type:"button",variant:"ghost",className:"size-9",onClick:t,disabled:!r,children:(0,a.jsx)(As,{className:"size-4"})})}),(0,a.jsx)($w,{index:e})]})]})},Vw=()=>{const{control:e}=Ge(),{fields:t,append:r,remove:s}=Do({control:e,name:"fields"}),{remove:n}=Do({control:e,name:"foreignKeys"}),o=Ft({control:e,name:"fields"}),l=()=>{r({columnName:"",columnType:"",defaultValue:"",isPrimaryKey:!1,isNullable:!0,isUnique:!1,isIdentity:!1,isArray:!1})},i=u=>{t.length>1&&(s(u),n(u))},c=t.reduce((u,h,m)=>(o?.[m]?.isPrimaryKey&&u.push({field:h,index:m}),u),[]),d=t.reduce((u,h,m)=>(o?.[m]?.isPrimaryKey||u.push({field:h,index:m}),u),[]);return(0,a.jsxs)("div",{className:"space-y-2",children:[c.length>1&&(0,a.jsx)(rt,{variant:"info",title:"Composite primary key selected",className:"mb-6"}),(0,a.jsxs)("div",{className:"grid grid-cols-4 px-2",children:[(0,a.jsx)(me,{className:"text-xs",children:"Column Name"}),(0,a.jsx)(me,{className:"text-xs",children:"Column Type"}),(0,a.jsx)(me,{className:"text-xs",children:"Default Value"}),(0,a.jsx)(me,{className:"text-xs",children:"Primary"})]}),(0,a.jsxs)("div",{className:"space-y-2",children:[c.length>0&&(0,a.jsx)("div",{className:"bg-primary/10 rounded-lg px-2 py-3 space-y-2",children:c.map(({field:u,index:h})=>(0,a.jsx)(ic,{index:h,onRemove:()=>i(h),canRemove:t.length>1},u.id))}),d.length>0&&(0,a.jsx)("div",{className:"space-y-2 px-2 py-3",children:d.map(({field:u,index:h})=>(0,a.jsx)(ic,{index:h,onRemove:()=>i(h),canRemove:t.length>1},u.id))})]}),(0,a.jsx)("div",{className:"border border-dashed border-input rounded-lg flex justify-center items-center p-6",children:(0,a.jsx)(B,{type:"button",variant:"secondary",size:"sm",onClick:l,children:"Add New Column"})})]})};function yR({className:e,...t}){return(0,a.jsx)("div",{"data-slot":"field-group",className:V("gap-4 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4 group/field-group @container/field-group flex w-full flex-col",e),...t})}var Bw=yd("data-[invalid=true]:text-destructive gap-2 group/field flex w-full",{variants:{orientation:{vertical:"flex-col [&>*]:w-full [&>.sr-only]:w-auto",horizontal:"flex-row items-center [&>[data-slot=field-label]]:flex-auto has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",responsive:"flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto @md/field-group:[&>[data-slot=field-label]]:flex-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px"}},defaultVariants:{orientation:"vertical"}});function bR({className:e,orientation:t="vertical",...r}){return(0,a.jsx)("div",{role:"group","data-slot":"field","data-orientation":t,className:V(Bw({orientation:t}),e),...r})}function xR({className:e,...t}){return(0,a.jsx)(me,{"data-slot":"field-label",className:V("has-data-checked:bg-primary/5 dark:has-data-checked:bg-primary/10 gap-2 group-data-[disabled=true]/field:opacity-50 has-[>[data-slot=field]]:rounded-sm has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-2 group/field-label peer/field-label flex w-fit leading-snug","has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",e),...t})}function SR({className:e,...t}){return(0,a.jsx)("p",{"data-slot":"field-description",className:V("text-muted-foreground text-left text-xs/relaxed [[data-variant=legend]+&]:-mt-1.5 leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance","last:mt-0 nth-last-2:-mt-1","[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",e),...t})}var Uw=f.memo(function({errors:t}){const r=[...new Map(t.map(s=>[s?.message,s])).values()];return r.length===1?(0,a.jsx)(a.Fragment,{children:r[0]?.message}):(0,a.jsx)("ul",{className:"ml-4 flex list-disc flex-col gap-1",children:r.map((s,n)=>s?.message&&(0,a.jsx)("li",{children:s.message},s?.message??n))})});function qw({className:e,children:t,errors:r,...s}){return t!=null||(r?.length??0)>0?(0,a.jsx)("div",{role:"alert","data-slot":"field-error",className:V("text-destructive text-xs/relaxed font-normal",e),...s,children:t??(r&&(0,a.jsx)(Uw,{errors:r}))}):null}var Ww=()=>{const{control:e,register:t,formState:{errors:r}}=Ge();return(0,a.jsx)(Ot,{control:e,name:"tableName",render:()=>(0,a.jsxs)("div",{className:"flex gap-24 px-2",children:[(0,a.jsx)(me,{htmlFor:"tableName",children:"Table Name"}),(0,a.jsxs)("div",{className:"flex-1 space-y-1",children:[(0,a.jsx)(Ke,{id:"tableName",...t("tableName",{required:"Table name is required"}),className:r.tableName?"border-destructive ring-destructive ring-1":""}),r.tableName&&(0,a.jsx)(qw,{errors:[r.tableName]})]})]})})},Kw=()=>{const{closeOverlay:e}=je(),t=St(),{selectedDatabase:r,dbType:s}=Me(),{mutateAsync:n,isPending:o}=ht({mutationFn:async i=>(await Bp(i,r)).data.data,onSuccess:async()=>{await Promise.all([t.invalidateQueries({queryKey:Ee.lists()}),t.invalidateQueries({queryKey:Ee.columns()})]),e("table-builder.create-table"),s&&cr.capture("table_created",{db_type:s})}});return{createTable:async(i,c)=>we.promise(n(i,c),{loading:"Creating table...",success:d=>d||"Table created successfully",error:d=>d.detail||d.message||"Failed to create table"}),isCreatingTable:o}},Hw=Cr({columnName:Vt().min(1,"Column name is required"),columnType:Vt().min(1,"Column type is required"),defaultValue:Vt(),isPrimaryKey:bt(),isNullable:bt(),isUnique:bt(),isIdentity:bt(),isArray:bt()}),Gw=Cr({columnName:Vt().min(1,"Column name is required"),referencedTable:Vt().min(1,"Referenced table is required"),referencedColumn:Vt().min(1,"Referenced column is required"),onUpdate:vl(["CASCADE","SET NULL","SET DEFAULT","RESTRICT","NO ACTION"]).default("NO ACTION"),onDelete:vl(["CASCADE","SET NULL","SET DEFAULT","RESTRICT","NO ACTION"]).default("NO ACTION")}),Yw=Cr({tableName:Vt().min(1,"Table name is required"),fields:xo(Hw).min(1,"At least one column is required"),foreignKeys:dg(e=>{if(Array.isArray(e))return e.filter(t=>t==null?!1:typeof t=="object"?t.columnName&&t.referencedTable&&t.referencedColumn:!1)},xo(Gw).optional())}),Jw={tableName:"",fields:[{columnName:"",columnType:"",defaultValue:"",isPrimaryKey:!1,isNullable:!0,isUnique:!1,isIdentity:!1,isArray:!1}],foreignKeys:void 0},Qw=()=>{const{closeOverlay:e,isOverlayOpen:t}=je(),{createTable:r,isCreatingTable:s}=Kw(),n=Ms({mode:"onSubmit",defaultValues:Jw,resolver:da(Yw)}),o=async c=>{const d={...c,foreignKeys:c.foreignKeys?.filter(u=>u===null?!0:u.columnName&&u.referencedTable&&u.referencedColumn)};try{await r(d,{onSuccess:()=>{n.reset()},onError:u=>{console.error("Error creating table:",u)}})}catch(u){console.error("Error creating table:",u)}},l=c=>{if(c.tableName?.message){we.error(c.tableName.message);return}if(c.fields&&Array.isArray(c.fields))for(const d of c.fields){if(d?.columnName?.message){we.error(d.columnName.message);return}if(d?.columnType?.message){we.error(d.columnType.message);return}}if(c.foreignKeys&&Array.isArray(c.foreignKeys))for(const d of c.foreignKeys){if(d?.columnName?.message){we.error(d.columnName.message);return}if(d?.referencedTable?.message){we.error(d.referencedTable.message);return}if(d?.referencedColumn?.message){we.error(d.referencedColumn.message);return}}we.error("Please check the form for errors")},i=()=>{n.reset(),e("table-builder.create-table")};return(0,a.jsx)(Ut,{title:"Create a new table",open:t("table-builder.create-table"),onOpenChange:c=>{c||i()},children:(0,a.jsx)(Ds,{...n,children:(0,a.jsxs)("form",{onSubmit:n.handleSubmit(o,l),className:"space-y-6",children:[(0,a.jsx)(Ww,{}),(0,a.jsx)(Vw,{}),(0,a.jsx)(Ai,{onCancel:i,isLoading:s})]})})})},lc="Select a table first",Xw="Not available for schemaless databases",Zw=()=>{const{pathname:e}=sd(),t=Am({strict:!1}).table??null,{dbType:r}=Me(),s=_r(),n=ha(),o=e.startsWith("/table/"),l=e.startsWith("/schema/");return{pathname:e,activeTable:t,dbType:r,isKeyValue:s?.dataModel==="key-value",isSchemaless:n,canCreateTable:!n,canEditRecords:!!t&&o,recordsHint:t?"Open the table data screen first":lc,hasIndexes:!!s?.indexes,canEditSchema:!!t&&l&&!n,schemaHint:n?Xw:t?"Open the table schema screen first":lc}},eN=()=>{const{openOverlay:e,closeOverlay:t,isOverlayOpen:r}=je(),[s,n]=(0,f.useState)("all"),[o,l]=(0,f.useState)(""),i=(0,f.useRef)(null),c=r("command-palette.root"),d=(0,f.useCallback)(w=>{if(w){e("command-palette.root");return}t("command-palette.root"),n("all"),l("")},[e,t]),u=(0,f.useCallback)(w=>{d(!1),w()},[d]),h=(0,f.useCallback)(()=>{n("tables"),l(""),setTimeout(()=>i.current?.focus(),0)},[]),m=(0,f.useCallback)(()=>{n("all"),l(""),setTimeout(()=>i.current?.focus(),0)},[]),p=(0,f.useCallback)(w=>{if(s==="all"&&w.startsWith(">")){h(),l(w.slice(1));return}if(s==="all"&&(w.toLowerCase()==="table "||w.toLowerCase()==="tables ")){h();return}l(w)},[s,h]),b=(0,f.useCallback)(w=>{w.key==="Backspace"&&o===""&&s==="tables"&&(w.preventDefault(),m())},[o,s,m]);return Ar("ctrl+k, meta+k",w=>{w.target?.closest?.(".monaco-editor")||(w.preventDefault(),d(!je.getState().isOverlayOpen("command-palette.root")))},{enableOnFormTags:!0,enableOnContentEditable:!0}),{open:c,mode:s,inputValue:o,inputRef:i,handleOpenChange:d,handleAction:u,handleInputChange:p,handleKeyDown:b,switchToAllMode:m,switchToTablesMode:h}};function tN(){const e=rd(),{openOverlay:t}=je(),{toggleSidebarOpen:r,toggleSidebarPinned:s,sidebar:n}=fn(),{toggleTheme:o,isDark:l}=nl(),{tablesList:i,isLoadingTablesList:c,errorTablesList:d}=ou(),{exportFile:u,isExportingFile:h}=by(),{copyTableSchema:m,isCopyingSchema:p}=xv(),{requestAssistant:b}=bv(),{open:w,mode:x,inputValue:N,inputRef:C,handleOpenChange:S,handleAction:g,handleInputChange:v,handleKeyDown:y,switchToAllMode:R,switchToTablesMode:I}=eN(),{pathname:k,activeTable:T,dbType:D,isKeyValue:_,isSchemaless:O,canCreateTable:F,canEditRecords:E,recordsHint:z,canEditSchema:G,schemaHint:fe,hasIndexes:Z}=Zw(),re=typeof navigator<"u"&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),Ne=$=>{g(()=>{D&&cr.capture("table_viewed",{db_type:D}),e({to:"/table/$table",params:{table:$},search:{}})})},L=$=>{g(()=>{b($),t("chat.assistant")})};return(0,a.jsxs)(vv,{open:w,onOpenChange:S,children:[(0,a.jsxs)("div",{className:"flex items-center border-b border-input px-2 gap-2 w-full",children:[x==="tables"&&(0,a.jsxs)("button",{type:"button",onClick:R,"aria-label":"Back to all commands",className:"flex items-center gap-1.5 h-8! rounded-md bg-primary/10 px-2.5 py-1 text-xs font-medium text-primary transition-all hover:bg-primary/20 shrink-0",children:[(0,a.jsx)(bo,{className:"size-3.5"}),(0,a.jsx)("span",{children:"Tables"}),(0,a.jsx)(oi,{className:"size-3 opacity-60"})]}),(0,a.jsx)(Si,{ref:C,placeholder:x==="all"?"Search commands... (type > for tables)":"Search tables...",value:N,onValueChange:v,onKeyDown:y,className:"border-0 px-0"})]}),(0,a.jsxs)(Ci,{children:[(0,a.jsx)(wi,{children:x==="tables"?"No tables found.":"No results found."}),x==="tables"&&!c&&!d&&i&&(0,a.jsx)(vr,{heading:"Tables",children:i.length===0?(0,a.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No tables in database"}):i.map($=>(0,a.jsxs)(Ae,{value:$.tableName,onSelect:()=>Ne($.tableName),children:[(0,a.jsx)(ja,{className:"mr-2 size-4 text-primary"}),(0,a.jsxs)("div",{className:"flex flex-1 items-center justify-between",children:[(0,a.jsx)("span",{className:"font-medium",children:$.tableName}),(0,a.jsxs)("span",{className:"text-xs text-muted-foreground",children:[$.rowCountEstimated&&"~",$.rowCount," ",$.rowCount===1?"row":"rows"]})]})]},$.tableName))}),x==="tables"&&c&&(0,a.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Loading tables..."}),x==="tables"&&d&&(0,a.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Failed to load tables."}),x==="all"&&(0,a.jsxs)(a.Fragment,{children:[!_&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(vr,{heading:"Quick Access",children:(0,a.jsxs)(Ae,{onSelect:I,keywords:["tables",">","go to table"],className:"group",children:[(0,a.jsx)(ai,{className:"mr-2 size-4 text-primary"}),(0,a.jsxs)("div",{className:"flex flex-1 items-center justify-between",children:[(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Search Tables"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Navigate to any table quickly"})]}),(0,a.jsx)(yv,{children:">"})]})]})}),(0,a.jsx)(Vs,{})]}),(0,a.jsxs)(vr,{heading:"Go to",children:[!_&&(0,a.jsxs)(Ae,{onSelect:()=>g(()=>e({to:"/"})),keywords:["go","navigate","home","tables"],children:[(0,a.jsx)(bo,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Go to Tables"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Open the tables overview"})]})]}),(0,a.jsxs)(Ae,{onSelect:()=>g(()=>e({to:"/runner"})),keywords:["go","navigate","sql","query","runner","editor"],children:[(0,a.jsx)(op,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Go to Query Runner"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Write and execute queries"})]})]}),!_&&(0,a.jsxs)(Ae,{disabled:!T||O,onSelect:()=>{if(!T||O)return;const $=T;g(()=>e({to:"/schema/$table",params:{table:$},search:{}}))},keywords:["go","navigate","schema","columns"],children:[(0,a.jsx)(zm,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Go to Schema"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:O?"Not available for schemaless databases":T?`View the schema of ${T}`:"Select a table first"})]})]}),Z&&(0,a.jsxs)(Ae,{disabled:!T,onSelect:()=>{if(!T)return;const $=T;g(()=>e({to:"/indexes/$table",params:{table:$},search:{}}))},keywords:["go","navigate","indexes","index"],children:[(0,a.jsx)(ul,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Go to Indexes"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:T?`View the indexes of ${T}`:"Select a table first"})]})]}),_&&(0,a.jsxs)(Ae,{onSelect:()=>g(()=>e({to:"/browser"})),keywords:["go","navigate","redis","browser","keys"],children:[(0,a.jsx)(ja,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Go to Redis Browser"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Browse keys across logical databases"})]})]})]}),(0,a.jsx)(Vs,{}),(0,a.jsxs)(vr,{heading:"AI Assistant",children:[(0,a.jsxs)(Ae,{onSelect:()=>g(()=>t("chat.assistant")),keywords:["ai","assistant","chat","help"],children:[(0,a.jsx)(Dm,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Chat with AI Assistant"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Ask questions about your database"})]})]}),(0,a.jsxs)(Ae,{onSelect:()=>L("Generate a query for this database. Ask me for the goal if it is unclear."),keywords:["ai","generate","sql","query","write"],children:[(0,a.jsx)(np,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Generate SQL with AI"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create queries using natural language"})]})]}),(0,a.jsxs)(Ae,{disabled:!T||O,onSelect:()=>{!T||O||L(`Explain the schema of table "${T}": what each column stores and how it relates to other tables.`)},keywords:["ai","explain","schema","table","understand"],children:[(0,a.jsx)(Gm,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Explain Table Schema"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:O?"Not available for schemaless databases":T?`Understand the structure of ${T} with AI`:"Select a table first"})]})]})]}),(0,a.jsx)(Vs,{}),(0,a.jsxs)(vr,{heading:"Database Actions",children:[F&&(0,a.jsxs)(Ae,{onSelect:()=>g(()=>t("table-builder.create-table")),keywords:["create","new","table"],children:[(0,a.jsx)(Ln,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Create New Table"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Design and create a new database table"})]})]}),_&&(0,a.jsxs)(Ae,{onSelect:()=>g(()=>{k.startsWith("/browser")||e({to:"/browser"}),t("redis-browser.create-key")}),keywords:["create","new","redis","key"],children:[(0,a.jsx)(nd,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Create Redis Key"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Add a new key to the selected database"})]})]}),!_&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(Ae,{disabled:!E,onSelect:()=>g(()=>t("records.add-record")),keywords:["add","new","row","record","insert"],children:[(0,a.jsx)(Ln,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Add New Row"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:E?`Insert a new record into ${T}`:z})]})]}),(0,a.jsxs)(Ae,{disabled:!E,onSelect:()=>g(()=>t("records.bulk-insert")),keywords:["bulk","insert","import","csv","excel","json"],children:[(0,a.jsx)(lp,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Bulk Insert Records"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:E?`Import many records into ${T}`:z})]})]}),(0,a.jsxs)(Ae,{disabled:!G,onSelect:()=>g(()=>t("schema.add-column")),keywords:["add","new","column","schema"],children:[(0,a.jsx)(cp,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Add Column"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:G?`Add a column to ${T}`:fe})]})]}),Z&&(0,a.jsxs)(Ae,{disabled:!T,onSelect:()=>{if(!T)return;const $=T;g(()=>{k.startsWith("/indexes/")||e({to:"/indexes/$table",params:{table:$},search:{}}),t("indexes.create-index")})},keywords:["create","add","new","index","indexes"],children:[(0,a.jsx)(ul,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Create Index"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:T?`Create an index on ${T}`:"Select a table first"})]})]}),(0,a.jsxs)(Ae,{disabled:!T||h,onSelect:()=>{if(!T)return;const $=T;g(()=>{u({tableName:$,format:"csv"}).catch(()=>{})})},keywords:["export","download","csv"],children:[(0,a.jsx)(fl,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Export Table as CSV"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:T?`Download ${T} as a CSV file`:"Select a table first"})]})]}),(0,a.jsxs)(Ae,{disabled:!T||h,onSelect:()=>{if(!T)return;const $=T;g(()=>{u({tableName:$,format:"json"}).catch(()=>{})})},keywords:["export","download","json"],children:[(0,a.jsx)(fl,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Export Table as JSON"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:T?`Download ${T} as a JSON file`:"Select a table first"})]})]}),(0,a.jsxs)(Ae,{disabled:!T||p||O,onSelect:()=>{if(!T||O)return;const $=T;g(()=>{m($).catch(()=>{})})},keywords:["copy","schema","ddl","clipboard"],children:[(0,a.jsx)(ni,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Copy Table Schema"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:O?"Not available for schemaless databases":T?`Copy the schema of ${T} to the clipboard`:"Select a table first"})]})]})]}),(0,a.jsxs)(Ae,{onSelect:()=>g(()=>{window.location.reload()}),keywords:["refresh","reload","restart"],children:[(0,a.jsx)(fp,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Reload Application"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Reload all tables and data"})]})]})]}),(0,a.jsx)(Vs,{}),(0,a.jsxs)(vr,{heading:"View & Settings",children:[(0,a.jsxs)(Ae,{onSelect:()=>g(r),keywords:["sidebar","show","hide","toggle","view"],children:[(0,a.jsx)(Fm,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsxs)("span",{children:[n.isOpen?"Hide":"Show"," Sidebar"]}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Toggle sidebar visibility"})]})]}),(0,a.jsxs)(Ae,{onSelect:()=>g(s),keywords:["sidebar","pin","unpin"],children:[n.isPinned?(0,a.jsx)(dp,{className:"mr-2 size-4"}):(0,a.jsx)(Mm,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsxs)("span",{children:[n.isPinned?"Unpin":"Pin"," Sidebar"]}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Keep sidebar always visible"})]})]}),(0,a.jsxs)(Ae,{onSelect:()=>g(o),keywords:["theme","dark","light","mode","appearance"],children:[l?(0,a.jsx)(ep,{className:"mr-2 size-4"}):(0,a.jsx)(Um,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsxs)("span",{children:["Switch to ",l?"Light":"Dark"," Mode"]}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Toggle the application theme"})]})]}),(0,a.jsxs)(Ae,{onSelect:()=>g(()=>t("settings.app")),keywords:["settings","preferences","configure","options"],children:[(0,a.jsx)(od,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:"Settings & Preferences"}),(0,a.jsx)("span",{className:"text-xs text-muted-foreground",children:"Configure application settings"})]})]})]}),!_&&!c&&!d&&i&&i.length>0&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(Vs,{}),(0,a.jsxs)(vr,{heading:"Recent Tables",children:[i.slice(0,5).map($=>(0,a.jsxs)(Ae,{value:$.tableName,keywords:["table","recent",$.tableName],onSelect:()=>Ne($.tableName),children:[(0,a.jsx)(ja,{className:"mr-2 size-4"}),(0,a.jsxs)("div",{className:"flex flex-col",children:[(0,a.jsx)("span",{children:$.tableName}),(0,a.jsxs)("span",{className:"text-xs text-muted-foreground",children:[$.rowCountEstimated&&"~",$.rowCount," ",$.rowCount===1?"row":"rows"]})]})]},$.tableName)),i.length>5&&(0,a.jsx)(Ae,{onSelect:I,className:"text-muted-foreground",children:(0,a.jsxs)("span",{className:"text-xs",children:["+",i.length-5," more tables — press"," ",(0,a.jsx)(et,{className:"rounded border bg-muted px-1 py-0.5 font-mono text-[10px]",children:">"})," ","to see all"]})})]})]})]})]}),(0,a.jsxs)("div",{"aria-hidden":"true",className:"flex items-center gap-3 border-t border-border px-3 py-2 text-[11px] text-muted-foreground",children:[(0,a.jsxs)("span",{className:"flex items-center gap-1",children:[(0,a.jsx)(et,{children:"↑"}),(0,a.jsx)(et,{children:"↓"})," to navigate"]}),(0,a.jsxs)("span",{className:"flex items-center gap-1",children:[(0,a.jsx)(et,{children:"↵"})," to select"]}),(0,a.jsxs)("span",{className:"flex items-center gap-1",children:[(0,a.jsx)(et,{children:"esc"})," to close"]}),(0,a.jsxs)("span",{className:"ml-auto flex items-center gap-1",children:[(0,a.jsx)(et,{children:re?"⌘":"Ctrl"}),(0,a.jsx)(et,{children:"K"})," to toggle"]})]})]})}function Bh(){return{id:"memory",label:"Session only (not saved)",persistent:!1,warning:"Keys stay in memory for this tab only. They are not saved across reloads.",load:()=>({}),save:()=>{},clear:()=>{}}}var rN=/^[a-z][a-z0-9-]{0,63}$/,sN="x-byok-";function zt(e){return typeof e=="string"&&rN.test(e)}function cc(e){if(!zt(e))throw new Error(`Invalid BYOK provider id: ${e}`);return`${sN}${e}`}function nN(e){if(typeof e!="object"||e===null||!("error"in e))return!1;const t=e.error;return!(typeof t!="object"||t===null||!("type"in t)||t.type!=="byok_missing"||!("provider"in t)||typeof t.provider!="string"||!zt(t.provider)||!("message"in t)||typeof t.message!="string")}var Uo=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name="ByokMissingError",this.provider=e}},Hn=class extends Error{provider;reason;constructor(e,t){super(t==="locked"?`${e} key is locked`:`Missing ${e} API key`),this.name="ByokBlockedError",this.provider=e,this.reason=t}},Uh=class extends Error{constructor(){super("BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider."),this.name="ByokUnresolvedProviderError"}};function En(e){return e.length<=4?"••":e.slice(-4)}var aN={status:{},locked:!1,prompt:null,storageError:null},qh=new WeakMap;function oN(e){const t=Object.entries(e.keys()).filter(s=>!!s[1]).map(s=>s[0]).filter(zt);if(t.length===1)return t[0];const r=qh.get(e)??[];if(r.length===1)return r[0]}function $r(e){if(!zt(e))throw new Error(`Invalid BYOK provider id: ${e}`);return e}function kn(e,t){return e instanceof Error&&e.message.length>0?e.message:t}function iN(e){if(typeof DOMException<"u"&&e instanceof DOMException&&e.name==="NotAllowedError")return!0;if(e instanceof Error){if(e.name==="NotAllowedError")return!0;const t=e.message.toLowerCase();return t.includes("cancelled")||t.includes("not allowed")}return!1}function dc(e){if(typeof e!="object"||e===null)return{};const t={};for(const[r,s]of Object.entries(e))zt(r)&&typeof s=="string"&&s.length>0&&(t[r]=s);return t}var lN=class{storage;#e={};#t={};#r;#s=null;#l=!1;#i={};#u={};#c=new Set;#d;#a=null;#o;constructor(e={}){this.storage=e.storage??Bh();const t=[];for(const r of e.providers??[]){const s=$r(r.id);t.push(s),r.with?.length&&(this.#u[s]=r.with.map(n=>$r(n.id)))}qh.set(this,t),this.#r=!!this.storage.unlockable,this.#d=this.#f(),this.#o=this.#g()}ready=()=>this.#o;subscribe=e=>(this.#c.add(e),()=>{this.#c.delete(e)});getSnapshot=()=>this.#d;#f(){return{status:{...this.#t},locked:this.#r,prompt:this.#s,storageError:this.#a}}keys(){return{...this.#e}}request(e,t){this.#s={provider:$r(e),reason:t},this.#n()}setServerCoverage(e){if(typeof e=="boolean"){this.#l=e,this.#i={};return}this.#l=!1,this.#i={...this.#i,...e}}#m(e){return this.#l||this.#i[e]===!0}#h(e){return[e,...this.#u[e]??[]]}headers(e){const t={};if(e){$r(e);for(const r of this.#h(e)){const s=this.#e[r];s&&(t[cc(r)]=s)}return t}for(const[r,s]of Object.entries(this.#e))s&&(t[cc(r)]=s);return t}async prepare(e){if(await this.#o,this.storage.unlockable&&this.#r&&await this.unlock(),!!e){$r(e);for(const t of this.#h(e))if(!(this.#e[t]||this.#m(t)))throw this.request(t,"missing"),new Hn(t,"missing")}}async update(e,t){await this.#o;let r,s;if(t===void 0){if(!this.#s)throw new Error("byok.update(key) cannot run when prompt is null");r=this.#s.provider,s=e}else r=$r(e),s=t;if(s=s.trim(),s.length===0)throw new Error("BYOK key must be non-empty");this.storage.unlockable&&this.#r&&await this.unlock();const n=this.#e,o={...this.#t},l=this.#r,i=this.#s,c=this.#a,d={...this.#e,[r]:s};try{await this.storage.save(d)}catch(u){throw this.#e=n,this.#t=o,this.#r=l,this.#s=i,this.#a=c,this.#t[r]={state:"error",masked:En(s),message:kn(u,`Failed to persist ${r} key`)},this.#n(),u}this.#e=d,this.#t[r]={state:"set",masked:En(s)},this.#r=!1,this.#s=null,this.#a=null,this.#n()}async clear(e){if(await this.#o,e){$r(e),this.storage.unlockable&&this.#r&&await this.unlock();const o=this.#e,l={...this.#t},i={...this.#e};delete i[e];try{await this.storage.save(i)}catch(c){throw this.#e=o,this.#t=l,this.#n(),c}this.#e=i,delete this.#t[e],this.#n();return}const t=this.#e,r=this.#t,s=this.#r,n=this.#s;try{await this.storage.clear()}catch(o){throw this.#e=t,this.#t=r,this.#r=s,this.#s=n,this.#n(),o}this.#e={},this.#t={},this.#r=!1,this.#s=null,this.#a=null,this.#n()}async unlock(){if(await this.#o,!!this.storage.unlockable)try{const e=dc(await this.storage.load());this.#e={...e,...this.#e};for(const[t,r]of Object.entries(e)){if(!zt(t)||!r)continue;const s=this.#t[t];(!s||s.state==="locked")&&(this.#t[t]={state:"set",masked:En(r)})}this.#r=!1,this.#a=null,this.#n()}catch(e){if(iN(e)){const t=this.#p();if(t)throw this.request(t,"locked"),new Hn(t,"locked")}throw this.#a=kn(e,"Failed to unlock keyring"),this.#n(),e instanceof Error?e:new Error(String(e))}}#p(){if(this.#s&&zt(this.#s.provider))return this.#s.provider;for(const[e,t]of Object.entries(this.#t))if(t?.state==="locked"&&zt(e))return e}async#g(){if(this.storage.unlockable){if(!this.storage.peek)return;try{const e=await this.storage.peek();for(const[t,r]of Object.entries(e))!zt(t)||this.#t[t]||(this.#t[t]={state:"locked",masked:r||"••"});this.#r=Object.keys(e).length>0,this.#a=null,this.#n()}catch(e){this.#a=kn(e,"Failed to read keyring"),this.#n()}return}try{const e=dc(await this.storage.load());this.#e={...e,...this.#e};for(const[t,r]of Object.entries(e))!zt(t)||!r||(this.#t[t]={state:"set",masked:En(r)});this.#a=null,this.#n()}catch(e){this.#a=kn(e,"Failed to read keyring"),this.#n()}}#n(){this.#d=this.#f();for(const e of this.#c)e()}};function cN(e={}){return new lN(e)}var nn=cN({storage:Bh()});nn.setServerCoverage({gemini:!0});var qo=class extends Error{missingFeature;constructor(e){super(dN(e)),this.name="UnsupportedResponseStreamError",this.missingFeature=e}};function dN(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function uN(e){if(!e.body)throw new qo("Response.body");if(typeof e.body.getReader!="function")throw new qo("Response.body.getReader");return e.body.getReader()}function fN(){if(typeof globalThis.TextDecoder!="function")throw new qo("TextDecoder");return new globalThis.TextDecoder}function hN(e){if(!e.startsWith("data:"))return e;const t=e.slice(5);return t.startsWith(" ")?t.slice(1):t}function uc(e){if(e instanceof Date)return Number.isNaN(e.getTime())?void 0:e;if(typeof e!="string")return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function mN(e){const t=uc(e.createdAt),r=e.parts.map(o=>{if(o.type!=="tool-result")return o;const l=uc(o.createdAt),{createdAt:i,...c}=o;return l?{...c,createdAt:l}:c}),{createdAt:s,...n}=e;return t?{...n,parts:r,createdAt:t}:{...n,parts:r}}function Wo(e){return e.map(mN)}function fc(e){return Object.keys(e).length>0?e:void 0}function Wh(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)&&"promptTokens"in e}function pN(e,t){return Wh(e)?e:Array.isArray(e)?hc(e,t):hc(void 0,t)}function hc(e,t){const r=e?.[0];if(r==null&&t==null)return;const{promptTokensDetails:s,completionTokensDetails:n,...o}=t??{},l=fc({...r?.cachedInputTokens!==void 0?{cachedTokens:r.cachedInputTokens}:{},...s}),i=fc({...r?.reasoningTokens!==void 0?{reasoningTokens:r.reasoningTokens}:{},...n});return{promptTokens:r?.inputTokens??0,completionTokens:r?.outputTokens??0,totalTokens:r?.totalTokens??0,...o,...l!==void 0?{promptTokensDetails:l}:{},...i!==void 0?{completionTokensDetails:i}:{}}}function mc(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Kh(e,t){if(t==null)return e;if(e==null)return{...t};const r={...e,...t};return mc(e.tanstack)&&mc(t.tanstack)&&(r.tanstack={...e.tanstack,...t.tanstack}),r}function Ve(e){if(e==null)return;const t="metadata"in e?e.metadata:void 0,r=(t!=null&&typeof t=="object"&&!Array.isArray(t)?t:e).tanstack;if(!(r==null||typeof r!="object"||Array.isArray(r)))return r}function Hh(e,t){const r=e.metadata,s=Ve(e)??{};return{...e,metadata:{...r??{},tanstack:{...s,...t}}}}var An=(function(e){return e.TEXT_MESSAGE_START="TEXT_MESSAGE_START",e.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",e.TEXT_MESSAGE_END="TEXT_MESSAGE_END",e.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.THINKING_START="THINKING_START",e.THINKING_END="THINKING_END",e.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",e.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",e.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",e.STATE_SNAPSHOT="STATE_SNAPSHOT",e.STATE_DELTA="STATE_DELTA",e.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",e.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",e.ACTIVITY_DELTA="ACTIVITY_DELTA",e.RAW="RAW",e.CUSTOM="CUSTOM",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.STEP_STARTED="STEP_STARTED",e.STEP_FINISHED="STEP_FINISHED",e.REASONING_START="REASONING_START",e.REASONING_MESSAGE_START="REASONING_MESSAGE_START",e.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",e.REASONING_MESSAGE_END="REASONING_MESSAGE_END",e.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",e.REASONING_END="REASONING_END",e.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",e})({}),gN=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function rr(e,t){return e>>>t|e<<32-t}function vN(e){const t=new TextEncoder().encode(e),r=t.length*8,s=t.length+1,n=s+(56-s%64+64)%64+8,o=new Uint8Array(n);o.set(t),o[t.length]=128;const l=new DataView(o.buffer);l.setUint32(n-8,Math.floor(r/4294967296)),l.setUint32(n-4,r>>>0);let i=1779033703,c=3144134277,d=1013904242,u=2773480762,h=1359893119,m=2600822924,p=528734635,b=1541459225;const w=new Uint32Array(64);for(let N=0;N<n;N+=64){for(let T=0;T<16;T++)w[T]=l.getUint32(N+T*4);for(let T=16;T<64;T++){const D=w[T-15]??0,_=w[T-2]??0,O=rr(D,7)^rr(D,18)^D>>>3,F=rr(_,17)^rr(_,19)^_>>>10;w[T]=(w[T-16]??0)+O+(w[T-7]??0)+F>>>0}let C=i,S=c,g=d,v=u,y=h,R=m,I=p,k=b;for(let T=0;T<64;T++){const D=rr(y,6)^rr(y,11)^rr(y,25),_=y&R^~y&I,O=k+D+_+(gN[T]??0)+(w[T]??0)>>>0,F=(rr(C,2)^rr(C,13)^rr(C,22))+(C&S^C&g^S&g)>>>0;k=I,I=R,R=y,y=v+O>>>0,v=g,g=S,S=C,C=O+F>>>0}i=i+C>>>0,c=c+S>>>0,d=d+g>>>0,u=u+v>>>0,h=h+y>>>0,m=m+R>>>0,p=p+I>>>0,b=b+k>>>0}const x=N=>(N>>>0).toString(16).padStart(8,"0");return x(i)+x(c)+x(d)+x(u)+x(h)+x(m)+x(p)+x(b)}function yN(e){return`sha256:${vN(e)}`}function Ko(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!="object")throw new TypeError("Interrupt values must be JSON-compatible.");if(t.has(e))throw new TypeError("Interrupt values must not cycle.");if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new TypeError("Interrupt values must use plain JSON objects.");t.add(e);let r;if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++)s.push(Ko(e[n],t));r=`[${s.join(",")}]`}else{const s=e;r=`{${Object.keys(s).sort().map(n=>`${JSON.stringify(n)}:${Ko(s[n],t)}`).join(",")}}`}return t.delete(e),r}function cs(e){return Ko(e,new WeakSet)}function ds(e,t=yN){if(typeof e!="string")throw new TypeError("Interrupt digests require canonical JSON text.");return t(e)}function Gh(e){e===null||typeof e!="object"||Object.isFrozen(e)||(Object.values(e).forEach(Gh),Object.freeze(e))}function Qe(e){const t=JSON.parse(cs(e));return Gh(t),t}function bN(e){const t=[...e].sort((n,o)=>n.interruptId.localeCompare(o.interruptId)),r=Qe(t),s=cs(r);return Object.freeze({resolutions:r,canonicalResolutions:s,fingerprint:ds(s)})}function pc(e){const t={};for(const[r,s]of Object.entries(e))r!=="$schema"&&(t[r]=s);return t}function Yh(e){return(typeof e=="object"||typeof e=="function")&&e!==null}function Cn(e){if(!Yh(e)||!("~standard"in e))return!1;const t=e["~standard"];return typeof t!="object"||t===null||!("version"in t)||t.version!==1||!("jsonSchema"in t)||typeof t.jsonSchema!="object"||t.jsonSchema===null||!("input"in t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function Lr(e){return Yh(e)&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"version"in e["~standard"]&&e["~standard"].version===1&&"validate"in e["~standard"]&&typeof e["~standard"].validate=="function"}function xN(e){return Object.keys(e).length>0?e:void 0}function gc(e){if(Array.isArray(e)){const r=e.map(n=>Gn(n,n.required||[])),s=r.map(n=>n.nullWidening??{});return{schema:r.map(n=>n.schema),itemMap:s.some(n=>Object.keys(n).length>0)?s:void 0}}const t=Gn(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function Gn(e,t=[]){const r={...e},s={};if(r.type==="object"&&r.properties){const n={...r.properties},o=Object.keys(n),l={};for(const i of o){const c=n[i];if(!c)continue;const d=!t.includes(i);let u=!1,h;if(c.type==="object"&&c.properties){const m=Gn(c,c.required||[]);n[i]=d?{...m.schema,type:["object","null"]}:m.schema,u=d,h=m.nullWidening}else if(c.type==="array"&&c.items){const m=gc(c.items);n[i]={...c,items:m.schema,...d?{type:["array","null"]}:{}},u=d,h=m.itemMap?{items:m.itemMap}:void 0}else d&&(c.type&&!Array.isArray(c.type)?(n[i]={...c,type:[c.type,"null"]},u=!0):Array.isArray(c.type)&&!c.type.includes("null")&&(n[i]={...c,type:[...c.type,"null"]},u=!0));(u||h)&&(l[i]={...h??{},...u?{widened:!0}:{}})}r.properties=n,r.required=o,r.additionalProperties=!1,Object.keys(l).length>0&&(s.properties=l)}if(r.type==="array"&&r.items){const n=gc(r.items);r.items=n.schema,n.itemMap&&(s.items=n.itemMap)}return{schema:r,nullWidening:xN(s)}}function SN(e){if(Cn(e)){const t=pc(e["~standard"].jsonSchema.input({target:"draft-07"}));return"properties"in t&&!t.type&&(t.type="object"),t.type==="object"&&!("properties"in t)&&(t.properties={}),t.type==="object"&&!("required"in t)&&(t.required=[]),t}if(Lr(e))throw new Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e!="object"?e:pc(e)}function Ho(e,t={}){if(!e)return;const{forStructuredOutput:r=!1}=t;if(!r&&!Cn(e)&&!Lr(e))return e;const s=SN(e);return!s||typeof s!="object"||!r?s:Gn(s,s.required||[]).schema}var CN=class extends Error{name="StandardSchemaValidationError";issues;constructor(e){super(`Validation failed: ${e.map(t=>t.message||"Validation failed").join(", ")}`),this.issues=e}};function wN(e,t){if(!Lr(e))return t;const r=e["~standard"].validate(t);if(r instanceof Promise)throw new Error("Schema validation returned a Promise. Use validateWithStandardSchema for async validation.");if(!r.issues)return r.value;throw new CN(r.issues)}var NN=new Set(["$schema","$id","$ref","$defs","type","properties","required","additionalProperties","items","oneOf","anyOf","allOf","enum","const","format","minimum","maximum","minLength","maxLength","pattern"]);function Jh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function ol(e){return Jh(e)&&Object.keys(e).some(t=>NN.has(t))}function jN(e){return Lr(e)||Cn(e)||ol(e)}function IN(e){if(!Jh(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>r==="approve"||r==="reject")&&t.every(r=>jN(e[r]))}function TN(e){const t={};for(const[r,s]of Object.entries(e))t[r]=s;return t}function tn(e){if(Lr(e)){const t=Cn(e)?TN(e["~standard"].jsonSchema.input({target:"draft-2020-12"})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(ol(e))return{source:e,jsonSchema:e};throw new TypeError("Expected a supported SchemaInput.")}function vc(e){const t={approved:{const:e.approved}},r=["approved"];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},r.push("payload")),{type:"object",properties:t,required:r,additionalProperties:!1}}function RN(e,t){const r=t===void 0?null:tn(t);let s=null,n=null;if(e!==void 0)if(Lr(e)||ol(e))s=tn(e),n=s;else if(IN(e))s=e.approve===void 0?null:tn(e.approve),n=e.reject===void 0?null:tn(e.reject);else throw new TypeError("approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.");const o={oneOf:[vc({approved:!0,payload:s,inputSchema:r}),vc({approved:!1,payload:n,inputSchema:null})]},l=cs(o),i=cs({approve:s?.jsonSchema??null,reject:n?.jsonSchema??null});return{branches:{approve:s,reject:n},responseSchema:o,responseSchemaHash:ds(l),approvalSchemaHash:ds(i)}}function yc(e){if(e===void 0)return ds("undefined");const t=tn(e).jsonSchema??{standardValidator:"unserialized"};return ds(cs(t))}var Sa="tanstack:interruptBinding",Qh=Sa;function Yn(e){return e&&typeof e=="object"?e:null}function yt(e,t){return typeof e[t]=="string"?e[t]:void 0}function EN(e){const t=e.v;return t===void 0?!0:t===1}function Xh(e){const t=Yn(e.metadata),r=t?Yn(t[Qh]):null;if(!r||yt(r,"interruptId")!==e.id||!EN(r))return;const s=yt(r,"kind"),n=yt(r,"interruptId"),o=yt(r,"responseSchemaHash"),l=yt(r,"expiresAt");if(!n||o===""||l!==void 0&&!Number.isFinite(Date.parse(l)))return;const i=1;if(s==="generic"){const u=yt(r,"definitionId"),h=yt(r,"key"),m=r.batchIndex,p=yt(r,"payloadSchemaHash");return(u!==void 0||h!==void 0||m!==void 0||p!==void 0)&&(!u||!h||typeof m!="number"||!Number.isInteger(m)||m<0)?void 0:{v:i,kind:s,interruptId:n,...o?{responseSchemaHash:o}:{},...l?{expiresAt:l}:{},...u?{definitionId:u}:{},...h?{key:h}:{},...typeof m=="number"?{batchIndex:m}:{},...p?{payloadSchemaHash:p}:{}}}if(!o)return;const c=yt(r,"toolName"),d=yt(r,"toolCallId");if(!(!c||!d)){if(s==="client-tool-execution"){const u=yt(r,"outputSchemaHash");return u?{v:i,kind:s,interruptId:n,toolName:c,toolCallId:d,outputSchemaHash:u,responseSchemaHash:o,...l?{expiresAt:l}:{}}:void 0}if(s==="tool-approval"){const u=yt(r,"inputSchemaHash"),h=yt(r,"approvalSchemaHash");return!u||!h?void 0:{v:i,kind:s,interruptId:n,toolName:c,toolCallId:d,originalArgs:r.originalArgs,inputSchemaHash:u,approvalSchemaHash:h,responseSchemaHash:o,...l?{expiresAt:l}:{}}}}}function kN(e){const t=Xh(e);if(!t)return;const r=Yn(e.metadata),s=r?Yn(r[Qh]):null;if(!s)return;const n=yt(s,"interruptedRunId"),o=s.generation;if(!(!n||typeof o!="number"||!Number.isInteger(o)||o<0))return{...t,interruptedRunId:n,generation:o}}var AN="tanstack:interruptPayload";function ON(e,t){if(!Cn(e))throw new TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{const r=e["~standard"].jsonSchema.input({target:"draft-07"});if(r===void 0)throw new TypeError("The exported schema is undefined.");if(typeof r=="function")throw new TypeError("The exported schema must not be a function.");if(Array.isArray(r))throw new TypeError("The exported schema must be a plain JSON object.");if(!r||typeof r!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(r)))throw new TypeError("The exported schema must be a plain JSON object.");const s={};for(const[n,o]of Object.entries(r))n!=="$schema"&&(s[n]=o);return{json:s,canonicalJson:cs(s)}}catch(r){throw new TypeError(`${t} could not export compatible JSON Schema: ${r instanceof Error?r.message:String(r)}`)}}function DN(e){return ds(ON(e,"Interrupt schema").canonicalJson)}var MN="tanstack:interruptContinuation";function _N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function PN(e){return{[MN]:e}}function FN(e){const t=Xh(e);if(t?.kind!=="generic"||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;const r=_N(e.metadata)?e.metadata:void 0,s=r!==void 0&&Object.prototype.hasOwnProperty.call(r,"tanstack:interruptPayload");return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??"",...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{},...t.responseSchemaHash!==void 0?{responseSchemaHash:t.responseSchemaHash}:{},...t.payloadSchemaHash!==void 0?{payloadSchemaHash:t.payloadSchemaHash}:{},...s?{payload:r[AN]}:{}}}var LN=new Set(["text","image","audio","video","document"]);function zN(e){if(typeof e!="object"||e===null)return!1;const t=e;if(typeof t.type!="string"||!LN.has(t.type))return!1;if(t.type==="text")return typeof t.content=="string";const r=t.source;if(typeof r!="object"||r===null)return!1;const s=r;return typeof s.value!="string"?!1:s.type==="data"?typeof s.mimeType=="string":s.type==="url"}function Go(e){return Array.isArray(e)&&e.length>0&&e.every(zN)}function il(e){return typeof e=="string"||Go(e)?e:JSON.stringify(e)}function $N(e){const t=e?.metadata;return typeof t=="object"&&t!==null&&t.providerExecuted===!0?t:null}function Zh(e){return $N(e)!==null}function io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function VN(e){return e.type==="text"||e.type==="image"||e.type==="audio"||e.type==="video"||e.type==="document"}function BN(e){try{return JSON.stringify(e)??""}catch{return""}}function bc(e){return typeof e=="string"&&e!==""?e:void 0}function UN(e){if("encryptedValue"in e){const t=bc(e.encryptedValue);if(t!==void 0)return t}return bc(Ve(e)?.signature)}function em(e){return e.length===0?null:e.every(t=>t.type==="text")?e.map(t=>t.content).join("")||null:e}function tm(e){return e==null?"":typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.content).join("")}function qN(e){return Array.isArray(e)?e:tm(e)}function WN(e){if(!("role"in e)||e.role!=="tool")return e;const t=e,r=Ve(t)?.toolResult;if(!io(r)||"content"in r&&!Go(r.content))return e;const s={...e};if("id"in r||Reflect.deleteProperty(s,"id"),"createdAt"in r||Reflect.deleteProperty(s,"createdAt"),typeof r.id=="string"&&Reflect.set(s,"id",r.id),typeof r.createdAt=="string"){const o=Bt(r.createdAt);o&&Reflect.set(s,"createdAt",o)}Go(r.content)&&Reflect.set(s,"content",r.content);const n=Reflect.get(t,"metadata");if(io(n)){const o=n.tanstack;if(io(o)){const{toolResult:l,...i}=o,c={...n};Object.keys(i).length?c.tanstack=i:delete c.tanstack,Object.keys(c).length?Reflect.set(s,"metadata",c):Reflect.deleteProperty(s,"metadata")}}return s}function Bt(e){if(e instanceof Date)return Number.isNaN(e.getTime())?void 0:e;if(typeof e!="string")return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function rm(e){if(e.type!=="tool-result")return e;const t=Bt(e.createdAt),{createdAt:r,...s}=e;return t===void 0?s:{...s,createdAt:t}}function sm(e){return Bt(Ve(e)?.createdAt)}function Yo(e){const t=Bt(e.createdAt);return t!==void 0?{createdAt:t}:{}}function Ca(e){return e.name!==void 0?{name:e.name}:{}}function wa(e){if(e==null||typeof e!="object"||Array.isArray(e)||!("type"in e)||e.type!=="ui-resource"||!("toolCallId"in e)||typeof e.toolCallId!="string"||!("toolName"in e)||typeof e.toolName!="string"||!("resource"in e)||e.resource==null||typeof e.resource!="object"||Array.isArray(e.resource))return!1;const t=e.resource;return"uri"in t&&typeof t.uri=="string"&&"mimeType"in t&&typeof t.mimeType=="string"}function xc(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function nm(e,t){if(t.length===0)return e;const r=new Set(e.parts.filter(wa).map(n=>xc(n))),s=t.filter(n=>!r.has(xc(n)));return s.length===0?e:{...e,parts:[...e.parts,...s]}}function KN(e){const t=e.parts.filter(wa),r=e.metadata??{},s=Ve(e),n={};s?.model!==void 0&&(n.model=s.model),s?.signature!==void 0&&(n.signature=s.signature),t.length>0&&(n.uiResources=t);const o={...r};return Object.keys(n).length>0?o.tanstack=n:delete o.tanstack,Object.keys(o).length>0?o:void 0}function HN(e){return e.role==="system"?[]:e.role!=="assistant"?[GN(e)]:JN(e)}function GN(e){const t=[];for(const r of e.parts)VN(r)&&t.push(r);return{id:e.id,role:e.role,content:em(t),...Ca(e),...Yo(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function Sc(){return{contentParts:[],toolCalls:[]}}function YN(e){return e.state==="input-complete"||e.state==="complete"||e.state==="approval-requested"||e.state==="approval-responded"||e.state==="error"||e.output!==void 0}function JN(e){const t=[];let r=Sc(),s=[];const n=new Set,o={id:e.id,...Ca(e),...Yo(e)},l=KN(e),i={...o,...l!==void 0&&{metadata:l}};function c(d=!1){const u=em(r.contentParts),h=u!==null,m=r.toolCalls.length>0,p=s.length>0;(d||h||m||p)&&(t.push({...i,role:"assistant",content:u,...m&&{toolCalls:r.toolCalls},...p&&{thinking:s},...r.structuredOutput&&{structuredOutput:r.structuredOutput}}),s=[]),r=Sc()}for(const d of e.parts)switch(d.type){case"text":case"image":case"audio":case"video":case"document":r.contentParts.push(d);break;case"tool-call":YN(d)&&r.toolCalls.push({id:d.id,type:"function",function:{name:d.name,arguments:d.arguments},...d.metadata!==void 0&&{metadata:d.metadata}});break;case"tool-result":c(t.length===0),(d.state==="complete"||d.state==="error")&&!n.has(d.toolCallId)&&(t.push({...d.id!==void 0&&{id:d.id},...Yo(d),role:"tool",content:d.content,toolCallId:d.toolCallId,...d.name!==void 0&&{name:d.name},...d.metadata!==void 0&&{metadata:d.metadata},...d.error!==void 0&&{error:d.error}}),n.add(d.toolCallId));break;case"thinking":(d.content||d.signature)&&(r.toolCalls.some(Zh)&&c(),s.push({content:d.content,...d.signature&&{signature:d.signature}}));break;case"structured-output":if(d.status==="complete"){const u=d.raw!==""?d.raw:d.data!==void 0?BN(d.data):"";u!==""&&(r.contentParts.push({type:"text",content:u}),r.structuredOutput=d)}}c();for(const d of e.parts)if(d.type==="tool-call"&&(d.output!==void 0&&!n.has(d.id)&&(t.push({role:"tool",content:il(d.output),toolCallId:d.id}),n.add(d.id)),d.output===void 0&&d.state==="approval-responded"&&d.approval?.approved!==void 0&&!n.has(d.id))){const u=d.approval.approved;t.push({role:"tool",content:JSON.stringify({approved:u,...u&&{pendingExecution:!0},message:u?"User approved this action":"User denied this action"}),toolCallId:d.id}),n.add(d.id)}return t.length===0&&t.push({...i,role:"assistant",content:null}),t}function Jn(e,t){const r=[],s=Bt(e.createdAt);if(e.role==="assistant"&&e.thinking?.length)for(const i of e.thinking)!i.content&&!i.signature||r.push({type:"thinking",content:i.content,...i.signature&&{signature:i.signature}});const n=e.structuredOutput??am(Ve(e)?.structuredOutput);if(e.role==="assistant"&&n){if(typeof e.content=="string"&&e.content&&e.content!==n.raw){const i=n.raw,c=i!==""&&e.content.endsWith(i)?e.content.slice(0,-i.length):e.content;c&&r.push({type:"text",content:c})}r.push(n)}else if(e.role==="tool"&&e.toolCallId)r.push({type:"tool-result",toolCallId:e.toolCallId,content:qN(e.content),state:e.error===void 0?"complete":"error",...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name},...e.metadata!==void 0&&{metadata:e.metadata},...s!==void 0&&{createdAt:s},...e.error!==void 0&&{error:e.error}});else if(Array.isArray(e.content))for(const i of e.content)r.push(i);else{const i=tm(e.content);i&&r.push({type:"text",content:i})}if(e.toolCalls&&e.toolCalls.length>0)for(const i of e.toolCalls){let c;try{c=JSON.parse(i.function.arguments)}catch{c=void 0}r.push({type:"tool-call",id:i.id,name:i.function.name,arguments:i.function.arguments,state:"input-complete",...c!==void 0&&{input:c},...i.metadata!==void 0&&{metadata:i.metadata}})}const o={id:t||ts(),role:e.role==="tool"?"assistant":e.role,parts:r,...Ca(e),...s!==void 0&&{createdAt:s},...e.metadata!==void 0&&{metadata:e.metadata}},l=Ve(e)?.uiResources;return nm(o,Array.isArray(l)?l.filter(wa):[])}function QN(e){if("parts"in e)return Vr(e,{...e,id:e.id||ts()});const t=e.id||ts();switch(e.role){case"user":return Vr(e,{id:t,role:"user",parts:XN(e.content)});case"assistant":{const r=Ve(e),s=r?.toolCallMetadata,n=am(r?.structuredOutput),o=e.toolCalls?.map(l=>{const i=s!=null&&typeof s=="object"?s[l.id]:void 0;return i!==void 0?{...l,metadata:i}:l});return Vr(e,Jn({role:"assistant",content:e.content??null,...Ca(e),...o&&{toolCalls:o},...n&&{structuredOutput:n}},t))}case"tool":{e=WN(e);const r=Bt("createdAt"in e?e.createdAt:void 0)??sm(e);return Vr(e,Jn({role:"tool",content:e.content,toolCallId:e.toolCallId,..."name"in e&&typeof e.name=="string"?{name:e.name}:{},..."id"in e&&typeof e.id=="string"?{id:e.id}:{},..."metadata"in e&&e.metadata!=null?{metadata:e.metadata}:{},...r!==void 0?{createdAt:r}:{},...e.error!==void 0&&{error:e.error}},t))}case"system":case"developer":return Vr(e,{id:t,role:"system",parts:e.content?[{type:"text",content:e.content}]:[]});case"reasoning":{const r=UN(e),s=typeof e.content=="string"?e.content:"";return Vr(e,{id:t,role:"assistant",parts:s||r!==void 0?[{type:"thinking",content:s,...r!==void 0?{signature:r}:{}}]:[]})}default:return Vr(e,{id:t,role:"assistant",parts:[]})}}function Vr(e,t){const r=t.parts.map(d=>rm(d));r!==t.parts&&(t={...t,parts:r});const s="name"in e&&typeof e.name=="string"?e.name:void 0;let n=s!==void 0?{...t,name:s}:t,o;if("metadata"in e){const d=e.metadata;d!=null&&typeof d=="object"&&!Array.isArray(d)&&(o=d,n={...n,metadata:o})}const l=Bt(n.createdAt)??(o!==void 0?sm(o):void 0);if(l!==void 0&&!Object.is(l,n.createdAt))n={...n,createdAt:l};else if(l===void 0&&n.createdAt!==void 0){const{createdAt:d,...u}=n;n=u}const i=Ve(o)?.uiResources,c=Array.isArray(i)?i.filter(wa):[];return nm(n,c)}function am(e){if(!(e==null||e.status!=="streaming"&&e.status!=="complete"&&e.status!=="error"||typeof e.raw!="string"))return{type:"structured-output",status:e.status,raw:e.raw,...e.partial!==void 0?{partial:e.partial}:{},...e.data!==void 0?{data:e.data}:{},...e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage!==void 0?{errorMessage:e.errorMessage}:{}}}function XN(e){if(typeof e=="string")return e?[{type:"text",content:e}]:[];const t=[];for(const r of e)r.type==="text"?t.push({type:"text",content:r.text}):r.type!=="binary"&&t.push(r);return t}function ZN(e,t){if("parts"in e){const r=e.parts.map(s=>rm(s));return{...e,parts:r,id:e.id||t(),createdAt:Bt(e.createdAt)??new Date}}else return{...Jn(e,t()),createdAt:Bt(e.createdAt)??new Date}}function ts(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function Cc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lo(e,t,r,s,n=!1){const o=Cc(e)?e:{},l=Cc(o.tanstack)?{...o.tanstack}:{};n&&delete l.uiResources;const i=Bt(t),c={...r!==void 0?{id:r}:{},...i&&{createdAt:i.toISOString()},...Array.isArray(s)&&{content:s}},d={...o,tanstack:{...l,toolResult:c}};return Object.keys(d).length?d:void 0}function ej(e,t){const r=[],s=new Set(e.flatMap(l=>"id"in l&&l.id&&l.role!=="tool"?[l.id]:[])),n=t?.includeSnapshotStructuredOutput??!1,o=new Set;for(const l of e)l.role==="assistant"&&l.id!==void 0&&o.add(l.id);for(const l of e){if(!("parts"in l)&&l.role==="tool"&&l.toolCallId){const m=uo(lj(l.id,l.toolCallId,o),s),p=lo(l.metadata,l.createdAt,l.id,l.content);r.push({role:"tool",id:m,...l.name!==void 0&&{name:l.name},toolCallId:l.toolCallId,content:typeof l.content=="string"?l.content:JSON.stringify(l.content),...l.error!==void 0&&{error:l.error},...p!==void 0&&{metadata:p}});continue}const i="parts"in l?l:Jn(l,l.id),c=i.parts;if(s.add(i.id),l.role==="system"){r.push(co(i,"system",{content:c.length>0?Jo(c):l.content??""},c,n));continue}if(l.role==="user"){r.push(co(i,"user",{content:c.length>0?nj(c):l.content??""},c,n));continue}for(const m of c)if(m.type==="thinking"){const p={role:"reasoning",id:om(ij(i.id,m),s),content:m.content};m.signature&&(p.encryptedValue=m.signature),r.push(p)}const d=Jo(c),u=oj(c);r.push(co(i,"assistant",{...d!==""&&{content:d},...u&&{toolCalls:u}},c,n));const h=new Set(c.flatMap(m=>m.type==="tool-result"?[m.toolCallId]:[]));for(const m of c)if(m.type==="tool-result"){const p=uo(m.id??Qo(m.toolCallId),s),b=lo(m.metadata,m.createdAt,m.id,m.content,!0);r.push({role:"tool",id:p,toolCallId:m.toolCallId,...m.name!==void 0&&{name:m.name},content:typeof m.content=="string"?m.content:JSON.stringify(m.content),...m.error!==void 0&&{error:m.error},...b!==void 0&&{metadata:b}})}else if(m.type==="tool-call"){const p=m.approval?.approved;if(h.has(m.id)||m.output===void 0&&(m.state!=="approval-responded"||p===void 0))continue;const b=m.output!==void 0?il(m.output):JSON.stringify({approved:p,...p&&{pendingExecution:!0},message:p?"User approved this action":"User denied this action"}),w=typeof b=="string"?b:JSON.stringify(b);r.push({role:"tool",id:uo(Qo(m.id),s),toolCallId:m.id,content:w,metadata:lo(void 0,void 0,void 0,b)})}}return r}function co(e,t,r,s,n){const o=tj(e,s,n),l={id:e.id,...e.name!==void 0&&{name:e.name},...o!==void 0&&{metadata:o}};return t==="system"?{...l,role:t,content:String(r.content??"")}:t==="user"?{...l,role:t,content:r.content??""}:{...l,role:t,...typeof r.content=="string"&&{content:r.content},...r.toolCalls!==void 0&&{toolCalls:r.toolCalls}}}function tj(e,t,r){const s={...e.metadata??{}},n=Ve(e),o={};n?.model!==void 0&&(o.model=n.model),n?.signature!==void 0&&(o.signature=n.signature);const l=Bt(e.createdAt);l!==void 0&&(o.createdAt=l.toISOString());const i=rj(t,r);i&&(o.structuredOutput=i);const c={};for(const u of t)u.type==="tool-call"&&u.metadata!==void 0&&(c[u.id]=u.metadata);Object.keys(c).length>0&&(o.toolCallMetadata=c);const d=t.filter(u=>u.type==="ui-resource");return d.length>0&&(o.uiResources=d),Object.keys(o).length>0?s.tanstack=o:delete s.tanstack,Object.keys(s).length>0?s:void 0}function rj(e,t){for(const r of e)if(r.type==="structured-output"&&(t||r.status!=="complete"))return sj(r,t)}function sj(e,t){return{status:e.status,raw:e.raw,...t&&e.partial!==void 0?{partial:e.partial}:{},...t&&e.data!==void 0?{data:e.data}:{},...t&&e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage!==void 0&&{errorMessage:e.errorMessage}}}function Jo(e){const t=[];for(const r of e)r.type==="text"?t.push(r.content):r.type==="structured-output"&&r.status==="complete"&&r.raw!==""&&t.push(r.raw);return t.join("")}function nj(e){if(!e.some(r=>r.type==="image"||r.type==="audio"||r.type==="video"||r.type==="document"))return Jo(e);const t=[];for(const r of e)r.type==="text"?t.push({type:"text",text:r.content}):(r.type==="image"||r.type==="audio"||r.type==="video"||r.type==="document")&&t.push(r);return t}function aj(e){if(e==null||typeof e!="object"||Array.isArray(e)||!("thoughtSignature"in e))return;const t=e.thoughtSignature;return typeof t=="string"&&t!==""?t:void 0}function oj(e){const t=[];for(const r of e)if(r.type==="tool-call"){const s=aj(r.metadata);t.push({id:r.id,type:"function",function:{name:r.name,arguments:r.arguments},...s!==void 0?{encryptedValue:s}:{}})}return t.length>0?t:void 0}function ij(e,t){return`${e}-reasoning-${t.id??cj(t.content)}`}function Qo(e){return`tool-${e}`}function uo(e,t){return om(e,t)}function om(e,t){if(!t.has(e))return t.add(e),e;let r=2;for(;t.has(`${e}-${r}`);)r++;const s=`${e}-${r}`;return t.add(s),s}function lj(e,t,r){const s=Qo(t);return e===void 0||r.has(e)?s:e}function cj(e){let t=0;for(let r=0;r<e.length;r++)t=t*31+e.charCodeAt(r)|0;return Math.abs(t).toString(36)}function dj(e){if((e.type===An.RUN_FINISHED||e.type===An.RUN_ERROR)&&(Array.isArray(e.usage)||Wh(e.usage))){const t=pN(e.usage,Ve(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===An.TOOL_CALL_START&&e.toolName===void 0&&e.toolCallName&&(e.toolName=e.toolCallName),e.type===An.TOOL_CALL_END&&e.input===void 0){const t=Ve(e)?.input;t!==void 0&&(e.input=t)}return e}function im(e){dj(e);const t=Ve(e),r=e;if(t==null)return r;for(const[s,n]of Object.entries(t))s==="usage"||s==="interruptErrors"||r[s]===void 0&&n!==void 0&&(r[s]=n);return t.interruptErrors!==void 0&&(r["tanstack:interruptErrors"]=t.interruptErrors),r}function wc(e){return typeof e=="string"&&e!==""?e:void 0}function lm(e){if("runId"in e){const t=wc(e.runId);if(t!==void 0)return t}return wc(Ve(e)?.runId)}var Nc=td((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),uj=td((e=>{var t=e&&e.__createBinding||(Object.create?(function(d,u,h,m){m===void 0&&(m=h);var p=Object.getOwnPropertyDescriptor(u,h);(!p||("get"in p?!u.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return u[h]}}),Object.defineProperty(d,m,p)}):(function(d,u,h,m){m===void 0&&(m=h),d[m]=u[h]})),r=e&&e.__exportStar||function(d,u){for(var h in d)h!=="default"&&!Object.prototype.hasOwnProperty.call(u,h)&&t(u,d,h)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var s=Nc();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return s.Allow}}),r(Nc(),e);var n=class extends Error{};e.PartialJSON=n;var o=class extends Error{};e.MalformedJSON=o;function l(d,u=s.Allow.ALL){if(typeof d!="string")throw new TypeError(`expecting str, got ${typeof d}`);if(!d.trim())throw new Error(`${d} is empty`);return i(d.trim(),u)}e.parseJSON=l;var i=(d,u)=>{const h=d.length;let m=0;const p=v=>{throw new n(`${v} at position ${m}`)},b=v=>{throw new o(`${v} at position ${m}`)},w=()=>(g(),m>=h&&p("Unexpected end of input"),d[m]==='"'?x():d[m]==="{"?N():d[m]==="["?C():d.substring(m,m+4)==="null"||s.Allow.NULL&u&&h-m<4&&"null".startsWith(d.substring(m))?(m+=4,null):d.substring(m,m+4)==="true"||s.Allow.BOOL&u&&h-m<4&&"true".startsWith(d.substring(m))?(m+=4,!0):d.substring(m,m+5)==="false"||s.Allow.BOOL&u&&h-m<5&&"false".startsWith(d.substring(m))?(m+=5,!1):d.substring(m,m+8)==="Infinity"||s.Allow.INFINITY&u&&h-m<8&&"Infinity".startsWith(d.substring(m))?(m+=8,1/0):d.substring(m,m+9)==="-Infinity"||s.Allow._INFINITY&u&&1<h-m&&h-m<9&&"-Infinity".startsWith(d.substring(m))?(m+=9,-1/0):d.substring(m,m+3)==="NaN"||s.Allow.NAN&u&&h-m<3&&"NaN".startsWith(d.substring(m))?(m+=3,NaN):S()),x=()=>{const v=m;let y=!1;for(m++;m<h&&(d[m]!=='"'||y&&d[m-1]==="\\");)y=d[m]==="\\"?!y:!1,m++;if(d.charAt(m)=='"')try{return JSON.parse(d.substring(v,++m-Number(y)))}catch(R){b(String(R))}else if(s.Allow.STR&u)try{return JSON.parse(d.substring(v,m-Number(y))+'"')}catch{return JSON.parse(d.substring(v,d.lastIndexOf("\\"))+'"')}p("Unterminated string literal")},N=()=>{m++,g();const v={};try{for(;d[m]!=="}";){if(g(),m>=h&&s.Allow.OBJ&u)return v;const y=x();g(),m++;try{v[y]=w()}catch(R){if(s.Allow.OBJ&u)return v;throw R}g(),d[m]===","&&m++}}catch{if(s.Allow.OBJ&u)return v;p("Expected '}' at end of object")}return m++,v},C=()=>{m++;const v=[];try{for(;d[m]!=="]";)v.push(w()),g(),d[m]===","&&m++}catch{if(s.Allow.ARR&u)return v;p("Expected ']' at end of array")}return m++,v},S=()=>{if(m===0){d==="-"&&b("Not sure what '-' is");try{return JSON.parse(d)}catch(y){if(s.Allow.NUM&u)try{return JSON.parse(d.substring(0,d.lastIndexOf("e")))}catch{}b(String(y))}}const v=m;for(d[m]==="-"&&m++;d[m]&&",]}".indexOf(d[m])===-1;)m++;m==h&&!(s.Allow.NUM&u)&&p("Unterminated number literal");try{return JSON.parse(d.substring(v,m))}catch{d.substring(v,m)==="-"&&p("Not sure what '-' is");try{return JSON.parse(d.substring(v,d.lastIndexOf("e")))}catch(R){b(String(R))}}},g=()=>{for(;m<h&&`
|
|
14
|
+
\r `.includes(d[m]);)m++};return w()},c=l;e.parse=c})),fj=uj(),hj=class{parse(e){if(!(!e||e.trim()===""))try{return(0,fj.parse)(e)}catch{return}}},cm=new hj;function mj(e){return cm.parse(e)}var pj=class{shouldEmit(e,t){return!0}};function gj(e){const t=new Error(e.message||e.error?.message||"An error occurred"),r=e.code??e.error?.code;return r!==void 0&&Object.assign(t,{code:r}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}function vj(e,t,r){return e.map(s=>{if(s.id!==t)return s;const n=[...s.parts],o=n.length>0?n[n.length-1]:null;return o&&o.type==="text"?n[n.length-1]={type:"text",content:r}:n.push({type:"text",content:r}),{...s,parts:n}})}function On(e,t,r){return e.map(s=>{if(s.id!==t)return s;const n=[...s.parts],o=n.find(d=>d.type==="tool-call"&&d.id===r.id),l=r.metadata??o?.metadata,i=r.input??o?.input,c={type:"tool-call",id:r.id,name:r.name,arguments:r.arguments,state:r.state,...o?.approval&&{approval:{...o.approval}},...o?.output!==void 0&&{output:o.output},...i!==void 0&&{input:i},...l!==void 0&&{metadata:l}};return o?n[n.indexOf(o)]=c:n.push(c),{...s,parts:n}})}function jc(e,t,r,s,n,o){return e.map(l=>{if(l.id!==t)return l;const i=[...l.parts],c=i.findIndex(u=>u.type==="tool-result"&&u.toolCallId===r),d={type:"tool-result",toolCallId:r,content:s,state:n,...o&&{error:o}};return c>=0?i[c]=d:i.push(d),{...l,parts:i}})}function Ic(e,t,r,s){return e.map(n=>{if(n.id!==t)return n;const o=[...n.parts],l=o.find(i=>i.type==="tool-call"&&i.id===r);if(l){const i=o.indexOf(l);o[i]={...l,state:"approval-requested",approval:{id:s,needsApproval:!0}}}return{...n,parts:o}})}function Tc(e,t,r,s,n){return e.map(o=>{const l=[...o.parts],i=l.find(c=>c.type==="tool-call"&&c.id===t);if(i){const c=l.indexOf(i);l[c]={...i,output:n?{error:n}:r,state:s??(n?"error":"complete")}}return{...o,parts:l}})}function yj(e,t,r){return e.map(s=>{const n=[...s.parts],o=n.find(l=>l.type==="tool-call"&&l.approval?.id===t);if(o&&o.approval){const l=n.indexOf(o);n[l]={...o,approval:{...o.approval,approved:r},state:"approval-responded"}}return{...s,parts:n}})}function bj(e,t,r){return e.map(s=>{if(s.id!==t)return s;const n=[...s.parts],o=n.findIndex(h=>h.type==="structured-output"),l=o>=0?n[o]:null,i=(l?.raw??"")+r,c=mj(i),d=c??l?.partial,u={type:"structured-output",status:"streaming",raw:i,...d!==void 0?{partial:d}:{},...l?.reasoning!==void 0?{reasoning:l.reasoning}:{}};return o>=0?n[o]=u:n.push(u),{...s,parts:n}})}function xj(e,t,r,s,n){return e.map(o=>{if(o.id!==t)return o;const l=[...o.parts],i=l.findIndex(h=>h.type==="structured-output"),c=i>=0?l[i].raw:"";let d=s||c;if(d===""&&r!==void 0)try{d=JSON.stringify(r)}catch{}const u={type:"structured-output",status:"complete",data:r,partial:r,raw:d,...n!==void 0?{reasoning:n}:{}};return i>=0?l[i]=u:l.push(u),{...o,parts:l}})}function Rc(e,t,r){return e.map(s=>{if(s.id!==t)return s;const n=[...s.parts],o=n.findIndex(i=>i.type==="structured-output");if(o<0)return n.push({type:"structured-output",status:"error",raw:"",errorMessage:r}),{...s,parts:n};const l=n[o];return l.status==="complete"?s:(n[o]={...l,status:"error",errorMessage:r},{...s,parts:n})})}function fo(e,t,r,s,n){return e.map(o=>{if(o.id!==t)return o;const l=[...o.parts],i=l.findIndex(d=>d.type==="thinking"&&d.stepId===r),c={type:"thinking",content:s,stepId:r,...n&&{signature:n}};return i>=0?l[i]=c:l.push(c),{...o,parts:l}})}var Sj=12;function Cj(e){return e.some(t=>{const r=t.metadata;if(!r||typeof r!="object"||Array.isArray(r))return!1;const s=r[Sa];return s!==null&&typeof s=="object"&&!Array.isArray(s)&&s.kind==="generic"})}var wj=class dm{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;finishReason=null;hasError=!1;isDone=!1;streamEndEmitted=!1;recording=null;recordingStartTime=0;constructor(t={}){this.chunkStrategy=t.chunkStrategy||new pj,this.events=t.events||{},this.jsonParser=t.jsonParser||cm,this.recordingEnabled=t.recording??!1,t.initialMessages&&(this.messages=[...t.initialMessages])}setMessages(t){this.messages=[...t],this.emitMessagesChange()}prependMessages(t){const r=new Set(this.messages.map(n=>n.id)),s=[];for(const n of t)r.has(n.id)||(r.add(n.id),s.push(n));this.messages=[...s,...this.messages],this.emitMessagesChange()}addUserMessage(t,r,s){const n=typeof t=="string"?[{type:"text",content:t}]:t.map(l=>l),o={id:r??ts(),role:"user",parts:n,createdAt:new Date,...s!=null?{metadata:s}:{}};return this.messages=[...this.messages,o],this.emitMessagesChange(),o}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(t){this.prepareAssistantMessage();const{messageId:r}=this.ensureAssistantMessage(t);return this.pendingManualMessageId=r,r}getCurrentAssistantMessageId(){let t=null;for(const[r,s]of this.messageStates)s.role==="assistant"&&(t=r);return t}addToolResult(t,r,s){const n=this.messages.find(c=>c.parts.some(d=>d.type==="tool-call"&&d.id===t));if(!n){console.warn(`[StreamProcessor] Could not find message with tool call ${t}`);return}let o=Tc(this.messages,t,r,s?"error":void 0,s);const l=il(r),i=s?"error":"complete";o=jc(o,n.id,t,l,i,s),this.messages=o,this.emitMessagesChange()}addToolApprovalResponse(t,r){this.messages=yj(this.messages,t,r),this.emitMessagesChange()}toModelMessages(){const t=[];for(const r of this.messages)t.push(...HN(r));return t}getMessages(){return this.messages}areAllToolsComplete(){const t=this.messages.findLast(n=>n.role==="assistant");if(!t)return!0;const r=t.parts.filter(n=>n.type==="tool-call");if(r.length===0)return!0;const s=new Set(t.parts.filter(n=>n.type==="tool-result").map(n=>n.toolCallId));return r.every(n=>n.state==="complete"||n.state==="approval-responded"||n.output!==void 0&&!n.approval||s.has(n.id)||Zh(n))}removeMessagesAfter(t){const r=new Set(this.messages.slice(0,t+1).map(s=>s.id));for(const s of this.structuredMessageIds)r.has(s)||this.structuredMessageIds.delete(s);for(const s of this.structuredOutputUpdateBatches.keys())r.has(s)||this.structuredOutputUpdateBatches.delete(s);for(const s of this.messageStates.keys())r.has(s)||this.messageStates.delete(s);for(const[s,n]of this.toolCallToMessage)r.has(n)||this.toolCallToMessage.delete(s);for(const s of this.activeMessageIds)r.has(s)||this.activeMessageIds.delete(s);this.messages=this.messages.slice(0,t+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(t){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(const r of t)this.processChunk(r);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(t){switch(this.recording&&this.recording.chunks.push({chunk:t,timestamp:Date.now(),index:this.recording.chunks.length}),t.type){case"TEXT_MESSAGE_START":this.handleTextMessageStartEvent(t);break;case"TEXT_MESSAGE_CONTENT":this.handleTextMessageContentEvent(t);break;case"TEXT_MESSAGE_END":this.handleTextMessageEndEvent(t);break;case"TOOL_CALL_START":this.handleToolCallStartEvent(t);break;case"TOOL_CALL_ARGS":this.handleToolCallArgsEvent(t);break;case"TOOL_CALL_END":this.handleToolCallEndEvent(t);break;case"RUN_FINISHED":this.handleRunFinishedEvent(t);break;case"RUN_ERROR":this.handleRunErrorEvent(t);break;case"STEP_FINISHED":this.handleStepFinishedEvent(t);break;case"MESSAGES_SNAPSHOT":this.handleMessagesSnapshotEvent(t);break;case"CUSTOM":this.handleCustomEvent(t);break;case"RUN_STARTED":this.handleRunStartedEvent(t);break;case"REASONING_START":case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"REASONING_MESSAGE_CONTENT":this.handleReasoningMessageContentEvent(t);break;case"REASONING_ENCRYPTED_VALUE":this.handleReasoningEncryptedValueEvent(t);break;case"TOOL_CALL_RESULT":this.handleToolCallResultEvent(t);break;case"STEP_STARTED":this.handleStepStartedEvent(t)}}createMessageState(t,r){const s={id:t,role:r,totalTextContent:"",currentSegmentText:"",lastEmittedText:"",hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(t,s),s}getMessageState(t){return this.messageStates.get(t)}consumePendingThinkingStep(t){if(!this.pendingThinkingStepId)return;const r=this.pendingThinkingStepId;t.currentThinkingStepId=r,t.thinkingSteps.has(r)||(t.thinkingSteps.set(r,""),t.thinkingStepOrder.push(r)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){const t=Array.from(this.activeMessageIds).reverse();for(const r of t){const s=this.messageStates.get(r);if(s&&s.role==="assistant")return r}for(const[r,s]of[...this.messageStates].reverse())if(s.role==="assistant")return r;return null}resumeAssistantState(t,r){this.activeMessageIds.add(t),(r.isComplete||this.isDone)&&(r.isComplete=!1,this.isDone=!1)}ensureAssistantMessage(t){if(t){const l=this.getMessageState(t);if(l)return this.resumeAssistantState(t,l),{messageId:t,state:l}}const r=this.getActiveAssistantMessageId();if(r){const l=this.getMessageState(r);if(l)return this.resumeAssistantState(r,l),{messageId:r,state:l}}if(t){const l=this.messages.find(i=>i.id===t);if(l){const i=this.createMessageState(t,l.role);this.activeMessageIds.add(t);const c=l.parts.length>0?l.parts[l.parts.length-1]:null;return c&&c.type==="text"&&(i.currentSegmentText=c.content,i.lastEmittedText=c.content,i.totalTextContent=c.content),{messageId:t,state:i}}}const s=t||ts(),n={id:s,role:"assistant",parts:[],createdAt:new Date};this.messages=[...this.messages,n];const o=this.createMessageState(s,"assistant");return this.activeMessageIds.add(s),this.pendingManualMessageId=s,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:s,state:o}}mergeMessageMetadata(t,r){if(r==null||typeof r!="object"||Array.isArray(r))return;const s=this.messages.find(u=>u.id===t);if(!s)return;const n=r,o=Ve(n),l=o!=null&&("content"in o||"args"in o)?{...n,tanstack:Object.fromEntries(Object.entries(o).filter(([u])=>u!=="content"&&u!=="args"))}:n,i=Kh(s.metadata,l),c=Bt(Ve(n)?.createdAt),d=c!==void 0;this.messages=this.messages.map(u=>u.id===t?{...u,...i!==void 0?{metadata:i}:{},...d?{createdAt:c}:{}}:u),this.emitMessagesChange()}handleTextMessageStartEvent(t){const{messageId:r,role:s}=t,n=s==="user"||s==="system"?s:"assistant";if(this.pendingManualMessageId){const l=this.pendingManualMessageId;if(this.pendingManualMessageId=null,l!==r){this.messages=this.messages.map(d=>d.id===l?{...d,id:r}:d);const c=this.messageStates.get(l);c&&(c.id=r,this.messageStates.delete(l),this.messageStates.set(r,c)),this.activeMessageIds.delete(l),this.activeMessageIds.add(r);for(const[d,u]of this.toolCallToMessage)u===l&&this.toolCallToMessage.set(d,r)}let i=this.messageStates.get(r);i?i.hasToolCallsSinceTextStart&&(i.currentSegmentText!==i.lastEmittedText&&this.emitTextUpdateForMessage(r),i.currentSegmentText="",i.lastEmittedText="",i.hasToolCallsSinceTextStart=!1):(i=this.createMessageState(r,n),this.activeMessageIds.add(r)),this.mergeMessageMetadata(r,t.metadata),this.emitMessagesChange();return}if(this.messages.find(l=>l.id===r)){this.activeMessageIds.add(r);const l=this.messageStates.get(r);l?l.hasToolCallsSinceTextStart&&(l.currentSegmentText!==l.lastEmittedText&&this.emitTextUpdateForMessage(r),l.currentSegmentText="",l.lastEmittedText="",l.hasToolCallsSinceTextStart=!1):this.createMessageState(r,n),this.mergeMessageMetadata(r,t.metadata);return}const o={id:r,role:n,parts:[],createdAt:new Date};this.messages=[...this.messages,o],this.createMessageState(r,n),this.activeMessageIds.add(r),this.mergeMessageMetadata(r,t.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(t){const{messageId:r}=t;this.mergeMessageMetadata(r,t.metadata);const s=this.getMessageState(r);s&&(s.isComplete||s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(r))}handleMessagesSnapshotEvent(t){this.resetStreamState();const r=this.messages,s=new Map(r.map(o=>[o.id,o])),n=this.mergeReasoningFanOut(t.messages.map(QN));this.messages=this.reconcileSnapshotToolCalls(n,r).map(o=>{if(o.metadata!=null)return o;const l=s.get(o.id);return l?.metadata==null?o:{...o,metadata:l.metadata}}),this.emitMessagesChange()}mergeReasoningFanOut(t){const r=[];let s=[];const n=c=>c.parts.filter(d=>d.type==="thinking"),o=c=>c.role==="assistant"&&c.parts.length>0&&c.parts.every(d=>d.type==="thinking"),l=c=>c.role==="assistant"&&c.parts.some(d=>d.type==="tool-result")&&c.parts.every(d=>d.type==="tool-result"||d.type==="ui-resource"),i=()=>{r.push(...s),s=[]};for(const c of t){if(o(c)){s.push(c);continue}if(c.role==="assistant"&&s.length>0&&!l(c)){r.push({...c,parts:[...s.flatMap(n),...c.parts]}),s=[];continue}i(),r.push(c)}return i(),r}reconcileSnapshotToolCalls(t,r){const s=new Map;for(const l of r)for(const i of l.parts)i.type==="tool-call"&&s.set(i.id,i);const n=new Set;for(const l of t)for(const i of l.parts)i.type==="tool-call"&&n.add(i.id);const o=[];for(const l of t){const i=l.parts.filter(h=>h.type==="tool-result"),c=l.role==="assistant"&&i.length===1&&l.parts.every(h=>h.type==="tool-result"||h.type==="ui-resource")?i[0]:void 0;if(!c){o.push(l);continue}const d=o.findLast(h=>h.parts.some(m=>m.type==="tool-call"&&m.id===c.toolCallId))??o.findLast(h=>h.role==="assistant"&&!(h.parts.length===1&&h.parts[0]?.type==="tool-result"));if(!d){n.has(c.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${c.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${c.toolCallId}") will not be able to locate this call`),o.push(l);continue}const u=[...d.parts];if(!n.has(c.toolCallId)&&!u.some(h=>h.type==="tool-call"&&h.id===c.toolCallId)){const h=s.get(c.toolCallId);h?(u.push({...h}),n.add(h.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${c.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${c.toolCallId}") will not be able to locate this call`)}u.push(...l.parts),d.parts=u}return this.enrichSnapshotToolCallsFromResults(o,s)}enrichSnapshotToolCallsFromResults(t,r){const s=new Map;for(const n of t)for(const o of n.parts)o.type==="tool-result"&&s.set(o.toolCallId,o);return t.map(n=>{const o=n.parts.map(l=>{if(l.type!=="tool-call")return l;const i=r.get(l.id),c=s.get(l.id);let d=l;if(i&&(i.output!==void 0||i.state==="complete"||i.state==="error")&&(l.output===void 0||l.state==="input-complete"||l.state==="input-streaming"||l.state==="awaiting-input")&&(d={...l,...i.output!==void 0?{output:i.output}:{},state:i.state,...i.approval!==void 0?{approval:i.approval}:{},...i.metadata!==void 0?{metadata:i.metadata}:{}}),c&&d.output===void 0){let u;if(Array.isArray(c.content))u=c.content;else try{u=JSON.parse(c.content)}catch{u=c.content}const h=c.state==="error"?this.extractToolResultError(u):void 0;d={...d,output:h?{error:h}:u,state:c.state==="error"?"error":"complete"}}return d});return o.some((l,i)=>l!==n.parts[i])?{...n,parts:o}:n})}handleTextMessageContentEvent(t){const{messageId:r,state:s}=this.ensureAssistantMessage(t.messageId);if(this.mergeMessageMetadata(r,t.metadata),this.structuredMessageIds.has(r)){const u=t.delta||"";u!==""&&(this.messages=bj(this.messages,r,u),s.totalTextContent+=u,this.queueStructuredOutputUpdate(r,u),this.emitMessagesChange());return}const n=s.currentSegmentText;s.hasToolCallsSinceTextStart&&n.length>0&&this.isNewTextSegment(t,n)&&(n!==s.lastEmittedText&&this.emitTextUpdateForMessage(r),s.currentSegmentText="",s.lastEmittedText="",s.hasToolCallsSinceTextStart=!1),s.hasToolCallsSinceTextStart=!1;const o=s.currentSegmentText,l=t.delta||"",i=l!==""?o+l:o,c=i.slice(o.length);s.currentSegmentText=i,s.totalTextContent+=c;const d=t.delta||"";this.chunkStrategy.shouldEmit(d,s.currentSegmentText)&&s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(r)}handleToolCallStartEvent(t){const r=t.parentMessageId??this.getActiveAssistantMessageId(),{messageId:s,state:n}=this.ensureAssistantMessage(r??void 0);n.hasToolCallsSinceTextStart=!0;const o=t.toolCallId;if(!n.toolCalls.get(o)){const l="awaiting-input",i=t.toolCallName,c=t.metadata,d={id:t.toolCallId,name:i,arguments:"",state:l,parsedArguments:void 0,index:n.toolCalls.size,...c!==void 0&&{metadata:c}};n.toolCalls.set(o,d),n.toolCallOrder.push(o),this.toolCallToMessage.set(o,s),this.messages=On(this.messages,s,{id:t.toolCallId,name:i,arguments:"",state:l,...c!==void 0&&{metadata:c}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(s,t.toolCallId,l,"")}}handleToolCallArgsEvent(t){const r=t.toolCallId,s=this.toolCallToMessage.get(r);if(!s)return;const n=this.getMessageState(s);if(!n)return;const o=n.toolCalls.get(r);if(!o)return;const l=o.state==="awaiting-input";o.arguments+=t.delta||"",l&&t.delta&&(o.state="input-streaming"),o.parsedArguments=this.jsonParser.parse(o.arguments),this.messages=On(this.messages,s,{id:o.id,name:o.name,arguments:o.arguments,state:o.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(s,o.id,o.state,o.arguments)}handleToolCallEndEvent(t){const r=this.toolCallToMessage.get(t.toolCallId);if(!r)return;const s=this.getMessageState(r);if(!s)return;const n=t.input!==void 0?t.input:Ve(t)?.input,o=s.toolCalls.get(t.toolCallId);if(o&&o.state!=="input-complete"){if(n!==void 0&&!o.arguments)try{o.arguments=JSON.stringify(n)}catch{}const l=s.toolCallOrder.indexOf(t.toolCallId);this.completeToolCall(r,l,o),n!==void 0&&(o.parsedArguments=n,this.messages=On(this.messages,r,{id:o.id,name:o.name,arguments:o.arguments,state:"input-complete",input:n,...o.metadata!==void 0&&{metadata:o.metadata}}),this.emitMessagesChange())}}extractToolResultError(t){return t&&typeof t=="object"&&"error"in t&&typeof t.error=="string"?t.error:typeof t=="string"?t:"Tool execution failed"}handleToolCallResultEvent(t){const r=this.toolCallToMessage.get(t.toolCallId)??this.messages.find(l=>l.parts.some(i=>i.type==="tool-call"&&i.id===t.toolCallId))?.id;if(!r)return;const s=t.state==="output-error"||Ve(t)?.state==="output-error";let n;try{n=JSON.parse(t.content)}catch{n=t.content}this.messages=Tc(this.messages,t.toolCallId,n,s?"error":void 0);const o=s?"error":"complete";this.messages=jc(this.messages,r,t.toolCallId,t.content,o,o==="error"?this.extractToolResultError(n):void 0),this.emitMessagesChange()}handleRunStartedEvent(t){this.activeRuns.add(t.runId)}handleRunFinishedEvent(t){const r=t;if(this.finishReason=r.finishReason!==void 0?r.finishReason:Ve(t)?.finishReason??null,this.activeRuns.delete(t.runId),t.outcome?.type==="interrupt"&&this.handleInterrupts(t.outcome.interrupts),this.activeRuns.size===0){if(this.completeAllToolCalls(),this.finishReason==="tool_calls"&&t.outcome?.type!=="interrupt")return;this.isDone=!0,this.finalizeStream()}}handleInterrupts(t){const r=Cj(t);for(const s of t){const n=s.metadata&&typeof s.metadata=="object"?s.metadata:{},o=typeof n.kind=="string"?n.kind:void 0,l=s.toolCallId;if(!l)continue;const i=typeof n.toolName=="string"?n.toolName:this.findToolCallName(l),c=Object.hasOwn(n,"input")?n.input:{};if(o==="approval"||s.reason==="approval_required"){const d=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(l)??this.messages.find(u=>u.role==="assistant"&&u.parts.some(h=>h.type==="tool-call"&&h.id===l))?.id;d&&(this.messages=Ic(this.messages,d,l,s.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:l,toolName:i,input:c,approvalId:s.id});continue}if(o==="client_tool"||s.reason==="client_tool_input"){if(r)continue;this.events.onToolCall?.({toolCallId:l,toolName:i,input:c})}}}findToolCallName(t){for(const r of this.messageStates.values()){const s=r.toolCalls.get(t);if(s)return s.name}return""}handleRunErrorEvent(t){this.hasError=!0;const r=lm(t);r?this.activeRuns.delete(r):this.activeRuns.clear();const{messageId:s}=this.ensureAssistantMessage(),n=t.message||"An error occurred";t.message||console.error("[StreamProcessor] RUN_ERROR with no message; original chunk:",t),this.structuredMessageIds.has(s)&&(this.flushStructuredOutputUpdate(s),this.messages=Rc(this.messages,s,n),this.structuredMessageIds.delete(s),this.emitStructuredOutputChange(s,"error"),this.emitMessagesChange()),this.events.onError?.(gj(t))}handleStepStartedEvent(t){const r=t.stepName||ts(),s=this.getActiveAssistantMessageId();if(s){const n=this.getMessageState(s);if(n){n.currentThinkingStepId=r,n.thinkingSteps.has(r)||(n.thinkingSteps.set(r,""),n.thinkingStepOrder.push(r)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=r}handleStepFinishedEvent(t){const r=t,s=r.signature;if(!s)return;const{messageId:n,state:o}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),l=o.currentThinkingStepId??r.stepId;if(!l)return;const i=o.thinkingSteps.get(l);i!==void 0&&(o.thinkingStepSignatures.set(l,s),this.messages=fo(this.messages,n,l,i,s),this.emitMessagesChange())}handleReasoningMessageContentEvent(t){const{messageId:r,state:s}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);s.hasSeenReasoningEvents=!0;const n=t.delta||"";this.consumePendingThinkingStep(s);const o=s.currentThinkingStepId??t.messageId;s.thinkingSteps.has(o)||(s.thinkingSteps.set(o,""),s.thinkingStepOrder.push(o),s.currentThinkingStepId=o);const l=(s.thinkingSteps.get(o)??"")+n;s.thinkingSteps.set(o,l),this.messages=fo(this.messages,r,o,l,s.thinkingStepSignatures.get(o)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(r,o,l)}handleReasoningEncryptedValueEvent(t){const r=t.encryptedValue;if(typeof r!="string"||r==="")return;if(t.subtype==="tool-call"){this.attachToolCallSignature(t.entityId,r);return}const{messageId:s,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),o=n.currentThinkingStepId??t.entityId;n.thinkingStepSignatures.set(o,r);const l=n.thinkingSteps.get(o)??"";n.thinkingSteps.has(o)||(n.thinkingSteps.set(o,l),n.thinkingStepOrder.push(o)),this.messages=fo(this.messages,s,o,l,r),this.emitMessagesChange()}attachToolCallSignature(t,r){this.messages=this.messages.map(s=>{let n=!1;const o=s.parts.map(l=>l.type!=="tool-call"||l.id!==t?l:(n=!0,{...l,metadata:{...l.metadata!=null&&typeof l.metadata=="object"?l.metadata:{},thoughtSignature:r}}));return n?{...s,parts:o}:s});for(const s of this.messageStates.values()){const n=s.toolCalls.get(t);n&&(n.metadata={...n.metadata??{},thoughtSignature:r})}this.emitMessagesChange()}handleCustomEvent(t){const r=this.getActiveAssistantMessageId();if(t.name==="structured-output.start"&&t.value){const s=t.value,{messageId:n}=this.ensureAssistantMessage(s.messageId??r??void 0);n&&(this.structuredMessageIds.add(n),this.structuredOutputUpdateBatches.delete(n),this.events.onStructuredOutputChange?.({phase:"start",messageId:n,status:"streaming",raw:""}));return}if(t.name==="structured-output.complete"&&t.value){const s=t.value,{messageId:n}=this.ensureAssistantMessage(s.messageId??r??void 0);n&&(this.flushStructuredOutputUpdate(n),this.messages=xj(this.messages,n,s.object,s.raw??"",s.reasoning),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,"complete"),this.emitMessagesChange())}if(t.name==="tool-input-available"&&t.value){const{toolCallId:s,toolName:n,input:o}=t.value;this.events.onToolCall?.({toolCallId:s,toolName:n,input:o});return}if(t.name==="approval-requested"&&t.value){const{toolCallId:s,toolName:n,input:o,approval:l}=t.value,i=r??this.toolCallToMessage.get(s);i&&(this.messages=Ic(this.messages,i,s,l.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:s,toolName:n,input:o,approvalId:l.id});return}if(t.name==="ui-resource"&&t.value){const s=t.value,n=this.toolCallToMessage.get(s.toolCallId)??r;if(n){const o={type:"ui-resource",resource:s.resource,toolCallId:s.toolCallId,toolName:s.toolName,...s.serverId!==void 0&&{serverId:s.serverId},...s.meta!==void 0&&{meta:s.meta}};this.messages=this.messages.map(l=>l.id===n?{...l,parts:[...l.parts,o]}:l),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${s.toolCallId}" (toolName "${s.toolName}")`);return}if(this.events.onCustomEvent){const s=t.value&&typeof t.value=="object"?t.value.toolCallId:void 0;this.events.onCustomEvent(t.name,t.value,{toolCallId:s})}}isNewTextSegment(t,r){return!0}completeAllToolCalls(){for(const t of this.activeMessageIds)this.completeAllToolCallsForMessage(t)}completeAllToolCallsForMessage(t){const r=this.getMessageState(t);r&&r.toolCalls.forEach((s,n)=>{if(s.state!=="input-complete"){const o=r.toolCallOrder.indexOf(n);this.completeToolCall(t,o,s)}})}completeToolCall(t,r,s){s.state="input-complete";let n=!1;try{s.parsedArguments=JSON.parse(s.arguments),n=!0}catch{s.parsedArguments=void 0}this.isToolCallPartErrored(s.id)||this.isToolCallPartAwaitingUserAction(s.id)||(this.messages=On(this.messages,t,{id:s.id,name:s.name,arguments:s.arguments,state:"input-complete",...n&&{input:s.parsedArguments},...s.metadata!==void 0&&{metadata:s.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(t,s.id,"input-complete",s.arguments))}isToolCallPartAwaitingUserAction(t){return this.messages.some(r=>r.parts?.some(s=>s.type==="tool-call"&&s.id===t&&(s.state==="approval-requested"||s.state==="approval-responded")))}isToolCallPartErrored(t){return this.messages.some(r=>r.parts?.some(s=>s.type==="tool-call"&&s.id===t&&s.state==="error"))}emitTextUpdateForMessage(t){const r=this.getMessageState(t);r&&(r.lastEmittedText=r.currentSegmentText,this.messages=vj(this.messages,t,r.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(t,r.currentSegmentText))}queueStructuredOutputUpdate(t,r){const s=this.structuredOutputUpdateBatches.get(t),n={delta:`${s?.delta??""}${r}`,chunkCount:(s?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(t,n),n.chunkCount>=Sj&&this.flushStructuredOutputUpdate(t)}flushStructuredOutputUpdate(t){const r=this.structuredOutputUpdateBatches.get(t);!r||r.chunkCount===0||(this.structuredOutputUpdateBatches.delete(t),this.emitStructuredOutputChange(t,"update",r.delta))}emitStructuredOutputChange(t,r,s){const n=this.messages.find(o=>o.id===t)?.parts.find(o=>o.type==="structured-output");n&&this.events.onStructuredOutputChange?.({phase:r,messageId:t,status:n.status,raw:n.raw,...n.partial!==void 0?{partial:n.partial}:{},...n.data!==void 0?{data:n.data}:{},...n.reasoning!==void 0?{reasoning:n.reasoning}:{},...n.errorMessage!==void 0?{errorMessage:n.errorMessage}:{},...s!==void 0?{delta:s}:{}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){this.isDone=!0;let t;for(const r of this.activeMessageIds){const s=this.getMessageState(r);if(!s)continue;this.completeAllToolCallsForMessage(r),s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(r),s.isComplete=!0;const n=this.messages.find(o=>o.id===r);n&&n.role==="assistant"&&(t=n)}for(const r of this.structuredMessageIds)this.flushStructuredOutputUpdate(r),this.messages=Rc(this.messages,r,"Stream ended without structured-output.complete"),this.emitStructuredOutputChange(r,"error");if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),t&&!this.hasError&&this.isWhitespaceOnlyMessage(t)){this.messages=this.messages.filter(r=>r.id!==t.id),this.emitMessagesChange();return}t&&!this.streamEndEmitted&&(this.streamEndEmitted=!0,this.events.onStreamEnd?.(t))}getCompletedToolCalls(){const t=[];for(const r of this.messageStates.values())for(const s of r.toolCalls.values())s.state==="input-complete"&&t.push({id:s.id,type:"function",function:{name:s.name,arguments:s.arguments},...s.metadata!==void 0&&{metadata:s.metadata}});return t}getResult(){const t=this.getCompletedToolCalls();let r="",s="";for(const n of this.messageStates.values()){r+=n.totalTextContent;for(const o of n.thinkingStepOrder)s+=n.thinkingSteps.get(o)??""}return{content:r,thinking:s||void 0,toolCalls:t.length>0?t:void 0,finishReason:this.finishReason}}getState(){let t="",r="";const s=new Map,n=[];for(const o of this.messageStates.values()){t+=o.totalTextContent;for(const l of o.thinkingStepOrder)r+=o.thinkingSteps.get(l)??"";for(const[l,i]of o.toolCalls)s.set(l,i);n.push(...o.toolCallOrder)}return{content:t,thinking:r,toolCalls:s,toolCallOrder:n,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:"1.0",timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.streamEndEmitted=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(t){return t.parts.length===0?!1:t.parts.every(r=>r.type==="text"&&r.content.trim()==="")}static async replay(t,r){return new dm(r).process(Nj(t))}};function Nj(e){return{async*[Symbol.asyncIterator](){for(const{chunk:t}of e.chunks)yield t}}}var Xo=(function(e){return e.TEXT_MESSAGE_START="TEXT_MESSAGE_START",e.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",e.TEXT_MESSAGE_END="TEXT_MESSAGE_END",e.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.THINKING_START="THINKING_START",e.THINKING_END="THINKING_END",e.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",e.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",e.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",e.STATE_SNAPSHOT="STATE_SNAPSHOT",e.STATE_DELTA="STATE_DELTA",e.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",e.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",e.ACTIVITY_DELTA="ACTIVITY_DELTA",e.RAW="RAW",e.CUSTOM="CUSTOM",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.STEP_STARTED="STEP_STARTED",e.STEP_FINISHED="STEP_FINISHED",e.REASONING_START="REASONING_START",e.REASONING_MESSAGE_START="REASONING_MESSAGE_START",e.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",e.REASONING_MESSAGE_END="REASONING_MESSAGE_END",e.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",e.REASONING_END="REASONING_END",e.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",e})({}),um=new WeakMap;function _t(e){return um.get(e)??lm(e)}var fm=class extends Error{constructor(){super("Stream ended with unterminated trailing data — connection was likely cut short."),this.name="StreamTruncatedError"}},ll=class extends Error{constructor(e){super("Stream response body read failed",{cause:e}),this.name="StreamReadError"}},jj=class extends Error{constructor(){super("Durable run ended without a terminal event and could not resume — the run did not complete."),this.name="DurableStreamIncompleteError"}},Ij=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name="StreamReconnectLimitError"}};function Tj(e){const t=e?.maxAttempts??5,r=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw new Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(r)||r<0)throw new Error(`Invalid reconnect.delayMs: ${r}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:r}}function Rj(e){const t=Tj(e),r=new Set;let s,n=0;return{get lastEventId(){return s},note(o){return o===void 0?"new":o===""?(s=void 0,r.clear(),"reset"):r.has(o)?"duplicate":(r.add(o),s=o,"new")},async waitBeforeReconnect(o,l){if(o)n=0;else if(n+=1,n>t.maxAttempts)throw new Ij(t.maxAttempts);await Ej(t.delayMs,l)}}}function Ej(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(r=>{const s=()=>{clearTimeout(n),r()},n=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e);t?.addEventListener("abort",s,{once:!0})})}function Ec(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Dn(e,t){if(!e)throw new Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function Gs(e){if(!e)return{};if(e instanceof Headers){const t={};return e.forEach((r,s)=>{t[s]=r}),t}return e}var kj="X-Run-Id";function Aj(e){return e===void 0?{}:{[kj]:e}}function cl(e,t){const r=e.indexOf("#"),s=r===-1?"":e.slice(r),n=r===-1?e:e.slice(0,r),o=n.indexOf("?"),l=o===-1?n:n.slice(0,o),i=new URLSearchParams(o===-1?"":n.slice(o+1));for(const[d,u]of Object.entries(t))i.set(d,u);const c=i.toString();return`${l}${c.length===0?"":`?${c}`}${s}`}async function*Oj(e,t){try{const r=fN();let s="";for(;!t?.aborted;){let n;try{n=await e.read()}catch(c){if(t?.aborted)return;throw new ll(c)}const{done:o,value:l}=n;if(o)break;s+=r.decode(l,{stream:!0});const i=s.split(`
|
|
15
|
+
`);s=i.pop()||"";for(const c of i){const d=c.endsWith("\r")?c.slice(0,-1):c;d.trim()&&(yield d)}}if(s+=r.decode(),s.trim()&&!t?.aborted)throw new fm}finally{e.releaseLock()}}function Dj(e){return im(e)}function Mj(e){const t=Ve(e)?.model;if(typeof t=="string")return t;const r="usage"in e?e.usage:void 0;if(Array.isArray(r)){const s=r[0]?.model;if(typeof s=="string")return s}}async function*_j(e,t){let r,s,n,o;for await(const l of e){if(l==="id"||l.startsWith("id:")){const h=l==="id"?"":l.slice(3);o=h.startsWith(" ")?h.slice(1):h;continue}if(l.startsWith(":")||l.startsWith("event:")||l.startsWith("retry:"))continue;const i=hN(l);if(i==="[DONE]"){yield{chunk:Hh({type:Xo.RUN_FINISHED,threadId:r??t?.threadId??"",runId:s??t?.runId??"",timestamp:Date.now()},{finishReason:"stop",...n!==void 0?{model:n}:{}})};return}const c=Dj(JSON.parse(i));"threadId"in c&&typeof c.threadId=="string"&&(r=c.threadId),"runId"in c&&typeof c.runId=="string"&&(s=c.runId);const d=Mj(c);d!==void 0&&(n=d);const u=o;o=void 0,yield{chunk:c,...u!==void 0?{id:u}:{}}}}async function dl(e){if(!e.ok){if(e.status===401){const t=await e.clone().json().catch(()=>null);if(nN(t))throw new Uo(t.error.provider)}throw new Error(`HTTP error! status: ${e.status} ${e.statusText}`)}}function Pj(e,t){const r={threadId:e};return t?.limit!==void 0&&(r.limit=String(t.limit)),t?.before!==void 0&&(r.before=t.before),r}function Fj(e){return e===null||typeof e!="object"?{truncated:!1}:!("truncated"in e)||e.truncated!==!0?{truncated:!1}:!("cursor"in e)||typeof e.cursor!="string"||e.cursor===""?{truncated:!1}:{truncated:!0,cursor:e.cursor}}async function Lj(e,t,r,s,n,o){const l=await e(cl(t,Pj(n,o)),{method:"GET",headers:{Accept:"application/json",...r},credentials:s});await dl(l);const i=await l.json(),c=i.activeRun&&typeof i.activeRun.runId=="string"?{runId:i.activeRun.runId}:null,d=i.interrupts&&typeof i.interrupts.runId=="string"&&Array.isArray(i.interrupts.pending)&&i.interrupts.pending.length>0?{runId:i.interrupts.runId,pending:i.interrupts.pending}:null;return{messages:Array.isArray(i.messages)?Wo(i.messages):[],activeRun:c,interrupts:d,page:Fj(i.page)}}async function zj(e,t,r,s,n){const o=await e(cl(t,{threadId:n}),{method:"GET",headers:{Accept:"application/json",...r},credentials:s});await dl(o);const l=await o.json();if(l===null)return{resumeSnapshot:null,activeRun:null};if(typeof l!="object"||Array.isArray(l))throw new Error(`Generation hydration expected a JSON object from ${t}, received ${Array.isArray(l)?"an array":typeof l}.`);const i=l,c=i.activeRun&&typeof i.activeRun.runId=="string"?{runId:i.activeRun.runId}:null;return{resumeSnapshot:i.resumeSnapshot??null,activeRun:c}}async function*Zo(e,t,r){await dl(e),yield*_j(Oj(uN(e),t),r)}async function*$j(e,t){for await(const{chunk:r}of Zo(e,t))yield r}function kc(e,t,r,s){return async function*(n,o){let l;try{l=await e(t,{...r,headers:{...r.headers,...n},...o?{signal:o}:{}})}catch(i){throw new ll(i)}yield*s(l,o)}}async function*Ac(e,t,r){const s=Rj(r);for(;;){if(t?.aborted)return;const n=s.lastEventId!==void 0?{"Last-Event-ID":s.lastEventId}:{};let o=!1,l=!1;try{for await(const{chunk:i,id:c}of e(n,t))s.note(c)!=="duplicate"&&(l=!0,(i.type==="RUN_FINISHED"||i.type==="RUN_ERROR")&&(o=!0),yield i)}catch(i){if(t?.aborted)return;if((i instanceof fm||i instanceof ll)&&s.lastEventId!==void 0){await s.waitBeforeReconnect(l,t);continue}throw i}if(t?.aborted||o)return;if(s.lastEventId!==void 0){if(l){await s.waitBeforeReconnect(!0,t);continue}throw new jj}return}}function Oc(e){if(!e)throw new Error("Connection adapter is required");const t="connect"in e,r="subscribe"in e,s="send"in e;if(t&&(r||s))throw new Error("Connection adapter must provide either connect or both subscribe and send, not both modes");if(r&&s){const d=e.joinRun?.bind(e),u=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...d?{joinRun:d}:{},...u?{hydrate:u}:{}}}if(!t)throw new Error("Connection adapter must provide either connect or both subscribe and send");let n=[],o=[],l;function i(d,u){u&&um.set(d,u);const h=o.shift();h?h(d):n.push(d)}async function c(d){const u=()=>l!==o||n.length===0&&(o.length>0||d?.aborted);for(let h=0;h<16&&!d?.aborted;h++){if(u())return;await Promise.resolve()}for(;!d?.aborted;){if(u())return;await new Promise(h=>setTimeout(h,0))}}return{subscribe(d){const u=n.splice(0),h=[];return n=u,o=h,(async function*(){l=h;try{for(;!d?.aborted;){let m;const p=u.shift();p!==void 0?m=p:m=await new Promise(b=>{const w=()=>b(null);h.push(x=>{d?.removeEventListener("abort",w),b(x)}),d?.addEventListener("abort",w,{once:!0})}),m!==null&&(yield m)}}finally{l===h&&(l=void 0)}})()},async send(d,u,h,m){let p=!1,b,w;try{const x=e.connect(d,u,h,m);for await(const N of x)"threadId"in N&&typeof N.threadId=="string"&&(b=N.threadId),"runId"in N&&typeof N.runId=="string"&&(w=N.runId),(N.type==="RUN_FINISHED"||N.type==="RUN_ERROR")&&(p=!0),i(N,m?.runId);!h?.aborted&&!p&&i(Hh({type:Xo.RUN_FINISHED,threadId:Dn(b??m?.threadId,"threadId"),runId:Dn(w??m?.runId,"runId"),timestamp:Date.now()},{finishReason:"stop",model:"connect-wrapper"}),m?.runId)}catch(x){if(!h?.aborted&&!p)try{const N=x instanceof Error?x.message:"Unknown error in connect()";i({type:Xo.RUN_ERROR,threadId:Dn(b??m?.threadId,"threadId"),runId:Dn(w??m?.runId,"runId"),timestamp:Date.now(),message:N},m?.runId)}catch{}throw x}await c(h)},...typeof e.joinRun=="function"?{joinRun:(d,u)=>e.joinRun(d,u)}:{},...(()=>{const d=e.hydrate;return typeof d=="function"?{hydrate:(u,h)=>d(u,h)}:{}})()}}function Vj(e,t,r,s){const n=ej(e),o={...s.body,...r?.forwardedProps??{},...t};return{threadId:r?.threadId??Ec("thread"),runId:r?.runId??Ec("run"),...r?.parentRunId!==void 0&&{parentRunId:r.parentRunId},...r?.resume!==void 0&&{resume:r.resume},state:{},messages:n,tools:r?.clientTools??[],context:[],forwardedProps:o,data:{...o}}}function CR(e,t={}){return{async*connect(r,s,n,o){const l=typeof e=="function"?e():e,i=typeof t=="function"?await t():t,c={"Content-Type":"application/json",...Gs(i.headers),...Gs(o?.headers),...Aj(o?.runId)},d=Vj(r,s,o,i),u=i.fetchClient??fetch,h=n||i.signal;yield*Ac(kc(u,l,{method:"POST",headers:c,body:JSON.stringify(d),credentials:i.credentials||"same-origin"},(m,p)=>Zo(m,p,{...o?.threadId!==void 0?{threadId:o.threadId}:{},...o?.runId!==void 0?{runId:o.runId}:{}})),h,i.reconnect)},async*joinRun(r,s){const n=typeof e=="function"?e():e,o=typeof t=="function"?await t():t,l=cl(n,{offset:"-1",runId:r}),i={...Gs(o.headers)},c=o.fetchClient??fetch,d=s||o.signal;yield*Ac(kc(c,l,{method:"GET",headers:i,credentials:o.credentials||"same-origin"},(u,h)=>Zo(u,h,{runId:r})),d,o.reconnect)},async hydrate(r,s){const n=typeof e=="function"?e():e,o=typeof t=="function"?await t():t;return Lj(o.fetchClient??fetch,n,Gs(o.headers),o.credentials||"same-origin",r,s)},async hydrateGeneration(r){const s=typeof e=="function"?e():e,n=typeof t=="function"?await t():t;return zj(n.fetchClient??fetch,s,Gs(n.headers),n.credentials||"same-origin",r)}}}function Bj(e){return{async*connect(t,r,s,n){if(!s)throw new Error("fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.");if(!n)throw new Error("fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.");const o=await e({messages:t,data:r,threadId:n.threadId,runId:n.runId,...n.parentRunId!==void 0?{parentRunId:n.parentRunId}:{},...n.resume!==void 0?{resume:n.resume}:{}},{signal:s,headers:n.headers});o instanceof Response?yield*$j(o,s):yield*Uj(o,s)}}}async function*Uj(e,t){if(t.aborted)return;const r=e[Symbol.asyncIterator](),s=new Promise(n=>{t.addEventListener("abort",()=>n({done:!0,value:void 0}),{once:!0})});try{for(;;){const n=await Promise.race([r.next(),s]);if(n.done)return;yield n.value}}finally{await r.return?.()}}function gr(e){return e.resumable}function ho(e,t){const r=FN(e.descriptor);return r?{...t,metadata:PN(r)}:t}function qj(e){return"cancel"in e&&"clearResolution"in e}var Wj=new Set(["invalid-payload","invalid-edited-args","invalid-tool-output","invalid-response-schema","unknown-interrupt","expired","stale","conflict","legacy-unsupported"]),Kj=new Set(["incomplete-batch","item-validation-failed","unsupported-bulk-operation","async-resolver","inactive-transaction","mixed-provenance","transport","server","protocol","invalid-response-schema","expired","stale","conflict","legacy-submit-failed"]);function Qt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function hm(e){return Qt(e)&&e.kind==="approval"&&typeof e.toolName=="string"&&"input"in e}function mm(e){return Qt(e)&&e.kind==="client_tool"&&typeof e.toolName=="string"&&"input"in e}function Hj(e){return hm(e.metadata)||mm(e.metadata)}function Dc(e){return kN(e)}function Gj(e){if(!Qt(e.metadata))return!1;const t=e.metadata[Sa];return!Qt(t)||t.v!==void 0&&t.v!==1?!1:t.kind==="generic"||t.kind==="tool-approval"||t.kind==="client-tool-execution"||"definitionId"in t||"key"in t||"batchIndex"in t||"payloadSchemaHash"in t}function Yj(e){if(!Qt(e.metadata))return!1;const t=e.metadata[Sa];return!Qt(t)||t.kind!=="generic"?!1:"definitionId"in t||"key"in t||"batchIndex"in t||"payloadSchemaHash"in t}function Jj(e){return e.metadata?.["tanstack:interruptPayload"]}function Qj(e){return e==="tanstack:client_tool_execution"||e==="client_tool_input"}function rn(e){if(e.responseSchema!==void 0)try{return ds(cs(e.responseSchema))}catch{return}}function Mc(e){if(e!==void 0)try{return DN(e)}catch{return}}function qr(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&"then"in e&&typeof e.then=="function"}function Mn(e,t,r){if(e===void 0)return{valid:!0,payload:t};if(Lr(e)){const s=e["~standard"].validate(t),n=o=>o.issues?{code:r,message:o.issues[0]?.message??"Schema validation failed."}:{valid:!0,payload:o.value};return qr(s)?Promise.resolve(s).then(n):n(s)}return{valid:!0,payload:t}}function Xj(e){for(const t of Wj)if(t===e)return!0;return!1}function Zj(e){for(const t of Kj)if(t===e)return!0;return!1}function _c(e){if(!Qt(e))return!1;const t=e.scope,r=e.code;return typeof r=="string"&&typeof e.message=="string"&&typeof e.retryable=="boolean"&&typeof e.threadId=="string"&&typeof e.interruptedRunId=="string"&&typeof e.generation=="number"?t==="item"?Xj(r)&&typeof e.interruptId=="string"&&(e.source==="client"||e.source==="server"):t==="batch"&&Zj(r)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(s=>typeof s=="string")&&(e.source==="client"||e.source==="server"||e.source==="transport"):!1}function eI(e){return _c(e)?[e]:!Qt(e)||!Array.isArray(e.errors)?[]:e.errors.every(_c)?e.errors:[]}function pm(e,t){if(e.length!==t.length)return!1;const r=[...e].sort(),s=[...t].sort();return r.every((n,o)=>n===s[o])}function Pc(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&pm(e.interruptIds,t.interruptIds)}function tI(e,t,r){const s=r.filter(i=>i.source!=="transport"),n=i=>t.includes(i)&&s.some(c=>Pc(i,c)),o=e.filter(i=>!n(i)),l=t.filter(i=>!s.some(c=>Pc(i,c)));return Object.freeze({rootErrors:Object.freeze([...o,...r]),submissionRootErrors:Object.freeze([...l,...s])})}function rI(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;const r=t.resolutions.map(s=>s.interruptId);return e.scope==="item"?r.includes(e.interruptId):pm(e.interruptIds,r)}function mo(e,t,r){const s=rn(e)??r?.responseSchemaHash;return Qe({v:1,kind:"generic",interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...s!==void 0?{responseSchemaHash:s}:{},...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{}})}function sI(e,t){const r=Qe(e.descriptor),s=e.error===void 0?Object.freeze([]):Object.freeze([Qe(e.error)]),n=s[0];return{id:r.id,interruptId:r.id,reason:r.reason,...r.message!==void 0?{message:r.message}:{},...r.responseSchema!==void 0?{responseSchema:r.responseSchema}:{},...r.expiresAt!==void 0?{expiresAt:r.expiresAt}:{},...r.metadata!==void 0?{metadata:r.metadata}:{},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:s,...n!==void 0?{error:n}:{},canResolve:e.canResolve}}var nI=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;const t=new Map;for(const r of e.interrupts??[]){if(t.has(r.id))throw new Error(`Duplicate interrupt definition id: ${r.id}`);t.set(r.id,r)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t="live"){this.activeSubmissionOperation=void 0,this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:Qe(e.interrupts)};const r=new Map;for(const s of e.interrupts){const n=Dc(s);n?.kind==="generic"&&n.definitionId!==void 0&&n.key!==void 0&&n.batchIndex!==void 0&&r.set(n.batchIndex,(r.get(n.batchIndex)??0)+1)}this.items=e.interrupts.map(s=>this.hydrateInterrupt(s,e,r)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind==="generic"&&e.definition!==void 0)}reset(e){this.activeSubmissionOperation=void 0,this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??"live")}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e=="boolean"){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(const e of this.items)gr(e)&&(e.validationGeneration++,e.resolution=Object.freeze(ho(e,{interruptId:e.descriptor.id,status:"cancelled"})),e.status="staged",e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw new Error("Interrupt submission is already active.");const e=this.retrySubmission;if(!e){this.addRootError("transport","There is no retryable interrupt submission.",!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){const r=this.items.find(s=>s.kind==="client-tool-execution"&&s.binding?.kind==="client-tool-execution"&&s.binding.toolCallId===e||s.kind==="generic"&&Qj(s.descriptor.reason)&&s.descriptor.toolCallId===e&&mm(s.descriptor.metadata));return r?(this.resolveItem(r.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){const r=this.items.find(s=>s.descriptor.id===e&&(s.kind==="tool-approval"||s.kind==="generic"&&s.descriptor.reason==="approval_required"&&hm(s.descriptor.metadata)));return r?(this.resolveItem(r.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,r){const s=Qe(e),n=Dc(s),o=n===void 0&&Hj(s);if(n===void 0&&!o)return Gj(s)?{descriptor:s,binding:mo(s,t,void 0),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","The interrupt binding is invalid or incomplete."),validationGeneration:0}:{descriptor:s,binding:void 0,kind:"unbound",status:"pending",canResolve:!1,resumable:!1,validationGeneration:0};const l=n!==void 0&&n.interruptId===s.id&&n.interruptedRunId===t.interruptedRunId&&n.generation===t.generation&&rn(s)===n.responseSchemaHash,i=n!==void 0&&n.interruptId===s.id&&n.interruptedRunId===t.interruptedRunId&&n.generation===t.generation&&n.responseSchemaHash===(rn(s)??n.responseSchemaHash);if(n!==void 0&&Yj(s)&&(!i||n.kind!=="generic"||n.definitionId===void 0||n.key===void 0||n.batchIndex===void 0))return{descriptor:s,binding:mo(s,t,n),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","The interrupt binding does not match this interrupted run."),validationGeneration:0};if(i&&n.kind==="tool-approval"){const d=this.tools?.find(u=>u.name===n.toolName);if(d?.needsApproval===!0&&s.toolCallId===n.toolCallId)try{const u=RN(d.approvalSchema,d.inputSchema);if(yc(d.inputSchema)===n.inputSchemaHash&&u.approvalSchemaHash===n.approvalSchemaHash&&u.responseSchemaHash===n.responseSchemaHash)return{descriptor:s,binding:Qe(n),kind:"tool-approval",status:"pending",canResolve:!0,resumable:!0,tool:d,validationGeneration:0}}catch{}}if(i&&n.kind==="client-tool-execution"){const d=this.tools?.find(u=>u.name===n.toolName);if(d!==void 0&&s.toolCallId===n.toolCallId&&yc(d.outputSchema)===n.outputSchemaHash)return{descriptor:s,binding:Qe(n),kind:"client-tool-execution",status:"pending",canResolve:!0,resumable:!0,tool:d,validationGeneration:0}}if(n!==void 0&&n.kind==="generic"&&n.definitionId!==void 0&&n.key!==void 0&&n.batchIndex!==void 0&&n.key.length>0&&r.get(n.batchIndex)!==1)return{descriptor:s,binding:Qe(n),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","Generic interrupt batch contains a duplicate batchIndex."),validationGeneration:0};if(l&&n.kind==="generic"&&n.definitionId!==void 0&&n.key!==void 0&&n.batchIndex!==void 0&&n.key.length>0&&r.get(n.batchIndex)===1){const d=this.interruptDefinitions.get(n.definitionId);if(d!==void 0&&Mc(d.responseSchema)===n.responseSchemaHash&&(d.payloadSchema===void 0?n.payloadSchemaHash===void 0:n.payloadSchemaHash===Mc(d.payloadSchema))){const u=Jj(s);return{descriptor:s,binding:Qe(n),definition:d,kind:"generic",status:"pending",canResolve:!0,resumable:!0,...u===void 0?{}:{payload:Qe(u)},validationGeneration:0}}}const c=o||n!==void 0&&n.interruptId===s.id&&n.interruptedRunId===t.interruptedRunId&&n.generation===t.generation&&(n.kind!=="generic"||rn(s)===void 0||n.responseSchemaHash===rn(s));return{descriptor:s,binding:mo(s,t,n),kind:"generic",status:"pending",canResolve:c,resumable:c,validationGeneration:0}}buildSnapshot(e){const t=this.requireHydration(),r=this.items.filter(s=>s.kind!=="client-tool-execution"&&s.status!=="submitting").map(s=>{const n=sI(s,t);if(s.kind==="unbound"||s.binding===void 0){const i={...n,kind:"unbound",canResolve:!1};return Object.freeze(i)}if(s.kind==="tool-approval"&&s.binding.kind==="tool-approval"){const i=Qe(s.binding),c={...n,kind:"tool-approval",binding:i,toolName:s.binding.toolName,toolCallId:s.binding.toolCallId,originalArgs:Qe(s.binding.originalArgs),cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:(d,u)=>{const h=Qt(u)?u:void 0;this.resolveItem(s.descriptor.id,{approved:d,...d&&h?.editedArgs!==void 0?{editedArgs:h.editedArgs}:{},...h?.payload!==void 0?{payload:h.payload}:{}},e)}};return Object.freeze(c)}const o=s.binding.kind==="generic"?Qe(s.binding):Qe({v:1,kind:"generic",interruptId:s.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof s.binding.responseSchemaHash=="string"?{responseSchemaHash:s.binding.responseSchemaHash}:{}});if(s.definition!==void 0&&s.binding.kind==="generic"){const i={...n,kind:"generic",definitionId:s.definition.id,key:s.binding.key??"",payload:s.payload,binding:o,cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:c=>this.resolveItem(s.descriptor.id,c,e)};return Object.freeze(i)}const l={...n,kind:"generic",binding:o,cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:i=>this.resolveItem(s.descriptor.id,i,e)};return Object.freeze(l)});return Object.freeze(r)}publish(e="live"){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)}resolveItem(e,t,r){this.assertItemMutable(r);const s=this.findItem(e);if(this.invalidateRetry(),!s.canResolve){s.status="error",s.error=this.itemError(e,"invalid-response-schema","The interrupt response schema is invalid and cannot be resolved."),r||this.publish();return}const n=++s.validationGeneration,o=this.validateCandidate(s,t);if(qr(o)){s.status="validating",s.error=void 0,r||this.publish(),Promise.resolve(o).then(l=>{n===s.validationGeneration&&this.applyValidation(s,l,r)}).catch(l=>{n===s.validationGeneration&&this.applyValidation(s,{code:this.validationCode(s),message:l instanceof Error?l.message:String(l)},r)});return}this.applyValidation(s,o,r)}cancelItem(e,t){this.assertItemMutable(t);const r=this.findItem(e);this.invalidateRetry(),r.validationGeneration++,r.resolution=Object.freeze(ho(r,{interruptId:e,status:"cancelled"})),r.status="staged",r.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);const r=this.findItem(e);this.invalidateRetry(),r.validationGeneration++,r.resolution=void 0,r.error=void 0,r.status="pending",t||this.publish()}maybeSubmit(){const e=this.items.some(o=>o.kind==="generic"),t=this.items.filter(o=>gr(o)&&!(e&&o.kind==="client-tool-execution"));if(t.length===0||t.some(o=>o.resolution===void 0||o.status!=="staged"))return;const r=this.requireHydration(),s=bN(t.map(o=>o.resolution).filter(o=>o!==void 0)),n=Object.freeze({threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation,resolutions:s.resolutions,canonicalResolutions:s.canonicalResolutions,fingerprint:s.fingerprint});this.submitBatch(n)}applyValidation(e,t,r){if(!("valid"in t)){e.status="error";const s=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=s,e.kind==="client-tool-execution"&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(n=>!(n.code==="item-validation-failed"&&n.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:"batch",code:"item-validation-failed",message:s.message,source:"client",retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:s.threadId,interruptedRunId:s.interruptedRunId,generation:s.generation})])),r||this.publish();return}e.resolution=Qe(ho(e,{interruptId:e.descriptor.id,status:"resolved",payload:t.payload})),e.status="staged",e.error=void 0,r||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind==="generic"){const r=Mn(e.definition?.responseSchema??e.descriptor.responseSchema,t,"invalid-payload");if(e.definition===void 0)return r;const s=n=>"valid"in n?{valid:!0,payload:t}:n;return qr(r)?Promise.resolve(r).then(s):s(r)}return e.kind==="client-tool-execution"?Mn(e.tool?.outputSchema,t,"invalid-tool-output"):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!Qt(t)||typeof t.approved!="boolean")return{code:"invalid-payload",message:"Tool approval resolutions require an approved boolean."};const r=t.approved,s=t.editedArgs;if(!r&&s!==void 0)return{code:"invalid-edited-args",message:"Rejected tool approvals cannot edit tool arguments."};if(r&&s!==void 0){const n=Mn(e.tool?.inputSchema,s,"invalid-edited-args");return qr(n)?Promise.resolve(n).then(o=>"valid"in o?this.validateApprovalPayload(e,t,o.payload):o):"valid"in n?this.validateApprovalPayload(e,t,n.payload):n}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,r){const s=t.approved===!0,n=this.approvalBranchSchema(e.tool,s),o=t.payload;if(n===void 0&&o!==void 0)return{code:"invalid-payload",message:"This approval branch does not accept a payload."};if(n!==void 0&&o===void 0)return{code:"invalid-payload",message:"This approval branch requires a payload."};const l=Mn(n,o,"invalid-payload"),i=c=>"valid"in c?{valid:!0,payload:{approved:s,...r!==void 0?{editedArgs:r}:{},...n!==void 0?{payload:c.payload}:{}}}:c;return qr(l)?Promise.resolve(l).then(i):i(l)}approvalBranchSchema(e,t){const r=e?.approvalSchema;return!Qt(r)||!("approve"in r||"reject"in r)?r:t?r.approve:r.reject}validationCode(e){return e.kind==="client-tool-execution"?"invalid-tool-output":"invalid-payload"}resolveBooleanBulk(e){const t=this.items.filter(r=>gr(r)&&r.kind!=="client-tool-execution");if(!t.every(r=>r.kind==="tool-approval"&&this.approvalBranchSchema(r.tool,e)===void 0)||t.length===0){this.addRootError("unsupported-bulk-operation","Boolean bulk resolution requires payloadless tool approvals.",!1);return}this.invalidateRetry();for(const r of t)r.validationGeneration++,r.resolution=Qe({interruptId:r.descriptor.id,status:"resolved",payload:{approved:e}}),r.status="staged",r.error=void 0;this.publish(),this.maybeSubmit()}resolveTransaction(e){const t=this.items.map(o=>({status:o.status,...o.resolution!==void 0?{resolution:o.resolution}:{},...o.error!==void 0?{error:o.error}:{},validationGeneration:o.validationGeneration})),r={active:!0};this.activeTransaction=r;const s=this.buildSnapshot(r).filter(qj);let n;try{for(const o of s){const l=e(o);if(l!==void 0){n={code:qr(l)?"async-resolver":"inactive-transaction",message:qr(l)?"Interrupt transaction resolvers must be synchronous.":"Interrupt transaction resolvers must return literal undefined."};break}}n===void 0&&this.items.some(o=>gr(o)&&o.kind!=="client-tool-execution"&&(o.resolution===void 0||o.status!=="staged"))&&(n={code:"incomplete-batch",message:"Interrupt transaction did not resolve every item."})}catch(o){n={code:"item-validation-failed",message:o instanceof Error?o.message:String(o)}}finally{r.active=!1,this.activeTransaction=void 0}if(n){this.restoreCheckpoints(t),this.addRootError(n.code,n.message,!1);return}this.publish(),this.maybeSubmit()}restoreCheckpoints(e){this.items.forEach((t,r)=>{const s=e[r];s&&(t.status=s.status,t.resolution=s.resolution,t.error=s.error,t.validationGeneration=s.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active)throw new Error("Interrupt transaction is inactive.");if(this.activeTransaction&&e!==this.activeTransaction)throw new Error("Interrupt transaction is inactive.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}assertRootMutable(){if(this.activeTransaction)throw new Error("Interrupt transaction is already active.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){const t={submission:e};this.activeSubmissionOperation=t,this.resuming=!0,this.retrySubmission=void 0;for(const r of this.items)gr(r)&&(r.status="submitting");this.publish(),this.performSubmission(t)}async performSubmission(e){try{await this.options.submit(e.submission)}catch(t){if(this.activeSubmissionOperation!==e)return;this.handleSubmissionFailure(t,e.submission)}finally{this.activeSubmissionOperation===e&&(this.activeSubmissionOperation=void 0,this.resuming=!1,this.publish())}}handleSubmissionFailure(e,t){const r=eI(e);if(r.length===0){const c=e instanceof Error?e.message:String(e);this.addRootError("transport",c,!0,"transport"),this.retrySubmission=t;for(const d of this.items)gr(d)&&(d.status="error");return}const s=r.filter(c=>rI(c,t));s.length!==r.length&&this.addRootError("protocol","Interrupt submission errors did not match the active batch.",!1);let n=!1,o=!1;const l=[];for(const c of s)if((c.code==="stale"||c.code==="expired"||c.code==="conflict")&&(n=!0),o||=c.retryable,c.scope==="item"){const d=this.items.find(u=>gr(u)&&u.descriptor.id===c.interruptId);d&&(d.status="error",d.error=Qe(c))}else l.push(Qe(c));const i=tI(this.rootErrors,this.submissionRootErrors,l);this.rootErrors=i.rootErrors,this.submissionRootErrors=i.submissionRootErrors;for(const c of this.items)gr(c)&&c.status==="submitting"&&(c.status="error");this.retrySubmission=o&&!n?t:void 0}addRootError(e,t,r,s="client"){const n=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:"batch",code:e,message:t,source:s,retryable:r,interruptIds:Object.freeze(this.items.filter(gr).map(o=>o.descriptor.id)),threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation})]),this.publish()}findItem(e){const t=this.items.find(r=>r.descriptor.id===e);if(!t)throw new Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw new Error("InterruptManager is not hydrated.");return this.hydration}itemError(e,t,r,s){const n=this.requireHydration();return Object.freeze({scope:"item",interruptId:e,code:t,message:r,...s!==void 0?{path:Object.freeze([...s])}:{},source:"client",retryable:!1,threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation})}};function aI(e,...t){const r=e?.();if(zt(r))return r;for(const s of t)if(zt(s))return s}async function oI(e,t){if(!t)throw new Uh;return await e.prepare(t),e.headers(t)}function iI(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():Math.random().toString(36).slice(2)}var _n;function Fc(){return _n!==void 0||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__=iI()),_n=globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__),_n}var lI=0;function sr(e){return e==null||e===""?"missing":`value-${encodeURIComponent(String(e))}`}function ei(e){const t=e.runtimeId??Fc(),r=e.eventId&&e.eventId.length>0?e.eventId:[e.source,e.eventType,sr(t),sr(e.clientId),sr(e.requestId),sr(e.streamId),sr(e.hookId),sr(e.threadId),sr(e.runId),sr(e.messageId),sr(e.toolCallId),sr(e.sequence),e.timestamp,Fc(),lI++].join(":");return{...e,runtimeId:t,eventId:r}}var cI=class extends Em{constructor(){super({pluginId:"tanstack-ai-devtools"})}},Lc=Symbol.for("tanstack.ai.devtools.eventClient");function dI(){const e=globalThis,t=e[Lc];if(t)return t;const r=new cI;return e[Lc]=r,r}var cn=dI();function Et(e,t){cn.emit(e,t)}var gm=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent("client:created",{initialMessageCount:e})}loadingChanged(e){this.emitEvent("client:loading:changed",{isLoading:e})}errorChanged(e){this.emitEvent("client:error:changed",{error:e})}textUpdated(e,t,r,s){this.emitEvent("text:chunk:content",{streamId:e,messageId:t,content:r,...s})}toolCallStateChanged(e,t,r,s,n,o,l){this.emitEvent("tools:call:updated",{streamId:e,messageId:t,toolCallId:r,toolName:s,state:n,arguments:o,...l})}thinkingUpdated(e,t,r,s,n){this.emitEvent("text:chunk:thinking",{streamId:e,messageId:t,content:r,delta:s,...n})}structuredOutputChanged(e,t,r,s,n){this.emitEvent(e,{streamId:t,messageId:r,...s,...n})}approvalRequested(e,t,r,s,n,o,l){this.emitEvent("tools:approval:requested",{streamId:e,messageId:t,toolCallId:r,toolName:s,input:n,approvalId:o,...l})}messageAppended(e,t,r){const s=e.parts.filter(n=>n.type==="text").map(n=>n.content).join(" ");this.emitEvent("text:message:created",{streamId:t,messageId:e.id,role:e.role,content:s,parts:e.parts,...r})}messageSent(e,t){const r=typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.content).join("");this.emitEvent("text:message:created",{messageId:e,role:"user",content:r,...Array.isArray(t)&&{parts:t}}),this.emitEvent("text:message:user",{messageId:e,role:"user",content:r,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent("client:reloaded",{fromMessageIndex:e})}stopped(){this.emitEvent("client:stopped")}messagesCleared(){this.emitEvent("client:messages:cleared")}toolResultAdded(e,t,r,s,n){this.emitEvent("tools:result:added",{toolCallId:e,toolName:t,output:r,state:s,...n})}toolApprovalResponded(e,t,r,s){this.emitEvent("tools:approval:responded",{approvalId:e,toolCallId:t,approved:r,...s})}toolFixtureApplied(e){this.emitEvent("devtools:tool-fixture:applied",{...e})}},uI=class extends gm{emitEvent(e,t){const r=Date.now(),s=e.startsWith("text:")||e.startsWith("tools:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",n=e.startsWith("client:")||e.startsWith("tools:")||e.startsWith("text:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",o=s?"user-visible":"client-state",l={hookId:this.clientId,...typeof t?.threadId=="string"?{threadId:t.threadId}:{},...typeof t?.runId=="string"?{runId:t.runId}:{},...typeof t?.streamId=="string"?{streamId:t.streamId}:{},...typeof t?.messageId=="string"?{messageId:t.messageId}:{},...typeof t?.toolCallId=="string"?{toolCallId:t.toolCallId}:{}};if(n){const i=ei({eventType:e,clientId:this.clientId,...l,source:"client",visibility:o,timestamp:r});cn.emit(e,{...t,...i})}else{const i=ei({eventType:e,source:"client",visibility:"client-state",timestamp:r});cn.emit(e,{...t,...i})}}},fI=class extends gm{emitEvent(){}},hI=class{events;constructor(e){this.events=new fI(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,r,s){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return""}observeChunk(e){}recordMemoryState(e){}recordCompactionEvent(e,t){}recordCompactionState(e){}recordSkillsState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},mI=e=>new hI(e);function zc(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function $c(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function Vc(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function pI(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var gI=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,r,s){this.adapter=e,this.id=t,this.applyMessages=r,this.applyResume=s}writeState(){const e=[...this.lastMessages];if(e.length===0&&!this.lastResume){const s=this.generation;this.runOperation(()=>{if(s===this.generation)return this.adapter.removeItem(this.id)});return}const t=this.generation,r={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,r)})}readInitial(){try{const e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(zc).catch(()=>{});const t=zc(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;const t=this.messagesGeneration;e.then(r=>{!r||this.messagesGeneration!==t||(this.lastResume=r.resume??null,this.lastMessages=r.messages,this.applyMessages(r.messages),r.resume&&this.applyResume&&this.applyResume(r.resume))}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.lastMessages=[],this.lastResume=null;const e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){const t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{const t=e();if(t instanceof Promise){this.queuePending=!0;const r=t.catch(()=>{});this.queue=r,r.finally(()=>{this.queue===r&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(const t of e.messages)this.clearedMessageIds.add(t.id);for(const t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){const t=_t(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const r=$c(e);if(r&&this.clearedToolCallIds.has(r))return!0;const s=pI(e);if(s&&this.clearedMessageIds.has(s))return r&&this.clearedToolCallIds.add(r),!0;const n=Vc(e);return n?!!this.clearedMessageIds.has(n):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){const e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){const t=Vc(e);t&&this.clearedMessageIds.add(t);const r=$c(e);r&&this.clearedToolCallIds.add(r)}isRunlessChunkFromIgnoredRun(e){return _t(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type==="TEXT_MESSAGE_START"||e.type==="TEXT_MESSAGE_CONTENT"||e.type==="TOOL_CALL_START"||e.type==="TOOL_CALL_ARGS"||e.type==="TOOL_CALL_END"||e.type==="TOOL_CALL_RESULT"||e.type==="MESSAGES_SNAPSHOT"||e.type==="RUN_ERROR"}};function Bc(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function Uc(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function vI(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var yI=class{clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;snapshotClear(e){for(const t of e.messages)this.clearedMessageIds.add(t.id);for(const t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}shouldIgnoreChunk(e){const t=_t(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const r=Bc(e);if(r&&this.clearedToolCallIds.has(r))return!0;const s=vI(e);if(s&&this.clearedMessageIds.has(s))return r&&this.clearedToolCallIds.add(r),!0;const n=Uc(e);return!!(n&&this.clearedMessageIds.has(n))}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetActiveRuns(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}takeRunlessRunId(){const e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){const t=Uc(e);t&&this.clearedMessageIds.add(t);const r=Bc(e);r&&this.clearedToolCallIds.add(r)}isRunlessChunkFromIgnoredRun(e){return _t(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type==="TEXT_MESSAGE_START"||e.type==="TEXT_MESSAGE_CONTENT"||e.type==="TOOL_CALL_START"||e.type==="TOOL_CALL_ARGS"||e.type==="TOOL_CALL_END"||e.type==="TOOL_CALL_RESULT"||e.type==="MESSAGES_SNAPSHOT"||e.type==="RUN_ERROR"}};function bI(e){const t=new Set;for(const r of e??[]){if(t.has(r.id))throw new Error(`Duplicate interrupt definition id: ${r.id}`);t.add(r.id)}}function qc(e){const{connection:t,fetcher:r}=e;if(t&&r)throw new Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(r)return Bj(r);throw new Error("ChatClient: either `connection` or `fetcher` is required.")}function Wc(e){return"connect"in e}function Kc(e){if(e.type!=="RUN_FINISHED"||e.outcome?.type==="interrupt")return!1;const t=e;return t.finishReason!==void 0?t.finishReason==="tool_calls":Ve(e)?.finishReason==="tool_calls"}function Hc(e){const t={whenBusy:"queue",drain:"fifo",onOverflow:"reject"};if(!e)return t;if(typeof e=="string")return{...t,whenBusy:e};if(typeof e=="function")return{...t,strategy:e};const r=e.maxSize;if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new Error("ChatClient: queue.maxSize must be a non-negative integer");return{whenBusy:e.whenBusy??"queue",drain:e.drain??"fifo",onOverflow:e.onOverflow??"reject",...r!==void 0?{maxSize:r}:{}}}function xI(e){const t=e.at(-1)?.body,r=[];for(const o of e){if(typeof o.content!="string")break;r.push(o.content)}if(r.length===e.length)return{content:r.join(`
|
|
16
|
+
`),...t!==void 0?{body:t}:{}};const s=[];let n;for(const o of e){if(typeof o.content=="string"){s.push({type:"text",content:o.content});continue}typeof o.content.content=="string"?s.push({type:"text",content:o.content.content}):s.push(...o.content.content),n=Kh(n,o.content.metadata)}return{content:{content:s,...n!==void 0?{metadata:n}:{}},...t!==void 0?{body:t}:{}}}function SI(e){if(!(e===null||typeof e!="object"||Array.isArray(e))&&!(!("approved"in e)||typeof e.approved!="boolean"))return e.approved}function CI(e){const t=e;if(t===null||typeof t!="object"||!("resumeState"in t))return;const r=t.resumeState;if(!(r===null||typeof r!="object"||!("threadId"in r)||typeof r.threadId!="string"||r.threadId.length===0||!("runId"in r)||typeof r.runId!="string"||r.runId.length===0))return{threadId:r.threadId,runId:r.runId}}var wI=2e3,NI=new Set(["TEXT_MESSAGE_START","TEXT_MESSAGE_CONTENT","TOOL_CALL_START","MESSAGES_SNAPSHOT"]),jI=64,II=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new yI;currentRunId=null;lastResume=null;runParents=new Map;supersededInterruptRunIds=new Set;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status="ready";connectionStatus="disconnected";abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;connectionDrainsOnSend=!1;errorReportedGeneration=null;streamGeneration=0;continuationGeneration=0;streamContinuationGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;historyPageSize;hasOlderMessages=!1;olderMessagesCursor;knownServerMessageIds=new Set;loadOlderMessagesInFlight=!1;historyGeneration=0;devtoolsMounted=!1;callbacksRef;constructor(e){bI(e.interrupts),this.threadId=e.threadId||"",this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw new Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1,this.historyPageSize=e.history?.pageSize}else if(e.persistence){if(!e.threadId)throw new Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new gI(e.persistence,e.threadId,i=>this.processor.setMessages(i),i=>this.applyPersistedResume(i)),this.historyPageSize=void 0}else this.historyPageSize=void 0;this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=Hc(e.queue);const r=qc(e);if(this.connectionDrainsOnSend=Wc(r),this.connection=Oc(r),this.clientToolsRef={current:new Map},e.tools)for(const i of e.tools)this.clientToolsRef.current.set(i.name,i);this.devtoolsBridge=(e.devtoolsBridgeFactory??mI)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new nI({...e.tools!==void 0?{tools:e.tools}:{},...e.interrupts!==void 0?{interrupts:e.interrupts}:{},submit:i=>this.submitInterruptBatch(i),onChange:i=>this.notifyResumeStateChange(i)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);const s=this.persistor?.readInitial(),n=s instanceof Promise?void 0:s,o=n?n.messages:e.initialMessages;let l=null;if(n?.resume){const i=n.resume;Array.isArray(i.pendingInterrupts)&&i.pendingInterrupts.length>0?this.applyResumeSnapshot(i):i.resumeState.runId&&(l=i.resumeState.runId)}if(!l&&e.initialResumeSnapshot){const i=e.initialResumeSnapshot;!(Array.isArray(i.pendingInterrupts)&&i.pendingInterrupts.length>0)&&i.resumeState.runId&&(l=i.resumeState.runId)}this.processor=new wj({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...o?{initialMessages:o}:{},events:{onMessagesChange:i=>{this.persistor?.notifyMessagesChanged(i),this.callbacksRef.current.onMessagesChange(i)},onStreamStart:()=>{this.setStatus("streaming");const i=this.processor.getCurrentAssistantMessageId();if(!i)return;const c=this.processor.getMessages().find(d=>d.id===i);c&&(this.currentMessageId=c.id,this.events.messageAppended(c,this.currentStreamId||void 0))},onStreamEnd:i=>{this.callbacksRef.current.onFinish(i),this.setStatus("ready"),this.resolveProcessing()},onError:i=>{this.reportStreamError(i)},onTextUpdate:(i,c)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,i,c)},onThinkingUpdate:(i,c)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,i,c,void 0)},onStructuredOutputChange:i=>{const c=this.devtoolsBridge.resolveStreamId(),d=i.phase==="start"?"structured-output:started":i.phase==="complete"?"structured-output:completed":i.phase==="error"?"structured-output:errored":"structured-output:updated";this.currentMessageId=i.messageId,this.events.structuredOutputChanged(d,c,i.messageId,{status:i.status,raw:i.raw,...i.partial!==void 0?{partial:i.partial}:{},...i.data!==void 0?{data:i.data}:{},...i.reasoning!==void 0?{reasoning:i.reasoning}:{},...i.errorMessage!==void 0?{errorMessage:i.errorMessage}:{},...i.delta!==void 0?{delta:i.delta}:{}})},onToolCallStateChange:(i,c,d,u)=>{const h=this.processor.getMessages().find(m=>m.id===i)?.parts.find(m=>m.type==="tool-call"&&m.id===c)?.name||"unknown";this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,i,c,h,d,u)},onToolCall:i=>{const c=(this.activeClientTools??this.clientToolsRef.current).get(i.toolName),d=c?.execute;if(d){const u=this.continuationGeneration,h=this.devtoolsBridge.getCurrentRunEventContext(),m=(async()=>{try{const p=this.activeClientTools===null?this.context:this.activeContext,b=await d(i.input,{toolCallId:i.toolCallId,context:p,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:i.toolCallId,tool:i.toolName,output:b,state:"output-available"},c,u,h)}catch(p){await this.addToolResultForClientTool({toolCallId:i.toolCallId,tool:i.toolName,output:null,state:"output-error",errorText:p.message},c,u,h)}finally{this.pendingToolExecutions.delete(i.toolCallId)}})();this.pendingToolExecutions.set(i.toolCallId,m)}},onApprovalRequest:i=>{const c=this.devtoolsBridge.resolveStreamId(),d=this.findMessageIdForToolCall(i.toolCallId)??this.currentMessageId??"";this.events.approvalRequested(c,d,i.toolCallId,i.toolName,i.input,i.approvalId)},onCustomEvent:(i,c,d)=>{i==="memory:state"&&this.devtoolsBridge.recordMemoryState(c),(i==="compaction:started"||i==="compaction:state"||i==="compaction:ended")&&this.devtoolsBridge.recordCompactionEvent(i,c),i==="skills:state"&&this.devtoolsBridge.recordSkillsState(c),this.callbacksRef.current.onCustomEvent(i,c,d)}}}),this.persistor?.hydrateAsync(s),this.rejoinRunId=l,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){const t=CI(e);if(t===void 0){this.interruptManager.reset({source:"hydrate"});return}this.lastResume=t;const r=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(r.length===0){this.interruptManager.reset({source:"hydrate"});return}const s=this.interruptGeneration(r);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:s,interrupts:r},"hydrate")}applyPersistedResume(e){this.applyResumeSnapshot(e);const t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,r=e.resumeState?.runId;!t&&r&&this.maybeRejoinInFlight(r)}maybeRejoinInFlight(e){this.connection.joinRun&&(this.disposed||!this.tailing||this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e))))}hydrateFromServer(){const e=this.connection.hydrate;if(!e||this.isLoading||this.abortController||this.disposed)return;const t=this.historyPageSize,r=t===void 0?void 0:{limit:t};(async()=>{let s;const n=this.historyGeneration;try{s=await e(this.threadId,r)}catch{return}if(n===this.historyGeneration&&!(this.disposed||!this.tailing)&&!(this.isLoading||this.abortController)){if(this.applyHydrationPage(s.page),s.messages.length>0){const o=Wo(s.messages);this.processor.setMessages(o),this.rememberServerMessageIds(o)}s.interrupts&&s.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:s.interrupts.runId},pendingInterrupts:s.interrupts.pending}):s.activeRun?.runId&&this.maybeRejoinInFlight(s.activeRun.runId)}})()}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||(this.threadId=this.generateUniqueId("thread")),this.uniqueId=this.threadId,this.threadId}drainIgnoredRunlessChunk(e){if(e.type!=="RUN_ERROR")return;const t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const t=_t(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),_t(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type==="RUN_STARTED"){const n=_t(e)??e.runId,o="parentRunId"in e&&typeof e.parentRunId=="string"?e.parentRunId:void 0;o&&(this.runParents.set(n,o),this.supersededInterruptRunIds.has(n)&&this.markLineageAnswered(o)),this.activeResumeThreadId="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=n;const l=this.supersededInterruptRunIds.has(n)&&!this.isLoading;l||(this.activeRunIds.add(n),this.clearedStreamTracker.onRunStarted(n),this.setSessionGenerating(!0)),this.persistor&&this.connection.joinRun&&!this.lastResume&&!l&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:n}),this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId)&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset());return}if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const r=_t(e);r?(this.activeRunIds.delete(r),this.clearedStreamTracker.onRunSettled(r)):e.type==="RUN_ERROR"&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0);const s=e.type==="RUN_FINISHED"&&Kc(e);t?.resolveProcessing!==!1&&!s&&this.resolveProcessing()}observeInterruptState(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR"||this.activeInterruptSubmission&&e.type==="RUN_ERROR")return;const t=_t(e),r="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId;if(t&&!Kc(e)&&(e.type==="RUN_ERROR"||e.type==="RUN_FINISHED"&&e.outcome?.type!=="interrupt")&&this.markLineageAnswered(t),e.type==="RUN_FINISHED"&&e.outcome?.type==="interrupt"){const u=this.currentRunId??t??this.activeResumeRunId??"";if(u&&this.supersededInterruptRunIds.has(u))return;this.lastResume={threadId:r??this.threadId,runId:u},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:u,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},"live");return}const s=e.type==="RUN_ERROR"&&!t,n=!!(t&&this.lastResume?.runId===t),o=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),l=!!(this.isLoading&&t&&(t===this.activeResumeRunId||t===this.currentRunId)),i=this.isLoading&&e.type==="RUN_FINISHED"&&!t,c=!!(this.activeInterruptSubmission&&this.isLoading&&e.type==="RUN_FINISHED"&&e.outcome?.type!=="interrupt"),d=!!(this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId));if(s||n||o||l||i||c||d){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange("live")}markLineageAnswered(e){let t=e,r=0;for(;t!==void 0&&r<jI;){if(this.supersededInterruptRunIds.has(t))return;this.supersededInterruptRunIds.add(t),t=this.runParents.get(t),r++}}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e=="boolean"){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){const r=t??this.lastResume;return r?this.resumeInterruptsUnsafeForGeneration(e,r,this.continuationGeneration):Promise.resolve(!1)}resumeInterruptsUnsafeForGeneration(e,t,r){return r!==this.continuationGeneration?Promise.resolve(!1):this.isLoading?new Promise((s,n)=>{this.queuePostStreamAction(async()=>{try{s(await this.resumeInterruptsUnsafeForGeneration(e,t,r))}catch(o){n(o)}})}):(this.pendingResumeThreadId=t.threadId,this.pendingResumeParentRunId=t.runId,this.pendingResumeItems=[...e],this.streamResponse())}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){const t=this.continuationGeneration;this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(const n of e.resolutions){const o=SI(n.payload);if(o===void 0)continue;const l=n.interruptId;this.processor.addToolApprovalResponse(l,o)}const r=await this.resumeInterruptsUnsafeForGeneration([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId},t).finally(()=>{this.activeInterruptSubmission===e&&(this.activeInterruptSubmission=void 0)});if(t!==this.continuationGeneration)return;const s=this.takeInterruptSubmissionFailure();if(s!==void 0)throw{errors:s.errors};if(!r)throw new Error("Interrupt continuation could not be started.");this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){const e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(const r of e){const s=r.metadata?.["tanstack:interruptBinding"];if(s===null||typeof s!="object"||!("generation"in s)||typeof s.generation!="number"||!Number.isInteger(s.generation)||s.generation<0||t!==void 0&&t!==s.generation)return 0;t=s.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){const t=this.getResumeState(),r=this.interruptManager.getState();this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,r.interrupts),this.callbacksRef.current.onInterruptStateChange(r,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}const t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){const t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.threadId},metadata:{hookName:e?.hookName??"useChat",outputKind:e?.outputKind??"chat",...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:r=>{this.processor.setMessages(r)},addToolResult:(r,s,n)=>{this.processor.addToolResult(r,s,n)},generateId:r=>this.generateUniqueId(r)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){const t=this.processor.getMessages();for(const r of t)if(r.parts.find(s=>s.type==="tool-call"&&s.id===e))return r.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus("ready")}reportStreamError(e){const t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status==="submitted"||this.status==="streaming")&&this.setStatus("error"),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;const e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(t=>{t instanceof Error&&t.name!=="AbortError"&&(this.setConnectionStatus("error"),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(t)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!=="error"&&this.setConnectionStatus("disconnected")))})}async consumeSubscription(e){const t=this.connection.subscribe(e);for await(const r of t){if(e.aborted)break;await this.processIncomingChunk(r)}}resumeInFlightRun(e){const t=this.connection.joinRun;if(!t)return;const r=new AbortController;this.abortController=r,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.streamContinuationGeneration=this.continuationGeneration,this.setIsLoading(!0),this.setStatus("streaming"),(async()=>{let s=!1,n=!1,o=!1;const l=setTimeout(()=>{n||r.abort()},wI);try{for await(const i of t(e,r.signal)){if(r.signal.aborted)break;n||(n=!0,clearTimeout(l)),!s&&NI.has(i.type)&&(s=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(i,{defer:!1})}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(i){const c=i instanceof Error&&(i.name==="AbortError"||i.name==="TimeoutError");!n&&!c&&(o=!0),n&&!c&&this.reportStreamError(i instanceof Error?i:new Error(String(i)))}finally{clearTimeout(l),!n&&o&&this.tailing&&!this.disposed&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null)),this.abortController===r&&(this.abortController=null,this.setIsLoading(!1),this.status==="streaming"&&this.setStatus("ready"),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){const e=this.processor.getMessages(),t=e[e.length-1];t&&t.role==="assistant"&&this.processor.setMessages(e.slice(0,-1))}async processIncomingChunk(e,t){if(e=im(e),e.type==="RUN_ERROR"&&this.isActiveInterruptSubmissionFailure(e)){const r=Ve(e)?.interruptErrors;this.interruptSubmissionFailure={errors:Array.isArray(r)?r:[]}}if(this.connectionStatus==="connecting"&&this.setConnectionStatus("connected"),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR")&&(_t(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e),this.processor.processChunk(e),this.updateRunLifecycle(e),this.observeInterruptState(e),t?.defer!==!1&&(typeof document>"u"||!document.hidden)&&await new Promise(r=>setTimeout(r,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){const t=this.activeInterruptSubmission,r=Ve(e)?.interruptErrors;if(!t||!Array.isArray(r)||r.length===0)return!1;const s=_t(e);return s!==void 0&&s!==this.currentRunId||typeof e.threadId=="string"&&e.threadId!==t.threadId?!1:r.every(n=>n==null||typeof n!="object"||typeof n.threadId!="string"||typeof n.interruptedRunId!="string"||typeof n.generation!="number"?!1:n.threadId===t.threadId&&n.interruptedRunId===t.interruptedRunId&&n.generation===t.generation)}resolveJoinedRun(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const t=_t(e);if(t===void 0)return;const r=this.joinedRunWaiters.get(t);r!==void 0&&(this.joinedRunWaiters.delete(t),r())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,r){if(this.mountDevtools(),typeof e=="string"&&!e.trim())return;if(this.hasPendingInterrupts())throw new Error("ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.");const s={...t,...r?.body};if(this.isSendBusy()){const{action:n,id:o}=this.decideWhenBusy(e,r);if(n==="drop")return;if(n==="queue"){this.enqueueMessage(e,s,o);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,s)}finally{this.sendInFlight=!1}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?"streaming":this.messageQueueDraining?"draining":"sendInFlight"}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{const r=this.normalizeMessageInput(e);this.pendingMessageBody=t;const s=this.processor.addUserMessage(r.content,r.id,r.metadata);return this.events.messageSent(s.id,r.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){const r=this.generateUniqueId("queued");if(t?.whenBusy)return{action:t.whenBusy,id:r};const{strategy:s,whenBusy:n}=this.queueConfig;if(s){const{action:o}=s({pending:{id:r,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:o,id:r}}return{action:n,id:r}}enqueueMessage(e,t,r){const{maxSize:s,onOverflow:n}=this.queueConfig;if(s!==void 0&&this.messageQueue.length>=s){if(n==="reject"||s===0)return;this.messageQueue.shift()}this.messageQueue.push({id:r??this.generateUniqueId("queued"),content:e,createdAt:Date.now(),...t!==void 0?{body:t}:{}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e=="string"?{content:e.trim()}:{content:e.content,id:e.id,...e.metadata!==void 0?{metadata:e.metadata}:{}}}async append(e){if(this.mountDevtools(),this.hasPendingInterrupts())throw new Error("ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.");const t=ZN(e,ts);if(t.role==="system")return;const r=t;this.events.messageAppended(r);const s=this.processor.getMessages();if(this.processor.setMessages([...s,r]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;const e=++this.streamGeneration;this.streamContinuationGeneration=this.continuationGeneration;const t=this.pendingResumeThreadId,r=this.pendingResumeParentRunId,s=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;const n=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(n),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=n,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus("submitted"),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;const o=this.abortController.signal;this.pendingToolExecutions.clear();let l=!1,i=null,c=!1;try{const d=this.messagesForSend(this.processor.getMessages()),u=new Map(this.clientToolsRef.current),h=this.context;if(await this.callbacksRef.current.onResponse(),o.aborted)return!1;const m={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId("stream"),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=u,this.activeContext=h,this.processor.prepareAssistantMessage(),this.ensureSubscription();const p=this.waitForProcessing();let b;if(this.byok){const x=aI(this.byokProvider,m.provider,oN(this.byok));b=await oI(this.byok,x)}const w={threadId:t??this.threadId,runId:n,...r!==null?{parentRunId:r}:{},clientTools:Array.from(u.values()).map(x=>({name:x.name,description:x.description,parameters:x.inputSchema?Ho(x.inputSchema):{type:"object"}})),forwardedProps:{...m},...s?{resume:s}:{},...b?{headers:b}:{}};if(this.devtoolsBridge.beginRun(w.runId,w.threadId),i=w.runId,this.devtoolsBridge.emitRunLifecycle("run:created",w.runId,"created"),this.devtoolsBridge.emitRunLifecycle("run:started",w.runId,"started"),this.devtoolsBridge.emitSnapshot(),await this.connection.send(d,m,o,w),e!==this.streamGeneration||o.aborted||(this.connectionDrainsOnSend&&this.resolveProcessing(),await p,e!==this.streamGeneration))return!1;if(this.status==="error")return i&&(this.devtoolsBridge.emitRunLifecycle("run:errored",i,"errored",this.error?{error:this.error.message}:{}),c=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),l=!0}catch(d){const u=d instanceof Error?d:new Error(String(d));if(u.name==="AbortError")return i&&(this.devtoolsBridge.emitRunLifecycle("run:cancelled",i,"cancelled"),c=!0),!1;if(u instanceof Uo&&this.byok?.request(u.provider,"missing"),u instanceof Hn&&u.reason==="locked"&&this.byok?.request(u.provider,"locked"),e===this.streamGeneration&&(this.reportStreamError(u),i&&(this.devtoolsBridge.emitRunLifecycle("run:errored",i,"errored",{error:u.message}),c=!0)),e===this.streamGeneration&&(u instanceof Uo||u instanceof Hn||u instanceof Uh))throw u}finally{e===this.streamGeneration&&(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.setCurrentRunId(null),this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,i&&!c&&(l?this.devtoolsBridge.emitRunLifecycle("run:completed",i,"completed"):o.aborted&&this.devtoolsBridge.emitRunLifecycle("run:cancelled",i,"cancelled")),await this.drainPostStreamActions(),l?(this.rememberProcessorMessageIds(),this.status!=="ready"&&this.setStatus("ready"),this.messageQueueDraining||await this.drainQueue()):this.flushQueue())}return l}subscribe(e){const t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus("connecting"),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected")}async reload(){const e=this.processor.getMessages();if(e.length===0)return;const t=e.findLastIndex(r=>r.role==="user");t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){this.continuationGeneration++;const e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),this.lastResume=null,this.activeInterruptSubmission=void 0,this.interruptManager.reset(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){const e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.resetHistoryPaging(),this.discardPendingSends(),this.persistor?.remove(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){const t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t,this.streamContinuationGeneration)}async addToolResultForClientTool(e,t,r,s){if(t&&e.state!=="output-error")try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(n){e={...e,output:null,state:"output-error",errorText:n.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||"output-available",s),r===this.continuationGeneration&&(this.processor.addToolResult(e.toolCallId,e.output,e.state==="output-error"?e.errorText||"Tool execution failed":void 0),this.devtoolsBridge.emitSnapshot(),!this.interruptManager.resolveClientToolOutput(e.toolCallId,e.state==="output-error"?{error:e.errorText||"Tool execution failed"}:e.output))){if(this.isLoading){this.queuePostStreamAction(()=>r===this.continuationGeneration?this.checkForContinuation():Promise.resolve());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&Lr(e.outputSchema)?wN(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;const t=this.processor.getMessages();let r;for(const s of t){const n=s.parts.find(o=>o.type==="tool-call"&&o.approval?.id===e.id);if(n){r=n.id;break}}if(r&&this.events.toolApprovalResponded(e.id,r,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){const t=this.continuationGeneration;this.postStreamActions.push(async()=>{t===this.continuationGeneration&&await e()})}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(this.streamContinuationGeneration===this.continuationGeneration&&!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;const e=this.processor.getMessages().findLast(t=>t.role==="assistant");return!e||!e.parts.some(t=>t.type==="tool-call")?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}getHasOlderMessages(){return this.hasOlderMessages}async loadOlderMessages(){const e=this.connection.hydrate;if(e===void 0||this.disposed||!this.hasOlderMessages)return;const t=this.olderMessagesCursor;if(t===void 0||this.loadOlderMessagesInFlight)return;const r={before:t};this.historyPageSize!==void 0&&(r.limit=this.historyPageSize),this.loadOlderMessagesInFlight=!0;const s=this.historyGeneration;try{const n=await e(this.threadId,r);if(this.disposed||s!==this.historyGeneration)return;const o=Wo(n.messages);if(o.length===0)throw new Error("Older page was empty");this.applyHydrationPage(n.page),this.processor.prependMessages(o),this.rememberServerMessageIds(o)}finally{this.loadOlderMessagesInFlight=!1}}resetHistoryPaging(){this.hasOlderMessages=!1,this.olderMessagesCursor=void 0,this.knownServerMessageIds.clear(),this.historyGeneration++}applyHydrationPage(e){if(e?.truncated===!0){this.hasOlderMessages=!0,this.olderMessagesCursor=e.cursor;return}this.hasOlderMessages=!1,this.olderMessagesCursor=void 0}rememberServerMessageIds(e){const t=e.map(r=>r.id);for(const r of t)this.knownServerMessageIds.add(r)}rememberProcessorMessageIds(){this.historyPageSize!==void 0&&this.rememberServerMessageIds(this.processor.getMessages())}messagesForSend(e){if(this.historyPageSize===void 0)return e;const t=[];for(const s of e)this.knownServerMessageIds.has(s.id)||t.push(s);if(t.length>0)return t;const r=e.findLastIndex(s=>s.role==="user");return r===-1?[]:e.slice(r)}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain==="batch"){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;const e=this.messageQueue.splice(0);this.emitQueueChange();const t=xI(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;const e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:r})=>({id:e,content:t,createdAt:r}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){const t=this.messageQueue.findIndex(r=>r.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){const t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected");const r=qc({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=Wc(r),this.connection=Oc(r),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),e.byok!==void 0&&(this.byok=e.byok),e.byokProvider!==void 0&&(this.byokProvider=e.byokProvider),"context"in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=new Map;for(const t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=Hc(e.queue)),e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onQueueChange!==void 0&&(this.callbacksRef.current.onQueueChange=e.onQueueChange),e.onResumeStateChange!==void 0&&(this.callbacksRef.current.onResumeStateChange=e.onResumeStateChange),e.onRunIdChange!==void 0&&(this.callbacksRef.current.onRunIdChange=e.onRunIdChange),e.onInterruptStateChange!==void 0&&(this.callbacksRef.current.onInterruptStateChange=e.onInterruptStateChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.disposed=!0,this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}};function Gc(e){return!e||typeof e!="object"?{}:{..."before"in e&&typeof e.before=="number"?{before:e.before}:{},..."after"in e&&typeof e.after=="number"?{after:e.after}:{},..."messagesBefore"in e&&typeof e.messagesBefore=="number"?{messagesBefore:e.messagesBefore}:{},..."messagesAfter"in e&&typeof e.messagesAfter=="number"?{messagesAfter:e.messagesAfter}:{},..."reusedCheckpoint"in e&&typeof e.reusedCheckpoint=="boolean"?{reusedCheckpoint:e.reusedCheckpoint}:{},..."maxTokens"in e&&typeof e.maxTokens=="number"?{maxTokens:e.maxTokens}:{},..."strategyKey"in e&&typeof e.strategyKey=="string"?{strategyKey:e.strategyKey}:{},..."durationMs"in e&&typeof e.durationMs=="number"?{durationMs:e.durationMs}:{}}}function Yc(e){if(!Array.isArray(e))return;const t=[];for(const r of e)!r||typeof r!="object"||!("role"in r)||!("tokens"in r)||!("text"in r)||typeof r.role!="string"||typeof r.tokens!="number"||typeof r.text!="string"||t.push({role:r.role,tokens:r.tokens,text:r.text});return t}function TI(e){if(!e||typeof e!="object"||!("before"in e)||!("after"in e)||!("messagesBefore"in e)||!("messagesAfter"in e)||typeof e.before!="number"||typeof e.after!="number"||typeof e.messagesBefore!="number"||typeof e.messagesAfter!="number")return null;const t="reusedCheckpoint"in e&&e.reusedCheckpoint===!0,r="maxTokens"in e&&typeof e.maxTokens=="number"?e.maxTokens:void 0,s="strategyKey"in e&&typeof e.strategyKey=="string"?e.strategyKey:void 0,n="dropped"in e?Yc(e.dropped):void 0,o="result"in e?Yc(e.result):void 0;return{before:e.before,after:e.after,messagesBefore:e.messagesBefore,messagesAfter:e.messagesAfter,reusedCheckpoint:t,...r!==void 0?{maxTokens:r}:{},...s?{strategyKey:s}:{},...n?{dropped:n}:{},...o?{result:o}:{}}}var Jc=Symbol.for("tanstack.ai.devtools.activeBridgeByHookId");function po(){const e=globalThis,t=e[Jc];if(t)return t;const r=new Map;return e[Jc]=r,r}function RI(e,t){return{get hookId(){return e.hookId},get clientId(){return e.clientId},get threadId(){return e.threadId},metadata:e.metadata,getSnapshot:t.getSnapshot,...t.getTools||e.getTools?{getTools:t.getTools??e.getTools}:{},...t.applyToolFixture||e.applyToolFixture?{applyToolFixture:t.applyToolFixture??e.applyToolFixture}:{}}}var EI=class{options;unsubscribers=[];disposed=!1;superseded=!1;registered=!1;constructor(e){this.options=e}emitRegistered(){this.prepareForMountEmit()&&(this.registered=!0,Et("hook:registered",{...this.createEnvelope("hook:registered"),...this.createMetadataPayload(),lifecycle:"mounted"}))}emitUpdated(){this.prepareForEmit()&&Et("hook:updated",{...this.createEnvelope("hook:updated"),...this.createMetadataPayload(),lifecycle:"active"})}emitSnapshot(){this.prepareForEmit()&&Et("hook:state-snapshot",{...this.createEnvelope("hook:state-snapshot"),...this.createMetadataPayload(),state:this.options.getSnapshot()})}emitToolsRegistered(){if(!this.prepareForEmit())return;const e=this.options.getTools?Array.from(this.options.getTools()).map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema?Ho(t.inputSchema):{type:"object"},outputSchema:t.outputSchema?Ho(t.outputSchema):void 0,needsApproval:t.needsApproval,metadata:t.metadata})):[];Et("tools:registered",{...this.createEnvelope("tools:registered"),...this.createMetadataPayload(),tools:e})}emitRunLifecycle(e,t,r,s={}){this.prepareForEmit()&&Et(e,{...this.createEnvelope(e,"client-state",{runId:t}),runId:t,status:r,...s.error?{error:s.error}:{}})}deactivate(){const e=po();e.get(this.options.hookId)===this&&e.delete(this.options.hookId);for(const t of this.unsubscribers.splice(0))t()}supersede(){this.disposed||(this.superseded=!0,this.disposed=!0,this.deactivate())}dispose(){if(this.disposed)return;if(this.disposed=!0,!this.registered){this.deactivate();return}if(po().get(this.options.hookId)!==this){this.deactivate();return}const e={...this.createEnvelope("hook:unregistered"),...this.createMetadataPayload(),reason:"disposed"};Et("hook:unregistered",e),this.deactivate()}prepareForEmit(){return this.disposed||this.superseded?!1:(this.activate(),!0)}prepareForMountEmit(){return this.superseded?!1:(this.disposed&&(this.disposed=!1,this.registered=!1),this.activate(),!0)}activate(){if(this.disposed)return;const e=po(),t=e.get(this.options.hookId);t&&t!==this&&(typeof t.supersede=="function"?t.supersede():t.deactivate()),e.set(this.options.hookId,this),!(this.unsubscribers.length>0)&&(this.unsubscribers.push(cn.on("devtools:request-state",r=>{this.handleRequestState(r)})),this.options.applyToolFixture&&this.unsubscribers.push(cn.on("devtools:tool-fixture:apply",r=>{this.handleToolFixtureApply(r)})))}handleRequestState(e){if(this.disposed||this.superseded)return;const t=e.payload.targetHookId;t&&t!==this.options.hookId||(this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot(),this.onReplayState())}onReplayState(){}async handleToolFixtureApply(e){const t=e.payload;this.matchesFixtureTarget(t)&&await this.options.applyToolFixture?.(t)}matchesFixtureTarget(e){return!e.hookId&&!e.threadId?!1:e.hookId?e.hookId===this.options.hookId:!(e.threadId&&(!this.options.threadId||e.threadId!==this.options.threadId))}createEnvelope(e,t="client-state",r={}){return ei({eventType:e,source:"client",visibility:t,clientId:this.options.clientId,hookId:this.options.hookId,...this.options.threadId?{threadId:this.options.threadId}:{},...r.runId?{runId:r.runId}:{},timestamp:Date.now()})}createMetadataPayload(){return{hookId:this.options.hookId,hookName:this.options.metadata.hookName,...this.options.metadata.name?{displayName:this.options.metadata.name}:{},...this.options.metadata.outputKind?{outputKind:this.options.metadata.outputKind}:{},...this.options.metadata.framework?{framework:this.options.metadata.framework}:{}}}},kI=class extends EI{events;chatOptions;currentRunId=null;currentRunThreadId=null;currentStreamId=null;lastStreamId=null;lastRunEventContext;lastMemoryStateValue=null;lastCompactionEvents=[];lastSkillsStateValue=null;constructor(e){super(RI(e,{getSnapshot:e.getSnapshot,applyToolFixture:t=>this.applyFixture(t)})),this.chatOptions=e,this.events=new PI(()=>e.clientId,this)}setCurrentStreamId(e){this.currentStreamId=e,e&&(this.lastStreamId=e)}recordStreamId(e){e&&(this.lastStreamId=e)}mountWithTools(e){this.events.clientCreated(e),this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot()}notifyToolsChanged(){this.emitToolsRegistered(),this.emitSnapshot()}getCurrentStreamId(){return this.currentStreamId}getLastStreamId(){return this.lastStreamId}resolveStreamId(){return this.currentStreamId??this.lastStreamId??this.chatOptions.generateId("stream")}beginRun(e,t){this.currentRunId=e,this.currentRunThreadId=t,this.lastRunEventContext={runId:e,threadId:t}}observeChunk(e){if(e.type==="RUN_STARTED"){this.beginRun(e.runId,e.threadId);return}if(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR"){const t=(e.type==="RUN_FINISHED",e.runId);if(!t||t===this.currentRunId){const r=this.getCurrentRunEventContext();r&&(this.lastRunEventContext=r),this.currentRunId=null,this.currentRunThreadId=null}}}recordMemoryState(e){this.lastMemoryStateValue=e,this.emitMemoryState(e)}recordSkillsState(e){this.lastSkillsStateValue=e,this.emitSkillsState(e)}emitMemoryState(e){if(!e||typeof e!="object")return;const t=e,r=t.scope,s=t.adapter;if(!r||typeof s!="string")return;const n=this.currentRunId?{runId:this.currentRunId}:{};Et("memory:retrieve:started",{...this.createEnvelope("memory:retrieve:started","client-state",n),scope:r,adapter:s,query:t.query??""}),t.recall&&Et("memory:retrieve:completed",{...this.createEnvelope("memory:retrieve:completed","client-state",n),scope:r,adapter:s,fragmentCount:t.recall.fragmentCount??0,hasTools:!!t.recall.hasTools,systemPromptChars:t.recall.systemPromptChars??0,durationMs:t.recall.durationMs??0}),t.snapshot&&Et("memory:snapshot",{...this.createEnvelope("memory:snapshot","client-state",n),scope:r,adapter:s,takenAt:t.snapshot.takenAt,data:t.snapshot.data,facts:t.snapshot.facts??[]})}recordCompactionEvent(e,t){this.lastCompactionEvents.push({eventType:e,value:t}),this.lastCompactionEvents.length>60&&this.lastCompactionEvents.splice(0,this.lastCompactionEvents.length-60),this.emitCompactionEvent(e,t)}recordCompactionState(e){this.recordCompactionEvent("compaction:state",e)}emitCompactionEvent(e,t){const r=this.currentRunId?{runId:this.currentRunId}:{};if(e==="compaction:started"){const s=Gc(t);Et("compaction:started",{...this.createEnvelope("compaction:started","client-state",r),...s});return}if(e==="compaction:ended"){const s=Gc(t);Et("compaction:ended",{...this.createEnvelope("compaction:ended","client-state",r),...s});return}if(e==="compaction:state"){const s=TI(t);if(!s)return;Et("compaction:state",{...this.createEnvelope("compaction:state","client-state",r),...s})}}emitSkillsState(e){if(!e||typeof e!="object")return;const t=e,r=Array.isArray(t.catalog)?t.catalog:[],s=Array.isArray(t.activated)?t.activated:[],n=this.currentRunId?{runId:this.currentRunId}:{};Et("skills:snapshot",{...this.createEnvelope("skills:snapshot","client-state",n),catalog:r,activated:s})}onReplayState(){this.lastMemoryStateValue!=null&&this.emitMemoryState(this.lastMemoryStateValue);for(const e of this.lastCompactionEvents)this.emitCompactionEvent(e.eventType,e.value);this.lastSkillsStateValue!=null&&this.emitSkillsState(this.lastSkillsStateValue)}getCurrentRunEventContext(){if(this.currentRunId)return{threadId:this.currentRunThreadId??this.chatOptions.threadId??"",runId:this.currentRunId}}getCurrentOrLastRunEventContext(){return this.getCurrentRunEventContext()??this.lastRunEventContext}findToolCallContext(e){const t={toolCallId:e},r=this.getCurrentRunEventContext();return r?{threadId:r.threadId,runId:r.runId,toolCallId:e}:this.chatOptions.threadId?{threadId:this.chatOptions.threadId,toolCallId:e}:t}async applyFixture(e){const t=this.chatOptions.getMessages(),r=e.threadId??this.chatOptions.threadId??"";if(e.execute){await this.executeFixture(e,t,r);return}const{message:s,toolCallId:n}=this.createReplayMessageFromFixture(e,t),o=s.id;this.events.messageAppended(s,void 0,{threadId:r,toolCallId:n,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,s]),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:r,...e.runId?{runId:e.runId}:{},toolName:e.toolName,input:e.input,output:e.output,messageId:o,toolCallId:n,...e.execute!==void 0?{execute:e.execute}:{},...e.message?{message:e.message}:{},...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}async executeFixture(e,t,r){const s=this.resolveFixtureToolCallId(e.toolCallId,t),n=this.resolveFixtureMessageId(e.messageId,t),o={id:n,role:"assistant",parts:[{type:"tool-call",id:s,name:e.toolName,arguments:go(e.input),input:e.input,state:"input-complete"}],createdAt:new Date};this.events.messageAppended(o,void 0,{threadId:r,toolCallId:s,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,o]),this.emitSnapshot();const l=this.findClientTool(e.toolName)?.execute;if(!l){console.warn(`[ai-devtools] tool fixture "${e.toolName}" requested execute=true but no client tool implementation is registered; replaying saved output instead.`),this.addToolResultForFixture({fixture:e,messageId:n,toolCallId:s,threadId:r,output:e.output,errorText:e.errorText});return}let i;try{i=await l(e.input)}catch(c){console.error(`[ai-devtools] tool fixture "${e.toolName}" execute threw`,c),this.addToolResultForFixture({fixture:e,messageId:n,toolCallId:s,threadId:r,output:null,errorText:c instanceof Error?`${c.name}: ${c.message}`:`Tool execution failed: ${String(c)}`});return}this.addToolResultForFixture({fixture:e,messageId:n,toolCallId:s,threadId:r,output:i})}addToolResultForFixture(e){const t=e.errorText?"output-error":"output-available";this.events.toolResultAdded(e.toolCallId,e.fixture.toolName,e.output,t,{threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolCallId:e.toolCallId}),this.chatOptions.addToolResult(e.toolCallId,e.output,e.errorText),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolName:e.fixture.toolName,input:e.fixture.input,output:e.output,execute:!0,messageId:e.messageId,toolCallId:e.toolCallId,...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}createReplayMessageFromFixture(e,t){const r=this.cloneFixtureSourceMessage(e,t);if(r)return r;const s=this.resolveFixtureToolCallId(e.toolCallId,t),n=this.resolveFixtureMessageId(e.messageId,t),o=e.errorText?"error":"complete";return{toolCallId:s,message:{id:n,role:"assistant",parts:[{type:"tool-call",id:s,name:e.toolName,arguments:go(e.input),input:e.input,state:"input-complete",output:e.output},{type:"tool-result",toolCallId:s,content:go(e.output),state:o,...e.errorText?{error:e.errorText}:{}}],createdAt:new Date}}}cloneFixtureSourceMessage(e,t){const r=e.message;if(!r||!Array.isArray(r.parts))return;const s=this.createFixtureToolCallIdMap(r.parts,t),n=r.parts.map(i=>OI(i,s)).filter(i=>!!i),o=e.toolCallId?s.get(e.toolCallId):void 0;if(MI(n,{...o?{mappedToolCallId:o}:{},output:e.output}),n.length===0)return;const l=(e.toolCallId?s.get(e.toolCallId):void 0)??DI(n);if(l)return{toolCallId:l,message:{id:this.resolveFixtureMessageId(r.id,t),role:r.role,parts:n,createdAt:new Date}}}createFixtureToolCallIdMap(e,t){const r=new Map;for(const s of e)!vm(s)||s.type!=="tool-call"||typeof s.id=="string"&&r.set(s.id,this.resolveFixtureToolCallId(s.id,t));return r}resolveFixtureMessageId(e,t){return e&&!t.some(r=>r.id===e)?e:this.chatOptions.generateId("fixture-msg")}resolveFixtureToolCallId(e,t){return e&&!_I(t,e)?e:this.chatOptions.generateId("fixture-tool-call")}findClientTool(e){const t=this.chatOptions.getTools?.();if(t){for(const r of t)if(r.name===e)return r}}};function vm(e){return typeof e=="object"&&e!==null}function go(e){if(typeof e=="string")return e;if(e===void 0||typeof e=="function"||typeof e=="symbol")return String(e);try{return JSON.stringify(e)}catch(t){return console.error("[ai-devtools] failed to JSON.stringify fixture value; falling back to String(). Tool call arguments may be malformed.",{error:t,value:e}),String(e)}}function AI(e){try{return JSON.parse(e)}catch(t){return console.error("[ai-devtools] failed to JSON.parse fixture result content; replaying as raw string. Fixture payload may be corrupted.",{error:t,content:e}),e}}function OI(e,t){if(!vm(e)||typeof e.type!="string")return;const r={...e};return e.type==="tool-call"&&typeof e.id=="string"&&(r.id=t.get(e.id)??e.id),e.type==="tool-result"&&typeof e.toolCallId=="string"&&(r.toolCallId=t.get(e.toolCallId)??e.toolCallId),r}function DI(e){const t=e.find(r=>r.type==="tool-call");return t?.type==="tool-call"?t.id:void 0}function MI(e,t){for(const r of e){if(r.type!=="tool-result")continue;const s=e.find(n=>n.type==="tool-call"&&n.id===r.toolCallId&&n.output===void 0);s&&(s.output=Array.isArray(r.content)?r.content:AI(r.content))}if(t.mappedToolCallId&&t.output!==void 0){const r=e.find(s=>s.type==="tool-call"&&s.id===t.mappedToolCallId&&s.output===void 0);r&&(r.output=t.output)}}function _I(e,t){return e.some(r=>r.parts.some(s=>s.type==="tool-call"?s.id===t:s.type==="tool-result"?s.toolCallId===t:!1))}var PI=class extends uI{getClientId;helper;constructor(e,t){super(e()),this.getClientId=e,this.helper=t}emitEvent(e,t){this.clientId=this.getClientId(),super.emitEvent(e,t)}afterEmit(e){e&&this.helper.recordStreamId(e),this.helper.emitSnapshot()}textUpdated(e,t,r,s){super.textUpdated(e,t,r,s??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}thinkingUpdated(e,t,r,s,n){super.thinkingUpdated(e,t,r,s,n??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}messageAppended(e,t,r){super.messageAppended(e,t,r??this.helper.getCurrentRunEventContext()),this.afterEmit(t)}toolCallStateChanged(e,t,r,s,n,o,l){super.toolCallStateChanged(e,t,r,s,n,o,l??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}structuredOutputChanged(e,t,r,s,n){super.structuredOutputChanged(e,t,r,s,n??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(t)}approvalRequested(e,t,r,s,n,o,l){super.approvalRequested(e,t,r,s,n,o,l??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(e)}toolResultAdded(e,t,r,s,n){super.toolResultAdded(e,t,r,s,n??this.helper.getCurrentRunEventContext()),this.afterEmit()}toolApprovalResponded(e,t,r,s){super.toolApprovalResponded(e,t,r,s??this.helper.getCurrentRunEventContext()),this.afterEmit()}clientCreated(e){super.clientCreated(e),this.afterEmit()}loadingChanged(e){super.loadingChanged(e),this.afterEmit()}errorChanged(e){super.errorChanged(e),this.afterEmit()}reloaded(e){super.reloaded(e),this.afterEmit()}stopped(){super.stopped(),this.afterEmit()}messagesCleared(){super.messagesCleared(),this.afterEmit()}messageSent(e,t){super.messageSent(e,t),this.afterEmit()}toolFixtureApplied(e){super.toolFixtureApplied(e),this.afterEmit()}};function FI(e){return new kI(e)}var Qc=Object.freeze([]),LI=Object.freeze([]);function wR(e){const t=(0,f.useId)(),r=e.threadId??t,[s,n]=(0,f.useState)(e.initialMessages||[]),[o,l]=(0,f.useState)(!1),[i,c]=(0,f.useState)(void 0),[d,u]=(0,f.useState)("ready"),[h,m]=(0,f.useState)(!1),[p,b]=(0,f.useState)("disconnected"),[w,x]=(0,f.useState)(!1),[N,C]=(0,f.useState)([]),[S,g]=(0,f.useState)(null),[v,y]=(0,f.useState)(()=>({interrupts:Qc,pendingInterrupts:Qc,interruptErrors:LI,resuming:!1})),R=(0,f.useRef)(e.initialMessages||[]),I=(0,f.useRef)(!0),k=(0,f.useRef)(!1),T=(0,f.useRef)(null),D=(0,f.useRef)(null),_=(0,f.useRef)(null);R.current=s;const O=(0,f.useRef)(e);O.current=e;const F=(0,f.useCallback)(he=>{he&&(g(he.getCurrentRunId()),y(he.getInterruptState()))},[]),{client:E,initialization:z}=(0,f.useMemo)(()=>{const he=e.initialMessages||[];I.current=!1;const ie=O.current,gt=ie.connection?{connection:ie.connection}:{fetcher:ie.fetcher},Nt={current:void 0},nt=()=>{const de=Nt.current;if(!(!de||T.current!==de))return de},er={ready:!1,callbacks:[]},Ue=de=>{if(!er.ready){er.callbacks.push(de);return}const j=Nt.current;!j||T.current!==j||de()},Kt=new II({devtoolsBridgeFactory:FI,...gt,initialMessages:he,...typeof ie.threadId=="string"&&ie.persistence?{persistence:ie.persistence,threadId:ie.threadId}:{...ie.threadId!==void 0&&{threadId:ie.threadId}},...ie.body!==void 0&&{body:ie.body},...ie.forwardedProps!==void 0&&{forwardedProps:ie.forwardedProps},...ie.byok!==void 0&&{byok:ie.byok},byokProvider:()=>O.current.byokProvider?.(),...ie.initialResumeSnapshot!==void 0&&{initialResumeSnapshot:ie.initialResumeSnapshot},...ie.context!==void 0&&{context:ie.context},devtools:{...ie.devtools,framework:"react",hookName:"useChat",outputKind:ie.outputSchema?"structured":"chat"},onResponse:de=>{if(nt())return O.current.onResponse?.(de)},onChunk:de=>{Ue(()=>{O.current.onChunk?.(de)})},onFinish:de=>{Ue(()=>{O.current.onFinish?.(de)})},onError:de=>{Ue(()=>{O.current.onError?.(de)})},...ie.tools!==void 0&&{tools:ie.tools},...ie.interrupts!==void 0&&{interrupts:ie.interrupts},onCustomEvent:(de,j,A)=>{Ue(()=>{O.current.onCustomEvent?.(de,j,A)})},...e.streamProcessor!==void 0&&{streamProcessor:e.streamProcessor},onMessagesChange:de=>{Ue(()=>{n(de)})},onLoadingChange:de=>{Ue(()=>{const j=nt();j&&(l(de),F(j))})},onErrorChange:de=>{Ue(()=>{c(de)})},onStatusChange:de=>{Ue(()=>{u(de)})},onSubscriptionChange:de=>{Ue(()=>{m(de)})},onConnectionStatusChange:de=>{Ue(()=>{b(de)})},onSessionGeneratingChange:de=>{Ue(()=>{x(de)})},...O.current.queue!==void 0&&{queue:O.current.queue},onQueueChange:de=>{Ue(()=>{C(de)})},onRunIdChange:de=>{Ue(()=>{g(de)})},onResumeStateChange:(de,j)=>{Ue(()=>{y(A=>({...A,interrupts:j,pendingInterrupts:j}))})},onInterruptStateChange:(de,j)=>{Ue(()=>{y(de),O.current.onInterruptStateChange?.(de,j)})}});return Nt.current=Kt,{client:Kt,initialization:er}},[r,F]);(0,f.useEffect)(()=>{T.current=E;try{for(;z.callbacks.length>0;){if(T.current!==E){z.callbacks.length=0;break}z.callbacks.shift()?.()}}finally{z.ready=!0}},[E,z]),(0,f.useEffect)(()=>{const he=E.getMessages();he!==R.current&&n(he)},[E]),(0,f.useEffect)(()=>{E.updateOptions({body:e.body})},[E,e.body]),(0,f.useEffect)(()=>{e.forwardedProps!==void 0&&E.updateOptions({forwardedProps:e.forwardedProps})},[E,e.forwardedProps]),(0,f.useEffect)(()=>{e.tools!==void 0&&E.updateOptions({tools:e.tools})},[E,e.tools]),(0,f.useEffect)(()=>{E.updateOptions({context:e.context})},[E,e.context]),(0,f.useEffect)(()=>{e.queue!==void 0&&E.updateOptions({queue:e.queue})},[E,e.queue]),(0,f.useEffect)(()=>{e.live?(E.subscribe(),k.current=!0):k.current&&(E.unsubscribe(),k.current=!1)},[E,e.live]),(0,f.useEffect)(()=>(E.attach(),()=>{E.detach()}),[E]),(0,f.useEffect)(()=>(_.current?.client===E&&(clearTimeout(_.current.timeout),_.current=null),D.current&&(clearTimeout(D.current),D.current=null),E.mountDevtools(),F(E),()=>{D.current=setTimeout(()=>{T.current===E&&(T.current=null),D.current=null},0);const he={client:E,timeout:setTimeout(()=>{O.current.live?E.unsubscribe():E.stop(),E.dispose(),_.current===he&&(_.current=null)},0)};_.current=he}),[E,F]);const G=(0,f.useCallback)(async(he,ie)=>{try{await E.sendMessage(he,void 0,ie)}finally{F(E)}},[E,F]),fe=(0,f.useCallback)(he=>{E.cancelQueued(he)},[E,F]),Z=(0,f.useCallback)(async he=>{try{await E.append(he)}finally{F(E)}},[E,F]),re=(0,f.useCallback)(async()=>{try{await E.reload()}finally{F(E)}},[E,F]),Ne=(0,f.useCallback)(()=>{E.stop()},[E]),L=(0,f.useCallback)(()=>{E.clear(),F(E)},[E,F]),$=(0,f.useCallback)(he=>{E.setMessagesManually(he)},[E]),ne=(0,f.useCallback)(async he=>{await E.addToolResult(he)},[E]),ee=(0,f.useCallback)(async he=>{await E.addToolApprovalResponse(he),F(E)},[E,F]),pe=(0,f.useCallback)(async(he,ie)=>{const gt=await E.resumeInterrupts(he,ie??void 0);return F(E),gt},[E,F]),K=(0,f.useCallback)(he=>{E.resolveInterrupts(he)},[E]),Ie=(0,f.useCallback)(()=>{E.cancelInterrupts()},[E]),Pe=(0,f.useCallback)(()=>{E.retryInterrupts()},[E]),pt=(0,f.useCallback)((he,ie)=>E.resumeInterruptsUnsafe(he,ie),[E]),Ye=E.getMessages(),st=(0,f.useMemo)(()=>{let he=-1;for(let ie=Ye.length-1;ie>=0;ie--)if(Ye[ie]?.role==="user"){he=ie;break}if(he===-1)return null;for(let ie=Ye.length-1;ie>he;ie--){const gt=Ye[ie];if(gt?.role!=="assistant")continue;const Nt=gt.parts.find(nt=>nt.type==="structured-output");if(Nt)return Nt}return null},[Ye]),Zt=(0,f.useMemo)(()=>st?st.partial??st.data??{}:{},[st]),oe=(0,f.useMemo)(()=>!st||st.status!=="complete"?null:st.data,[st]);return{messages:Ye,sendMessage:G,append:Z,reload:re,stop:Ne,isLoading:o,error:i,status:d,isSubscribed:h,connectionStatus:p,sessionGenerating:w,setMessages:$,clear:L,addToolResult:ne,addToolApprovalResponse:ee,queue:N,cancelQueued:fe,runId:S,interrupts:v.interrupts,pendingInterrupts:v.pendingInterrupts,interruptErrors:v.interruptErrors,resuming:v.resuming,resolveInterrupts:K,cancelInterrupts:Ie,retryInterrupts:Pe,resumeInterruptsUnsafe:pt,resumeInterrupts:pe,partial:Zt,final:oe}}function zI(e){return(0,f.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>aN)}var NR=new Uint8Array(128).fill(128),$I=Dr()(Cd(e=>({provider:"gemini",model:ml("gemini"),includeSchemaInAiContext:!0,setProvider:t=>e({provider:t,model:ml(t)}),setModel:t=>e({model:t}),setIncludeSchemaInAiContext:t=>e({includeSchemaInAiContext:t})}),{name:"db-studio-ai-settings"})),VI=()=>{const[e,t]=(0,f.useState)(""),r=zI(nn),s=$I(),n=yl.find(u=>u.id===s.provider),o=r.status[s.provider],l=o&&"masked"in o?o.masked:null,i=s.provider==="gemini",c=async()=>{const u=e.trim();u&&(await we.promise(nn.update(s.provider,u),{loading:`Saving ${n?.label} key...`,success:`${n?.label} key ready for this tab`,error:h=>h.message||`Could not save ${n?.label} key`}),t(""))},d=async()=>{await we.promise(nn.clear(s.provider),{loading:`Removing ${n?.label} key...`,success:i?"Using the hosted Gemini key":"API key removed",error:u=>u.message||`Could not remove ${n?.label} key`})};return(0,a.jsxs)("section",{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"space-y-2 rounded-lg border p-3",children:[(0,a.jsx)(me,{htmlFor:"ai-provider",children:"Provider"}),(0,a.jsxs)(dt,{value:s.provider,onValueChange:u=>{t(""),s.setProvider(u)},children:[(0,a.jsx)(lt,{id:"ai-provider",children:(0,a.jsx)(it,{})}),(0,a.jsx)(ct,{children:yl.map(u=>(0,a.jsx)(ue,{value:u.id,children:u.label},u.id))})]}),(0,a.jsx)(me,{htmlFor:"ai-model",children:"Model"}),(0,a.jsxs)(dt,{value:s.model,onValueChange:s.setModel,children:[(0,a.jsx)(lt,{id:"ai-model",children:(0,a.jsx)(it,{})}),(0,a.jsx)(ct,{children:n?.models.map(u=>(0,a.jsx)(ue,{value:u.id,children:u.label},u.id))})]})]}),(0,a.jsxs)("div",{className:"space-y-2 rounded-lg border p-3",children:[(0,a.jsxs)(me,{htmlFor:"ai-api-key",children:[n?.label," API key"]}),(0,a.jsx)(Ke,{id:"ai-api-key",type:"password",autoComplete:"off",value:e,onChange:u=>t(u.target.value),placeholder:l?`Saved ${l}`:"Paste an API key"}),(0,a.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Kept in memory for this tab only and cleared when the page reloads.",i&&" Leave empty to use the hosted Gemini key."]}),r.storageError&&(0,a.jsx)("p",{className:"text-xs text-destructive",children:r.storageError}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(B,{type:"button",disabled:!e.trim(),onClick:c,children:"Save key"}),o&&o.state!=="empty"&&(0,a.jsx)(B,{type:"button",variant:"outline",onClick:d,children:i?"Use hosted key":"Remove key"})]})]}),(0,a.jsxs)("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)(me,{htmlFor:"include-schema",children:"Include database schema"}),(0,a.jsx)("p",{className:"text-xs text-muted-foreground",children:"Share table and column metadata for context-aware answers."})]}),(0,a.jsx)(Zn,{id:"include-schema",checked:s.includeSchemaInAiContext,onCheckedChange:s.setIncludeSchemaInAiContext})]})]})},ym=yd("hover:text-foreground aria-pressed:bg-muted focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[state=on]:bg-accent data-[state=on]:text-accent-foreground gap-1 rounded-md text-xs font-medium transition-all [&_svg:not([class*='size-'])]:size-3.5 group/toggle hover:bg-muted inline-flex items-center justify-center whitespace-nowrap outline-none focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",{variants:{variant:{default:"bg-transparent",ghost:"bg-transparent hover:bg-muted",outline:"border-input hover:bg-muted border bg-transparent"},size:{default:"h-7 min-w-7 px-2",sm:"h-6 min-w-6 rounded-[min(var(--radius-md),8px)] px-1.5 text-[0.625rem] [&_svg:not([class*='size-'])]:size-3",lg:"h-8 min-w-8 px-2"}},defaultVariants:{variant:"default",size:"default"}});function jR({className:e,variant:t="default",size:r="default",...s}){return(0,a.jsx)(jp,{"data-slot":"toggle",className:V(ym({variant:t,size:r,className:e})),...s})}var bm=f.createContext({size:"default",variant:"default",spacing:0,orientation:"horizontal"});function Xc({className:e,variant:t,size:r,spacing:s=0,orientation:n="horizontal",children:o,...l}){return(0,a.jsx)(Np,{"data-slot":"toggle-group","data-variant":t,"data-size":r,"data-spacing":s,"data-orientation":n,style:{"--gap":s},className:V("rounded-md data-[size=sm]:rounded-[min(var(--radius-md),8px)] group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] data-[orientation=vertical]:flex-col data-[orientation=vertical]:items-stretch",e),...l,children:(0,a.jsx)(bm.Provider,{value:{variant:t,size:r,spacing:s,orientation:n},children:o})})}function Zc({className:e,children:t,variant:r="default",size:s="default",...n}){const o=(0,f.use)(bm);return(0,a.jsx)(kp,{"data-slot":"toggle-group-item","data-variant":o.variant||r,"data-size":o.size||s,"data-spacing":o.spacing,className:V("group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-l-md group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-t-md group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-r-md group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-b-md shrink-0 focus:z-10 focus-visible:z-10 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t",ym({variant:o.variant||r,size:o.size||s}),e),...n,children:t})}var BI=()=>{const{editor:e,setTabSize:t,setEditorFontSize:r,setEditorWordWrap:s}=fn();return(0,a.jsxs)("section",{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"space-y-2 rounded-lg border p-3",children:[(0,a.jsx)(me,{children:"Tab size"}),(0,a.jsx)("p",{className:"text-xs text-muted-foreground",children:"Indentation used by the query editor and JSON cells."}),(0,a.jsx)(Xc,{type:"single",variant:"outline",className:"w-full",value:String(e.tabSize),onValueChange:n=>{n&&t(Number(n))},"aria-label":"Tab size",children:mg.map(n=>(0,a.jsxs)(Zc,{value:String(n),className:"flex-1",children:[n," spaces"]},n))})]}),(0,a.jsxs)("div",{className:"space-y-2 rounded-lg border p-3",children:[(0,a.jsx)(me,{children:"Font size"}),(0,a.jsx)("p",{className:"text-xs text-muted-foreground",children:"Text size in the query editor."}),(0,a.jsx)(Xc,{type:"single",variant:"outline",className:"w-full",value:String(e.fontSize),onValueChange:n=>{n&&r(Number(n))},"aria-label":"Editor font size",children:pg.map(n=>(0,a.jsxs)(Zc,{value:String(n),className:"flex-1",children:[n," px"]},n))})]}),(0,a.jsxs)("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)(me,{htmlFor:"editor-word-wrap",children:"Word wrap"}),(0,a.jsx)("p",{className:"text-xs text-muted-foreground",children:"Wrap long lines in the query editor instead of scrolling."})]}),(0,a.jsx)(Zn,{id:"editor-word-wrap",checked:e.wordWrap,onCheckedChange:s})]})]})},UI=()=>{const[e,t]=(0,f.useState)(lg()?.enabled??!1),[r,s]=(0,f.useState)(!1);(0,f.useEffect)(()=>{Sd().then(o=>t(o?.enabled??!1))},[]);const n=async o=>{s(!0);try{const l=await cg(o);t(l.enabled),l.enabled?await hd():await zp?.close(500),we.success(l.enabled?"Analytics enabled":"Analytics disabled")}catch(l){we.error(l instanceof Error?l.message:"Could not update analytics")}finally{s(!1)}};return(0,a.jsxs)("section",{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)(me,{htmlFor:"anonymous-telemetry",children:"Anonymous analytics"}),(0,a.jsx)("p",{className:"text-xs text-muted-foreground",children:"Share feature usage, database engine, country, performance, and sanitized errors. Queries, schemas, names, and values are never collected."})]}),(0,a.jsx)(Zn,{id:"anonymous-telemetry",checked:e,disabled:r,onCheckedChange:o=>{n(o)}})]}),(0,a.jsx)(B,{type:"button",variant:"outline",disabled:r,onClick:()=>{s(!0),og().then(()=>we.success("Analytics identifier reset")).catch(()=>we.error("Could not reset analytics identifier")).finally(()=>s(!1))},children:"Reset analytics identifier"})]})},vo=({title:e,description:t,children:r})=>(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)("h3",{className:"text-sm font-semibold",children:e}),(0,a.jsx)("p",{className:"text-xs text-muted-foreground",children:t})]}),r]}),qI=()=>{const{closeOverlay:e,isOverlayOpen:t}=je();return(0,a.jsxs)(Ut,{title:"Settings",description:"Changes apply immediately and are saved on this device.",open:t("settings.app"),size:"sm:max-w-md!",onOpenChange:r=>{r||e("settings.app")},children:[(0,a.jsx)(vo,{title:"Editor",description:"Query editor and JSON cell behavior.",children:(0,a.jsx)(BI,{})}),(0,a.jsx)(Vn,{}),(0,a.jsx)(vo,{title:"AI",description:"Provider, model, and API key for the assistant.",children:(0,a.jsx)(VI,{})}),(0,a.jsx)(Vn,{}),(0,a.jsx)(vo,{title:"Privacy",description:"Control anonymous analytics and reliability reporting.",children:(0,a.jsx)(UI,{})})]})},IR=()=>{const[e,t]=(0,f.useState)(!1);return(0,f.useEffect)(()=>{let r=!0;return nn.ready().then(()=>{r&&t(!0)}),()=>{r=!1}},[]),e},TR=()=>{const{setDbType:e,selectedDatabase:t,setSelectedDatabase:r}=Me(),{data:s,isLoading:n,error:o,refetch:l,isRefetching:i}=Rr({queryKey:$n.list(),queryFn:md,select:c=>c.data.data,staleTime:3e5});return(0,f.useEffect)(()=>{s?.dbType&&(e(s.dbType),vd(s.dbType)),!t&&s?.databases?.length&&r(s.databases[0]?.name??null)},[s?.dbType,s?.databases,t,e,r]),{databases:s?.databases,dbType:s?.dbType,isLoadingDatabases:n,databasesError:o,refetchDatabases:l,isRefetchingDatabases:i}},WI=()=>{const{selectedDatabase:e,setSelectedDatabase:t,setDbType:r}=Me(),s=(0,f.useRef)(!1),{data:n,isLoading:o,error:l}=Rr({queryKey:$n.list(),queryFn:md,select:m=>m.data.data,staleTime:3e5}),{data:i,isLoading:c,error:d}=Rr({queryKey:$n.current(),queryFn:async()=>{const m=await Pp();return r(m.data.data.dbType),vd(m.data.data.dbType),!e&&m.data.data.db&&t(m.data.data.db),m.data.data},staleTime:3e5});(0,f.useEffect)(()=>{if(s.current||o||c)return;s.current=!0;const m=i?.db||n?.databases?.[0]?.name;m&&t(m)},[o,c,i?.db,n?.databases,t]);const u=o||c,h=s.current;return{currentDatabase:i,databases:n?.databases,isLoading:u,isInitialized:h,error:l||d}},RR=()=>{const{data:e,isLoading:t,error:r}=Rr({queryKey:$n.connectionInfo(),queryFn:Fp,select:s=>s.data.data,staleTime:3e5});return{connectionInfo:e,isLoadingConnectionInfo:t,connectionInfoError:r}},KI=`
|
|
17
|
+
try {
|
|
18
|
+
const stored = localStorage.getItem('db-studio-personal-preferences');
|
|
19
|
+
const theme = stored ? JSON.parse(stored)?.state?.theme : 'dark';
|
|
20
|
+
const isDark = theme === 'dark' || (theme === 'system' ? window.matchMedia('(prefers-color-scheme: dark)').matches : false);
|
|
21
|
+
if (isDark) {
|
|
22
|
+
document.documentElement.classList.add('dark');
|
|
23
|
+
document.documentElement.classList.remove('light');
|
|
24
|
+
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', '#09090b');
|
|
25
|
+
} else {
|
|
26
|
+
document.documentElement.classList.remove('dark');
|
|
27
|
+
document.documentElement.classList.add('light');
|
|
28
|
+
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', '#ffffff');
|
|
29
|
+
}
|
|
30
|
+
} catch (_) {
|
|
31
|
+
document.documentElement.classList.add('dark');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
try {
|
|
35
|
+
if (/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
|
|
36
|
+
document.documentElement.classList.add('os-macos');
|
|
37
|
+
}
|
|
38
|
+
} catch (_) {}
|
|
39
|
+
`,xm=Tm({component:function(){nl();const t=sd({select:i=>i.pathname}),{dbType:r}=Me(),{isLoading:s,isInitialized:n,error:o}=WI();(0,f.useEffect)(()=>{if(o&&r){const i=o?.status;cr.capture("connection_error",{db_type:r,status_bucket:i?i>=500?"5xx":"4xx":"network"})}},[o,r]),(0,f.useEffect)(()=>{const i="db-studio-telemetry-notice-shown";Sd().then(c=>{c?.enabled&&(hd(),localStorage.getItem(i)||(localStorage.setItem(i,"1"),we.info("Anonymous usage and reliability data helps improve DB Studio.",{description:"Queries, schemas, names, and values are never collected. Disable it in Settings.",duration:8e3})))})},[]),(0,f.useEffect)(()=>{const i=t.split("/").filter(Boolean)[0],c=["browser","table","schema","runner","visualizer","logs","indexes"].find(d=>d===i)??"home";cr.capture("page_viewed",{page:c})},[t]);const l=(s||!n)&&!o;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("script",{defer:!0,src:`data:text/javascript;base64,${btoa(KI)}`}),(0,a.jsx)(qg,{fullPageNavigationOnShallowFalseUpdates:!0,defaultOptions:{shallow:!0,clearOnDefault:!0},children:l?(0,a.jsx)("div",{className:"flex items-center justify-center h-screen",children:(0,a.jsx)(dn,{size:"size-8",color:"bg-primary"})}):o?(0,a.jsxs)("div",{className:"flex flex-col items-center justify-center h-screen gap-3 text-center",children:[(0,a.jsx)("p",{className:"text-destructive font-medium",children:"Failed to connect to the database"}),(0,a.jsx)("p",{className:"text-muted-foreground text-sm max-w-sm",children:o?.message??"An unexpected error occurred"})]}):(0,a.jsx)(Nm,{})}),(0,a.jsx)(Sg,{position:"top-right"}),(0,a.jsx)(tN,{}),(0,a.jsx)(Qw,{}),(0,a.jsx)(qI,{})]})}}),HI=()=>Ct(()=>import("./_pathlessLayout-DYRsUfs6.js").then(e=>e.t),__vite__mapDeps([15,1,16,2,3,17,4,5,18,19,20,7,21,10,22,23,24,25,6,8,26,27])),GI=At("/_pathlessLayout")({component:kt(HI,"component")}),YI=()=>Ct(()=>import("./_pathlessLayout-D83hYFIC.js"),__vite__mapDeps([28,16,1,2,3])),JI=At("/_pathlessLayout/")({component:kt(YI,"component")}),QI=()=>Ct(()=>import("./browser-dcbfhXDu.js"),__vite__mapDeps([29,1,16,2,3,17,4,5,18,19,20,7,21,10,23,26,8,27,24])),XI=At("/_pathlessLayout/browser")({component:kt(QI,"component")}),ZI=()=>Ct(()=>import("./logs-Ncb6EFEi.js"),__vite__mapDeps([30,3,1,2])),eT=At("/_pathlessLayout/logs")({component:kt(ZI,"component")}),tT=()=>Ct(()=>import("./visualizer-Cxu0_nai.js"),__vite__mapDeps([31,3,1,2])),rT=At("/_pathlessLayout/visualizer")({component:kt(tT,"component")}),sT=()=>Ct(()=>import("./indexes-Cv0o_HTj.js"),__vite__mapDeps([32,3,1,2])),nT=At("/_pathlessLayout/indexes/")({component:kt(sT,"component")}),aT=()=>Ct(()=>import("./_table-Cwy7lxKk.js"),__vite__mapDeps([33,1,16,2,3,17,4,5,18,19,20,7,21,10,22,23,24])),oT=At("/_pathlessLayout/indexes/$table")({component:kt(aT,"component")}),iT=()=>Ct(()=>import("./runner-WhyDqbco.js"),__vite__mapDeps([34,3,1,2,35,16,17,18,4,5,20,7,21,10,26,8])),lT=At("/_pathlessLayout/runner/")({validateSearch:e=>typeof e.cmd=="string"?{cmd:e.cmd}:{},component:kt(iT,"component")}),cT=()=>Ct(()=>import("./_queryId-DmyRcSX-.js"),__vite__mapDeps([36,3,1,2,35,16,17,18,4,5,20,7,21,10,26,8])),dT=At("/_pathlessLayout/runner/$queryId")({component:kt(cT,"component")}),uT=()=>Ct(()=>import("./schema-DdnQO20v.js"),__vite__mapDeps([37,3,1,2])),fT=At("/_pathlessLayout/schema/")({component:kt(uT,"component")}),hT=()=>Ct(()=>import("./_table-DaqO5XGq.js"),__vite__mapDeps([38,3,1,2])),mT=At("/_pathlessLayout/schema/$table")({component:kt(hT,"component")}),pT=()=>Ct(()=>import("./table-Gq1Nd4WJ.js"),__vite__mapDeps([39,3,1,2])),gT=At("/_pathlessLayout/table/")({component:kt(pT,"component")}),Mt=GI.update({id:"/_pathlessLayout",getParentRoute:()=>xm}),vT=JI.update({id:"/",path:"/",getParentRoute:()=>Mt}),yT=XI.update({id:"/browser",path:"/browser",getParentRoute:()=>Mt}),bT=eT.update({id:"/logs",path:"/logs",getParentRoute:()=>Mt}),xT=rT.update({id:"/visualizer",path:"/visualizer",getParentRoute:()=>Mt}),ST=nT.update({id:"/indexes/",path:"/indexes/",getParentRoute:()=>Mt}),CT=oT.update({id:"/indexes/$table",path:"/indexes/$table",getParentRoute:()=>Mt}),wT=lT.update({id:"/runner/",path:"/runner/",getParentRoute:()=>Mt}),NT=dT.update({id:"/runner/$queryId",path:"/runner/$queryId",getParentRoute:()=>Mt}),jT=fT.update({id:"/schema/",path:"/schema/",getParentRoute:()=>Mt}),IT=mT.update({id:"/schema/$table",path:"/schema/$table",getParentRoute:()=>Mt}),TT=gT.update({id:"/table/",path:"/table/",getParentRoute:()=>Mt}),RT={PathlessLayoutBrowserRoute:yT,PathlessLayoutLogsRoute:bT,PathlessLayoutVisualizerRoute:xT,PathlessLayoutIndexRoute:vT,PathlessLayoutIndexesTableRoute:CT,PathlessLayoutRunnerQueryIdRoute:NT,PathlessLayoutSchemaTableRoute:IT,PathlessLayoutTableTableRoute:al.update({id:"/table/$table",path:"/table/$table",getParentRoute:()=>Mt}),PathlessLayoutIndexesIndexRoute:ST,PathlessLayoutRunnerIndexRoute:wT,PathlessLayoutSchemaIndexRoute:jT,PathlessLayoutTableIndexRoute:TT},ET={PathlessLayoutRoute:Mt._addFileChildren(RT)},kT=xm._addFileChildren(ET)._addFileTypes(),AT=km({routeTree:kT,context:{queryClient:Nd()},defaultPreload:"intent",scrollRestoration:!0,defaultStructuralSharing:!0}),yo=document.getElementById("root");if(yo&&!yo.innerHTML){const e=gg.createRoot(yo),t=Nd();e.render((0,a.jsx)(f.StrictMode,{children:(0,a.jsx)(Sm,{client:t,children:(0,a.jsx)(Im,{router:AT})})}))}export{xv as $,sR as A,eR as B,nw as C,ou as D,ve as E,tu as F,eu as G,kr as H,$t as I,mt as J,XT as K,ru as L,ha as M,gn as N,nR as O,yn as P,Ms as Q,ZT as R,nl as S,Ar as T,Oi as U,vn as V,dr as W,da as X,_r as Y,Ot as Z,SR as _,RR as a,bi as at,vR as b,Xc as c,$I as d,bv as et,zI as f,bR as g,nn as h,oT as i,aa as it,rR as j,by as k,Zc as l,CR as m,dT as n,ta as nt,TR as o,sa as ot,wR as p,fa as q,lT as r,ra as rt,IR as s,na as st,mT as t,et as tt,jR as u,yR as v,ke as w,al as x,xR as y,tR as z};
|