const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TableSchemaView-1sbDFRYn.js","assets/vendor-codemirror-CkItnc0H.js","assets/vendor-ui-BLV2MnSs.js","assets/vendor-ag-grid-NsbaVf01.js","assets/ExportDialog-AcQ1rtHi.js"])))=>i.map(i=>d[i]);
import{j as e,s as We,M as ue,a as pt,R as Je,o as Ve,P as gt,k as bt}from"./vendor-codemirror-CkItnc0H.js";import{r as i,g as vt,R as Ke,c as fe,X as we,C as Ge,a as yt,L as ae,b as je,D as Ye,W as jt,E as wt,T as re,S as St,d as Ie,e as Se,U as ne,f as Re,h as Xe,i as Te,j as Ze,k as Pe,l as Nt,P as Ct,m as kt,n as Et,o as Tt,p as et,q as $t,B as _t,s as Dt,H as It,F as Rt,t as zt}from"./vendor-ui-BLV2MnSs.js";import{r as tt,t as Lt,A as Ot}from"./vendor-ag-grid-NsbaVf01.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();var _e={},Fe=tt;_e.createRoot=Fe.createRoot,_e.hydrateRoot=Fe.hydrateRoot;const Pt={},Me=t=>{let a;const s=new Set,n=(x,f)=>{const j=typeof x=="function"?x(a):x;if(!Object.is(j,a)){const v=a;a=f??(typeof j!="object"||j===null)?j:Object.assign({},a,j),s.forEach(S=>S(a,v))}},r=()=>a,d={setState:n,getState:r,getInitialState:()=>u,subscribe:x=>(s.add(x),()=>s.delete(x)),destroy:()=>{(Pt?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),s.clear()}},u=a=t(n,r,d);return d},Ft=t=>t?Me(t):Me;var st={exports:{}},at={},rt={exports:{}},nt={};/**
 * @license React
 * use-sync-external-store-shim.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var oe=i;function Mt(t,a){return t===a&&(t!==0||1/t===1/a)||t!==t&&a!==a}var At=typeof Object.is=="function"?Object.is:Mt,qt=oe.useState,Bt=oe.useEffect,Ut=oe.useLayoutEffect,Qt=oe.useDebugValue;function Ht(t,a){var s=a(),n=qt({inst:{value:s,getSnapshot:a}}),r=n[0].inst,o=n[1];return Ut(function(){r.value=s,r.getSnapshot=a,$e(r)&&o({inst:r})},[t,s,a]),Bt(function(){return $e(r)&&o({inst:r}),t(function(){$e(r)&&o({inst:r})})},[t]),Qt(s),s}function $e(t){var a=t.getSnapshot;t=t.value;try{var s=a();return!At(t,s)}catch{return!0}}function Wt(t,a){return a()}var Jt=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Wt:Ht;nt.useSyncExternalStore=oe.useSyncExternalStore!==void 0?oe.useSyncExternalStore:Jt;rt.exports=nt;var Vt=rt.exports;/**
 * @license React
 * use-sync-external-store-shim/with-selector.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var Ne=i,Kt=Vt;function Gt(t,a){return t===a&&(t!==0||1/t===1/a)||t!==t&&a!==a}var Yt=typeof Object.is=="function"?Object.is:Gt,Xt=Kt.useSyncExternalStore,Zt=Ne.useRef,es=Ne.useEffect,ts=Ne.useMemo,ss=Ne.useDebugValue;at.useSyncExternalStoreWithSelector=function(t,a,s,n,r){var o=Zt(null);if(o.current===null){var l={hasValue:!1,value:null};o.current=l}else l=o.current;o=ts(function(){function d(v){if(!u){if(u=!0,x=v,v=n(v),r!==void 0&&l.hasValue){var S=l.value;if(r(S,v))return f=S}return f=v}if(S=f,Yt(x,v))return S;var h=n(v);return r!==void 0&&r(S,h)?(x=v,S):(x=v,f=h)}var u=!1,x,f,j=s===void 0?null:s;return[function(){return d(a())},j===null?void 0:function(){return d(j())}]},[a,s,n,r]);var c=Xt(t,o[0],o[1]);return es(function(){l.hasValue=!0,l.value=c},[c]),ss(c),c};st.exports=at;var as=st.exports;const rs=vt(as),ot={},{useDebugValue:ns}=Ke,{useSyncExternalStoreWithSelector:os}=rs;let Ae=!1;const ls=t=>t;function is(t,a=ls,s){(ot?"production":void 0)!=="production"&&s&&!Ae&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),Ae=!0);const n=os(t.subscribe,t.getState,t.getServerState||t.getInitialState,a,s);return ns(n),n}const qe=t=>{(ot?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const a=typeof t=="function"?Ft(t):t,s=(n,r)=>is(a,n,r);return Object.assign(s,a),s},Ce=t=>t?qe(t):qe,cs={};function ds(t,a){let s;try{s=t()}catch{return}return{getItem:r=>{var o;const l=d=>d===null?null:JSON.parse(d,void 0),c=(o=s.getItem(r))!=null?o:null;return c instanceof Promise?c.then(l):l(c)},setItem:(r,o)=>s.setItem(r,JSON.stringify(o,void 0)),removeItem:r=>s.removeItem(r)}}const xe=t=>a=>{try{const s=t(a);return s instanceof Promise?s:{then(n){return xe(n)(s)},catch(n){return this}}}catch(s){return{then(n){return this},catch(n){return xe(n)(s)}}}},us=(t,a)=>(s,n,r)=>{let o={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:b=>b,version:0,merge:(b,k)=>({...k,...b}),...a},l=!1;const c=new Set,d=new Set;let u;try{u=o.getStorage()}catch{}if(!u)return t((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),s(...b)},n,r);const x=xe(o.serialize),f=()=>{const b=o.partialize({...n()});let k;const y=x({state:b,version:o.version}).then(R=>u.setItem(o.name,R)).catch(R=>{k=R});if(k)throw k;return y},j=r.setState;r.setState=(b,k)=>{j(b,k),f()};const v=t((...b)=>{s(...b),f()},n,r);let S;const h=()=>{var b;if(!u)return;l=!1,c.forEach(y=>y(n()));const k=((b=o.onRehydrateStorage)==null?void 0:b.call(o,n()))||void 0;return xe(u.getItem.bind(u))(o.name).then(y=>{if(y)return o.deserialize(y)}).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==o.version){if(o.migrate)return o.migrate(y.state,y.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return y.state}).then(y=>{var R;return S=o.merge(y,(R=n())!=null?R:v),s(S,!0),f()}).then(()=>{k==null||k(S,void 0),l=!0,d.forEach(y=>y(S))}).catch(y=>{k==null||k(void 0,y)})};return r.persist={setOptions:b=>{o={...o,...b},b.getStorage&&(u=b.getStorage())},clearStorage:()=>{u==null||u.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>h(),hasHydrated:()=>l,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(d.add(b),()=>{d.delete(b)})},h(),S||v},xs=(t,a)=>(s,n,r)=>{let o={storage:ds(()=>localStorage),partialize:h=>h,version:0,merge:(h,b)=>({...b,...h}),...a},l=!1;const c=new Set,d=new Set;let u=o.storage;if(!u)return t((...h)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),s(...h)},n,r);const x=()=>{const h=o.partialize({...n()});return u.setItem(o.name,{state:h,version:o.version})},f=r.setState;r.setState=(h,b)=>{f(h,b),x()};const j=t((...h)=>{s(...h),x()},n,r);r.getInitialState=()=>j;let v;const S=()=>{var h,b;if(!u)return;l=!1,c.forEach(y=>{var R;return y((R=n())!=null?R:j)});const k=((b=o.onRehydrateStorage)==null?void 0:b.call(o,(h=n())!=null?h:j))||void 0;return xe(u.getItem.bind(u))(o.name).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==o.version){if(o.migrate)return[!0,o.migrate(y.state,y.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,y.state];return[!1,void 0]}).then(y=>{var R;const[F,M]=y;if(v=o.merge(M,(R=n())!=null?R:j),s(v,!0),F)return x()}).then(()=>{k==null||k(v,void 0),v=n(),l=!0,d.forEach(y=>y(v))}).catch(y=>{k==null||k(void 0,y)})};return r.persist={setOptions:h=>{o={...o,...h},h.storage&&(u=h.storage)},clearStorage:()=>{u==null||u.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>S(),hasHydrated:()=>l,onHydrate:h=>(c.add(h),()=>{c.delete(h)}),onFinishHydration:h=>(d.add(h),()=>{d.delete(h)})},o.skipHydration||S(),v||j},ms=(t,a)=>"getStorage"in a||"serialize"in a||"deserialize"in a?((cs?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),us(t,a)):xs(t,a),ze=ms,De="/api/v1";async function z(t,a){const s={...a==null?void 0:a.headers};a!=null&&a.body&&(s["Content-Type"]??(s["Content-Type"]="application/json"));const n=await fetch(`${De}${t}`,{...a,headers:s});if(!n.ok){const r=await n.json().catch(()=>({detail:n.statusText}));throw new Error(r.detail||`HTTP ${n.status}`)}if(n.status!==204)return n.json()}const A={getSessions:()=>z("/sessions"),createSession:t=>z("/sessions",{method:"POST",body:JSON.stringify(t)}),getSession:t=>z(`/sessions/${t}`),updateSession:(t,a)=>z(`/sessions/${t}`,{method:"PUT",body:JSON.stringify(a)}),deleteSession:t=>z(`/sessions/${t}`,{method:"DELETE"}),testSession:t=>z(`/sessions/${t}/test`,{method:"POST"}),probeConnection:t=>z("/sessions/probe",{method:"POST",body:JSON.stringify(t)}),getDatabases:t=>z(`/sessions/${t}/databases`),getTables:(t,a)=>z(`/sessions/${t}/databases/${a}/tables`),getColumns:(t,a,s)=>z(`/sessions/${t}/databases/${a}/tables/${s}/columns`),getIndexes:(t,a,s)=>z(`/sessions/${t}/databases/${a}/tables/${s}/indexes`),getCreateSql:(t,a,s)=>z(`/sessions/${t}/databases/${a}/tables/${s}/create_sql`),executeQuery:(t,a,s,n)=>z(`/sessions/${t}/query`,{method:"POST",body:JSON.stringify({sql:a,database:s,limit:n})}),cellUpdate:(t,a)=>z(`/sessions/${t}/cell-update`,{method:"POST",body:JSON.stringify(a)}),rowInsert:(t,a)=>z(`/sessions/${t}/row-insert`,{method:"POST",body:JSON.stringify(a)}),rowDelete:(t,a)=>z(`/sessions/${t}/rows`,{method:"DELETE",body:JSON.stringify(a)}),createTable:(t,a,s)=>z(`/sessions/${t}/databases/${a}/tables`,{method:"POST",body:JSON.stringify(s)}),dropTable:(t,a,s)=>z(`/sessions/${t}/databases/${a}/tables/${s}`,{method:"DELETE"}),truncateTable:(t,a,s)=>z(`/sessions/${t}/databases/${a}/tables/${s}/truncate`,{method:"POST"}),createIndex:(t,a,s,n)=>z(`/sessions/${t}/databases/${a}/tables/${s}/indexes`,{method:"POST",body:JSON.stringify(n)}),dropIndex:(t,a,s,n)=>z(`/sessions/${t}/databases/${a}/tables/${s}/indexes/${n}`,{method:"DELETE"}),setPrimaryKey:(t,a,s,n)=>z(`/sessions/${t}/databases/${a}/tables/${s}/primary-key`,{method:"POST",body:JSON.stringify({columns:n})}),dropPrimaryKey:(t,a,s)=>z(`/sessions/${t}/databases/${a}/tables/${s}/primary-key`,{method:"DELETE"}),addColumn:(t,a,s,n)=>z(`/sessions/${t}/databases/${a}/tables/${s}/columns`,{method:"POST",body:JSON.stringify(n)}),modifyColumn:(t,a,s,n,r)=>z(`/sessions/${t}/databases/${a}/tables/${s}/columns/${n}`,{method:"PUT",body:JSON.stringify(r)}),dropColumn:(t,a,s,n)=>z(`/sessions/${t}/databases/${a}/tables/${s}/columns/${n}`,{method:"DELETE"}),exportConfig:async t=>{const a=await fetch(`${De}/config/export`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:t})});if(!a.ok){const d=await a.json().catch(()=>({detail:a.statusText}));throw new Error(d.detail||`HTTP ${a.status}`)}const s=await a.blob(),r=(a.headers.get("Content-Disposition")??"").match(/filename="([^"]+)"/),o=r?r[1]:"lagun_sessions.json",l=URL.createObjectURL(s),c=document.createElement("a");c.href=l,c.download=o,c.click(),URL.revokeObjectURL(l)},importConfig:async(t,a)=>{const s=new FormData;s.append("file",t),s.append("passphrase",a);const n=await fetch(`${De}/config/import`,{method:"POST",body:s});if(!n.ok){const r=await n.json().catch(()=>({detail:n.statusText}));throw new Error(r.detail||`HTTP ${n.status}`)}return n.json()}},ee=Ce()(ze((t,a)=>({sessions:[],activeSessionId:null,loading:!1,error:null,loadSessions:async()=>{t({loading:!0,error:null});try{const s=await A.getSessions();t({sessions:s,loading:!1})}catch(s){t({error:String(s),loading:!1})}},setActiveSession:s=>t({activeSessionId:s}),createSession:async s=>{const n=await A.createSession(s);return t(r=>({sessions:[...r.sessions,n]})),n},updateSession:async(s,n)=>{const r=await A.updateSession(s,n);return t(o=>({sessions:o.sessions.map(l=>l.id===s?r:l)})),r},deleteSession:async s=>{await A.deleteSession(s),t(n=>({sessions:n.sessions.filter(r=>r.id!==s),activeSessionId:n.activeSessionId===s?null:n.activeSessionId}))},testSession:async s=>A.testSession(s)}),{name:"lagun-session-ui",version:1,partialize:t=>({activeSessionId:t.activeSessionId})}));function fs(){var t;return((t=crypto.randomUUID)==null?void 0:t.call(crypto))??"10000000-1000-4000-8000-100000000000".replace(/[018]/g,a=>(+a^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+a/4).toString(16))}function Be(){return`tab-${fs()}`}const te=Ce()(ze((t,a)=>({tabs:[],activeTabId:null,openQueryTab:(s,n)=>{const r=Be(),o={id:r,label:n?`Query — ${n}`:"Query",type:"query",sessionId:s,database:n};t(l=>({tabs:[...l.tabs,o],activeTabId:r}))},openTableTab:(s,n,r)=>{const o=a().tabs.find(d=>d.type==="table"&&d.sessionId===s&&d.database===n&&d.table===r);if(o){t({activeTabId:o.id});return}const l=Be(),c={id:l,label:r,type:"table",sessionId:s,database:n,table:r};t(d=>({tabs:[...d.tabs,c],activeTabId:l}))},closeTab:s=>{t(n=>{var l;const r=n.tabs.filter(c=>c.id!==s);let o=n.activeTabId;if(o===s){const c=n.tabs.findIndex(d=>d.id===s);o=((l=r[Math.max(0,c-1)])==null?void 0:l.id)??null}return{tabs:r,activeTabId:o}})},setActiveTab:s=>t({activeTabId:s}),setSql:(s,n)=>t(r=>({tabs:r.tabs.map(o=>o.id===s?{...o,sql:n}:o)}))}),{name:"lagun-tabs",version:2,partialize:t=>({tabs:t.tabs,activeTabId:t.activeTabId})})),B=i.forwardRef(({variant:t="secondary",size:a="md",className:s,children:n,...r},o)=>e.jsx("button",{ref:o,className:fe("inline-flex items-center justify-center gap-1.5 font-medium rounded-md transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 disabled:opacity-50 disabled:cursor-not-allowed",{"bg-brand-600 hover:bg-brand-500 text-white":t==="primary","bg-surface-700 hover:bg-surface-600 text-slate-200 border border-surface-600":t==="secondary","hover:bg-surface-800 text-slate-400 hover:text-slate-200":t==="ghost","bg-red-700 hover:bg-red-600 text-white":t==="danger"},{"px-2 py-1 text-xs":a==="sm","px-3 py-1.5 text-sm":a==="md","px-4 py-2 text-base":a==="lg"},s),...r,children:n}));B.displayName="Button";function ke({open:t,onClose:a,title:s,children:n,footer:r,width:o="max-w-lg"}){return i.useEffect(()=>{if(!t)return;const l=c=>{c.key==="Escape"&&a()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[t,a]),t?e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[e.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:a}),e.jsxs("div",{className:`relative bg-surface-900 border border-surface-700 rounded-lg shadow-2xl w-full ${o} flex flex-col max-h-[90vh]`,children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-surface-700",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-100",children:s}),e.jsx(B,{variant:"ghost",size:"sm",onClick:a,className:"p-1",children:e.jsx(we,{size:14})})]}),e.jsx("div",{className:"p-4 overflow-y-auto flex-1",children:n}),r&&e.jsx("div",{className:"px-4 py-3 border-t border-surface-700 flex justify-end gap-2",children:r})]})]}):null}const Y=i.forwardRef(({label:t,error:a,className:s,...n},r)=>{const o=n.id??(t?`input-${t.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}`:void 0);return e.jsxs("div",{className:"flex flex-col gap-1",children:[t&&e.jsx("label",{htmlFor:o,className:"text-xs font-medium text-slate-400 uppercase tracking-wide",children:t}),e.jsx("input",{ref:r,id:o,className:fe("bg-surface-800 border border-surface-700 rounded-md px-3 py-1.5 text-sm text-slate-100 placeholder-slate-500","focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500","disabled:opacity-50 disabled:cursor-not-allowed",a&&"border-red-500",s),...n}),a&&e.jsx("p",{className:"text-xs text-red-400",children:a})]})});Y.displayName="Input";const Ue={name:"",host:"localhost",port:"3306",username:"root",password:"",default_db:"",query_limit:"100",ssl_enabled:!1};function lt({open:t,onClose:a,session:s}){const{createSession:n,updateSession:r,testSession:o}=ee(),[l,c]=i.useState(Ue),[d,u]=i.useState(!1),[x,f]=i.useState(!1),[j,v]=i.useState(null),[S,h]=i.useState([]),[b,k]=i.useState([]),[y,R]=i.useState(!1),[F,M]=i.useState(null),[W,O]=i.useState(null);i.useEffect(()=>{s?(c({name:s.name,host:s.host,port:String(s.port),username:s.username,password:"",default_db:s.default_db??"",query_limit:String(s.query_limit),ssl_enabled:s.ssl_enabled}),k(s.selected_databases??[])):(c(Ue),k([])),O(null),v(null),h([]),M(null)},[s,t]);const N=(m,$)=>c(Q=>({...Q,[m]:$})),p=async()=>{u(!0),O(null);try{const m={name:l.name,host:l.host,port:parseInt(l.port),username:l.username,...l.password?{password:l.password}:{},default_db:l.default_db||void 0,query_limit:parseInt(l.query_limit),ssl_enabled:l.ssl_enabled,selected_databases:b};s?await r(s.id,m):await n({...m,password:l.password}),a()}catch(m){O(String(m))}finally{u(!1)}},T=async()=>{f(!0),v(null);try{let m;s?m=await o(s.id):m=await A.probeConnection({host:l.host,port:parseInt(l.port),username:l.username,password:l.password,ssl_enabled:l.ssl_enabled}),m.ok?v({ok:!0,msg:`Connected! MySQL ${m.server_version} — ${m.latency_ms}ms`}):v({ok:!1,msg:m.error??"Connection failed"})}finally{f(!1)}},D=async()=>{R(!0),M(null);try{let m;if(s?m=await o(s.id):m=await A.probeConnection({host:l.host,port:parseInt(l.port),username:l.username,password:l.password,ssl_enabled:l.ssl_enabled}),m.ok){const $=m.databases??[];h($),k(Q=>Q.filter(J=>$.includes(J)))}else M(m.error??"Connection failed")}catch(m){M(String(m))}finally{R(!1)}},I=m=>{k($=>$.includes(m)?$.filter(Q=>Q!==m):[...$,m])},U=()=>{k(m=>m.length===S.length?[]:[...S])};return e.jsx(ke,{open:t,onClose:a,title:s?"Edit Connection":"New Connection",footer:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",onClick:a,children:"Cancel"}),e.jsxs(B,{variant:"secondary",onClick:T,disabled:x,children:[x?e.jsx(ae,{size:12,className:"animate-spin"}):null,"Test"]}),e.jsxs(B,{variant:"primary",onClick:p,disabled:d,children:[d?e.jsx(ae,{size:12,className:"animate-spin"}):null,s?"Save":"Create"]})]}),children:e.jsxs("div",{className:"flex flex-col gap-3",children:[j&&e.jsxs("div",{className:`flex items-center gap-2 text-xs px-3 py-2 rounded ${j.ok?"bg-green-900/40 text-green-300":"bg-red-900/40 text-red-300"}`,children:[j.ok?e.jsx(Ge,{size:12}):e.jsx(yt,{size:12}),j.msg]}),W&&e.jsx("p",{className:"text-xs text-red-400",children:W}),e.jsx(Y,{label:"Connection Name",value:l.name,onChange:m=>N("name",m.target.value),placeholder:"My Database"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx("div",{className:"col-span-2",children:e.jsx(Y,{label:"Host",value:l.host,onChange:m=>N("host",m.target.value),placeholder:"localhost"})}),e.jsx(Y,{label:"Port",type:"number",value:l.port,onChange:m=>N("port",m.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Y,{label:"Username",value:l.username,onChange:m=>N("username",m.target.value),placeholder:"root"}),e.jsx(Y,{label:"Password",type:"password",value:l.password,onChange:m=>N("password",m.target.value),placeholder:s?"(unchanged)":""})]}),e.jsx(Y,{label:"Default Database (optional)",value:l.default_db,onChange:m=>N("default_db",m.target.value),placeholder:"my_db"}),e.jsx(Y,{label:"Row Limit",type:"number",value:l.query_limit,onChange:m=>N("query_limit",m.target.value)}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-slate-300 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:l.ssl_enabled,onChange:m=>N("ssl_enabled",m.target.checked),className:"rounded"}),"Enable SSL"]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-slate-400 uppercase tracking-wide",children:"Databases"}),e.jsxs("div",{className:"flex items-center gap-2",children:[S.length>0&&e.jsx("button",{type:"button",onClick:U,className:"text-xs text-brand-400 hover:text-brand-300",children:b.length===S.length?"Deselect all":"Select all"}),e.jsxs("button",{type:"button",onClick:D,disabled:y,title:"Fetch databases from server",className:"flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-surface-700 hover:bg-surface-600 text-slate-300 disabled:opacity-50",children:[y?e.jsx(ae,{size:11,className:"animate-spin"}):e.jsx(je,{size:11}),"Fetch"]})]})]}),F&&e.jsx("p",{className:"text-xs text-red-400",children:F}),S.length===0&&!y&&!F&&e.jsx("p",{className:"text-xs text-slate-500 italic",children:"Click Fetch to load available databases from the server."}),S.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"max-h-40 overflow-y-auto rounded border border-surface-700 bg-surface-950 divide-y divide-surface-800",children:S.map(m=>e.jsxs("label",{className:"flex items-center gap-2 px-3 py-1.5 cursor-pointer hover:bg-surface-800",children:[e.jsx("input",{type:"checkbox",checked:b.includes(m),onChange:()=>I(m),className:"rounded"}),e.jsx(Ye,{size:11,className:"text-yellow-400 flex-shrink-0"}),e.jsx("span",{className:"text-xs text-slate-300",children:m})]},m))}),e.jsx("p",{className:"text-xs text-slate-500",children:b.length===0?"No selection — all databases will be shown":`${b.length} of ${S.length} selected`})]})]})]})})}function hs({onNew:t}){const{sessions:a,activeSessionId:s,setActiveSession:n,deleteSession:r}=ee(),{openQueryTab:o}=te(),[l,c]=i.useState(null),[d,u]=i.useState(null);return a.length===0?e.jsx("div",{className:"px-3 py-4 text-center text-xs text-slate-500",children:"No connections yet."}):e.jsxs("div",{className:"py-1",children:[a.map(x=>e.jsxs("div",{className:fe("flex items-center px-3 py-1.5 cursor-pointer group transition-colors",s===x.id?"bg-brand-600/20 text-brand-300":"hover:bg-surface-800 text-slate-300"),onClick:()=>n(x.id),children:[e.jsx(jt,{size:12,className:"flex-shrink-0 mr-2 text-green-400"}),e.jsx("span",{className:"flex-1 truncate text-xs",children:x.name}),e.jsx("span",{className:"text-slate-500 text-xs mr-1",children:x.host}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{onClick:f=>{f.stopPropagation(),u(d===x.id?null:x.id)},className:"opacity-0 group-hover:opacity-100 p-0.5 rounded hover:bg-surface-700 text-slate-400 hover:text-slate-200",children:e.jsx(wt,{size:12})}),d===x.id&&e.jsxs("div",{className:"absolute right-0 top-6 bg-surface-800 border border-surface-700 rounded shadow-lg z-50 py-1 w-40",onMouseLeave:()=>u(null),children:[e.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-surface-700 text-slate-200",onClick:f=>{f.stopPropagation(),o(x.id),u(null)},children:[e.jsx(re,{size:12})," New Query"]}),e.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-surface-700 text-slate-200",onClick:f=>{f.stopPropagation(),c(x),u(null)},children:[e.jsx(St,{size:12})," Edit"]}),e.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-surface-700 text-red-400",onClick:f=>{f.stopPropagation(),r(x.id),u(null)},children:[e.jsx(Ie,{size:12})," Delete"]})]})]})]},x.id)),l&&e.jsx(lt,{open:!!l,onClose:()=>c(null),session:l})]})}function ps({open:t,onClose:a}){const[s,n]=i.useState(""),[r,o]=i.useState(""),[l,c]=i.useState(!1),[d,u]=i.useState(null),x=()=>{n(""),o(""),u(null),a()},f=async()=>{if(u(null),!s){u("Enter a passphrase to protect the exported passwords.");return}if(s!==r){u("Passphrases do not match.");return}c(!0);try{await A.exportConfig(s),x()}catch(j){u(String(j))}finally{c(!1)}};return e.jsx(ke,{open:t,onClose:x,title:"Export Connections",width:"max-w-md",footer:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",onClick:x,children:"Cancel"}),e.jsxs(B,{variant:"primary",onClick:f,disabled:l,children:[l?e.jsx(ae,{size:12,className:"animate-spin mr-1"}):e.jsx(Se,{size:12,className:"mr-1"}),"Download"]})]}),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Export all saved connections to an encrypted JSON file. You will need this passphrase to import the file on any Lagun instance."}),e.jsx(Y,{label:"Passphrase",type:"password",value:s,onChange:j=>n(j.target.value),placeholder:"Strong passphrase",autoComplete:"new-password"}),e.jsx(Y,{label:"Confirm passphrase",type:"password",value:r,onChange:j=>o(j.target.value),placeholder:"Repeat passphrase",autoComplete:"new-password",onKeyDown:j=>j.key==="Enter"&&f()}),d&&e.jsx("p",{className:"text-xs text-red-400",children:d})]})})}function gs({open:t,onClose:a}){const{loadSessions:s}=ee(),[n,r]=i.useState(null),[o,l]=i.useState(""),[c,d]=i.useState(!1),[u,x]=i.useState(null),[f,j]=i.useState(null),v=()=>{r(null),l(""),x(null),j(null),a()},S=async()=>{if(!n){j("Select a file first.");return}if(!o){j("Enter the passphrase used during export.");return}d(!0),j(null);try{const h=await A.importConfig(n,o);x(h),await s()}catch(h){j(String(h))}finally{d(!1)}};return e.jsx(ke,{open:t,onClose:v,title:"Import Connections",width:"max-w-md",footer:u?e.jsx(B,{variant:"primary",onClick:v,children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",onClick:v,children:"Cancel"}),e.jsxs(B,{variant:"primary",onClick:S,disabled:c||!n,children:[c?e.jsx(ae,{size:12,className:"animate-spin mr-1"}):e.jsx(ne,{size:12,className:"mr-1"}),"Import"]})]}),children:u?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-4",children:[e.jsx(Ge,{size:32,className:"text-green-400"}),e.jsx("p",{className:"text-sm text-slate-200 font-medium",children:"Import complete"}),e.jsxs("p",{className:"text-xs text-slate-400",children:[u.imported," connection",u.imported!==1?"s":""," imported",u.skipped>0?`, ${u.skipped} skipped`:"","."]})]}):e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Select a Lagun export file (.json) to restore saved connections."}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-slate-400 uppercase tracking-wide block mb-1",children:"Export file"}),e.jsx("input",{type:"file",accept:".json,application/json",onChange:h=>{var b;r(((b=h.target.files)==null?void 0:b[0])??null),j(null)},className:`text-sm text-slate-300 file:mr-3 file:py-1 file:px-3 file:rounded file:border-0
                         file:text-xs file:font-medium file:bg-surface-700 file:text-slate-200
                         hover:file:bg-surface-600 cursor-pointer`})]}),e.jsx(Y,{label:"Passphrase",type:"password",value:o,onChange:h=>l(h.target.value),placeholder:"Passphrase used during export",autoComplete:"current-password",onKeyDown:h=>h.key==="Enter"&&S()}),f&&e.jsx("p",{className:"text-xs text-red-400",children:f})]})})}const be={},ve={},ye={},me=Ce((t,a)=>({databases:{},tables:{},columns:{},loadingDbs:new Set,loadingTables:new Set,loadDatabases:async s=>{const{databases:n}=a();if(n[s])return n[s];if(be[s])return be[s];t(o=>({loadingDbs:new Set([...o.loadingDbs,s])}));const r=A.getDatabases(s).then(o=>(t(l=>({databases:{...l.databases,[s]:o},loadingDbs:new Set([...l.loadingDbs].filter(c=>c!==s))})),o)).catch(()=>(t(o=>({loadingDbs:new Set([...o.loadingDbs].filter(l=>l!==s))})),[])).finally(()=>{delete be[s]});return be[s]=r,r},loadTables:async(s,n)=>{const r=`${s}/${n}`,{tables:o}=a();if(o[r])return o[r];if(ve[r])return ve[r];t(c=>({loadingTables:new Set([...c.loadingTables,r])}));const l=A.getTables(s,n).then(c=>(t(d=>({tables:{...d.tables,[r]:c},loadingTables:new Set([...d.loadingTables].filter(u=>u!==r))})),c)).catch(()=>(t(c=>({loadingTables:new Set([...c.loadingTables].filter(d=>d!==r))})),[])).finally(()=>{delete ve[r]});return ve[r]=l,l},loadColumns:async(s,n,r)=>{const o=`${s}/${n}/${r}`,{columns:l}=a();if(l[o])return l[o];if(ye[o])return ye[o];const c=A.getColumns(s,n,r).then(d=>(t(u=>({columns:{...u.columns,[o]:d}})),d)).catch(()=>[]).finally(()=>{delete ye[o]});return ye[o]=c,c},invalidateSession:s=>{t(n=>{const r={...n.databases};delete r[s];const o=Object.fromEntries(Object.entries(n.tables).filter(([c])=>!c.startsWith(`${s}/`))),l=Object.fromEntries(Object.entries(n.columns).filter(([c])=>!c.startsWith(`${s}/`)));return{databases:r,tables:o,columns:l}})},invalidateTable:(s,n,r)=>{const o=`${s}/${n}/${r}`;t(l=>{const c={...l.columns};return delete c[o],{columns:c}})}})),Z=i.forwardRef(({label:t,error:a,className:s,children:n,...r},o)=>e.jsxs("div",{className:"flex flex-col gap-1",children:[t&&e.jsx("label",{className:"text-xs font-medium text-slate-400 uppercase tracking-wide",children:t}),e.jsx("select",{ref:o,className:fe("bg-surface-800 border border-surface-700 rounded-md px-3 py-1.5 text-sm text-slate-100","focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500","disabled:opacity-50 disabled:cursor-not-allowed",a&&"border-red-500",s),...r,children:n}),a&&e.jsx("p",{className:"text-xs text-red-400",children:a})]}));Z.displayName="Select";function it({open:t,onClose:a,sessionId:s,database:n,table:r,onImportComplete:o}){const[l,c]=i.useState(null),[d,u]=i.useState(null),[x,f]=i.useState(null),[j,v]=i.useState(!1),[S,h]=i.useState(","),[b,k]=i.useState(""),[y,R]=i.useState('"'),[F,M]=i.useState('"'),[W,O]=i.useState("crlf"),[N,p]=i.useState("utf-8"),D={crlf:`\r
`,lf:`
`,cr:"\r"}[W]||`\r
`,[I,U]=i.useState(!0),[m,$]=i.useState(r??""),[Q,J]=i.useState("insert"),[H,w]=i.useState(!1),[_,P]=i.useState(!1),[E,G]=i.useState(null),X=i.useRef(null),le=me(g=>g.tables[`${s}/${n}`]??[]),{loadTables:he}=me();i.useEffect(()=>{he(s,n)},[s,n,he]);const ie=S==="custom"?b:S,ce=i.useCallback(()=>JSON.stringify({database:n,table:m,delimiter:ie,quotechar:y,escapechar:F,lineterminator:D,encoding:N,first_row_header:I,strategy:Q}),[n,m,ie,y,F,D,N,I,Q]),C=i.useRef();i.useEffect(()=>{if(!l){u(null),f(null);return}return clearTimeout(C.current),C.current=setTimeout(async()=>{v(!0),f(null);try{const g=new FormData;g.append("file",l),g.append("config",ce());const K=await fetch(`/api/v1/sessions/${s}/import/preview`,{method:"POST",body:g});K.ok?(u(await K.json()),f(null)):(f(await K.text()),u(null))}catch(g){f(String(g)),u(null)}finally{v(!1)}},300),()=>clearTimeout(C.current)},[l,ie,y,F,W,N,I,s,ce]);const q=g=>{g&&g.length>0&&(c(g[0]),G(null))},L=g=>{g.preventDefault(),q(g.dataTransfer.files)},V=async()=>{if(!(!l||!m)){P(!0),G(null);try{const g=new FormData;g.append("file",l),g.append("config",ce());const se=await(await fetch(`/api/v1/sessions/${s}/import`,{method:"POST",body:g})).json();G(se),se.ok&&(o==null||o())}catch(g){G({ok:!1,rows_processed:0,rows_imported:0,method:"unknown",error:String(g)})}finally{P(!1)}}};return e.jsx(ke,{open:t,onClose:a,title:`Import into ${n}${m?"."+m:""}`,width:"max-w-2xl",footer:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",onClick:a,children:"Cancel"}),e.jsx(B,{variant:"primary",onClick:V,disabled:_||!l||!m,children:_?"Importing…":"Import"})]}),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"border-2 border-dashed border-surface-700 rounded-lg p-6 text-center cursor-pointer hover:border-surface-600 transition-colors",onClick:()=>{var g;return(g=X.current)==null?void 0:g.click()},onDragOver:g=>g.preventDefault(),onDrop:L,children:[e.jsx("input",{ref:X,type:"file",accept:".csv,.tsv,.txt",className:"hidden",onChange:g=>q(g.target.files)}),l?e.jsxs("div",{className:"text-sm",children:[e.jsx(ne,{size:20,className:"mx-auto mb-2 text-brand-400"}),e.jsx("p",{className:"text-slate-200",children:l.name}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[(l.size/1024).toFixed(1)," KB"]})]}):e.jsxs("div",{className:"text-sm text-slate-500",children:[e.jsx(ne,{size:20,className:"mx-auto mb-2"}),e.jsx("p",{children:"Drop a CSV file here or click to select"}),e.jsx("p",{className:"text-xs mt-1",children:".csv, .tsv, .txt"})]})]}),j&&e.jsx("p",{className:"text-xs text-slate-500",children:"Loading preview…"}),x&&e.jsx("p",{className:"text-xs text-red-400",children:x}),d&&e.jsxs("div",{className:"overflow-x-auto max-h-48 border border-surface-700 rounded",children:[e.jsxs("table",{className:"text-xs w-full",children:[e.jsx("thead",{children:e.jsx("tr",{className:"bg-surface-800",children:d.columns.map((g,K)=>e.jsx("th",{className:"px-2 py-1 text-left text-slate-300 font-medium whitespace-nowrap border-b border-surface-700",children:g},K))})}),e.jsx("tbody",{children:d.rows.map((g,K)=>e.jsx("tr",{className:"hover:bg-surface-800/50",children:g.map((se,de)=>e.jsx("td",{className:"px-2 py-1 text-slate-400 whitespace-nowrap border-b border-surface-800",children:se},de))},K))})]}),d.total_lines_sampled>d.rows.length&&e.jsxs("p",{className:"text-xs text-slate-500 px-2 py-1",children:["Showing ",d.rows.length," of ",d.total_lines_sampled,"+ rows"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs(Z,{label:"Target Table",value:m,onChange:g=>$(g.target.value),children:[e.jsx("option",{value:"",children:"Select table…"}),le.map(g=>e.jsx("option",{value:g.name,children:g.name},g.name))]}),e.jsxs(Z,{label:"Import Strategy",value:Q,onChange:g=>J(g.target.value),children:[e.jsx("option",{value:"insert",children:"INSERT (fail on duplicate)"}),e.jsx("option",{value:"insert_ignore",children:"INSERT IGNORE (skip duplicates)"}),e.jsx("option",{value:"replace",children:"REPLACE INTO (overwrite)"})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-slate-300 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:I,onChange:g=>U(g.target.checked),className:"rounded border-surface-600 bg-surface-800 text-brand-500 focus:ring-brand-500"}),"First row contains column names"]}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1 text-xs text-slate-400 hover:text-slate-200 transition-colors",onClick:()=>w(!H),children:[H?e.jsx(Re,{size:12}):e.jsx(Xe,{size:12}),"CSV Format Options"]}),H&&e.jsxs("div",{className:"mt-3 flex flex-col gap-3 pl-4 border-l border-surface-700",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Z,{label:"Delimiter",value:S,onChange:g=>h(g.target.value),children:[e.jsx("option",{value:",",children:"Comma (,)"}),e.jsx("option",{value:";",children:"Semicolon (;)"}),e.jsx("option",{value:"\\t",children:"Tab"}),e.jsx("option",{value:"|",children:"Pipe (|)"}),e.jsx("option",{value:"custom",children:"Custom"})]}),S==="custom"&&e.jsx(Y,{label:"Custom",value:b,onChange:g=>k(g.target.value.slice(0,1)),className:"w-16"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Z,{label:"Quote Character",value:y,onChange:g=>R(g.target.value),children:[e.jsx("option",{value:'"',children:'Double Quote (")'}),e.jsx("option",{value:"'",children:"Single Quote (')"}),e.jsx("option",{value:"",children:"None"})]}),e.jsxs(Z,{label:"Escape Character",value:F,onChange:g=>M(g.target.value),children:[e.jsx("option",{value:'"',children:'Double Quote (")'}),e.jsx("option",{value:"\\\\",children:"Backslash (\\)"}),e.jsx("option",{value:"",children:"None"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Z,{label:"Line Ending",value:W,onChange:g=>O(g.target.value),children:[e.jsx("option",{value:"crlf",children:"CRLF (Windows)"}),e.jsx("option",{value:"lf",children:"LF (Unix/Mac)"}),e.jsx("option",{value:"cr",children:"CR (Legacy Mac)"})]}),e.jsxs(Z,{label:"Encoding",value:N,onChange:g=>p(g.target.value),children:[e.jsx("option",{value:"utf-8",children:"UTF-8"}),e.jsx("option",{value:"utf-8-sig",children:"UTF-8 with BOM"}),e.jsx("option",{value:"ascii",children:"ASCII"})]})]})]})]}),E&&e.jsx("div",{className:`p-3 rounded text-xs ${E.ok?"bg-green-900/30 border border-green-800 text-green-300":"bg-red-900/30 border border-red-800 text-red-300"}`,children:E.ok?e.jsxs(e.Fragment,{children:["Imported ",E.rows_imported," rows via ",E.method==="load_data"?"LOAD DATA":"batch insert",".",E.warnings&&E.warnings.length>0&&e.jsxs("ul",{className:"mt-1 list-disc list-inside text-yellow-400",children:[E.warnings.slice(0,5).map((g,K)=>e.jsx("li",{children:g},K)),E.warnings.length>5&&e.jsxs("li",{children:["…and ",E.warnings.length-5," more"]})]})]}):e.jsxs(e.Fragment,{children:["Import failed: ",E.error]})})]})})}const bs=Object.freeze(Object.defineProperty({__proto__:null,default:it},Symbol.toStringTag,{value:"Module"}));function vs(t){const a=`lagun-bookmarks-${t}`,[s,n]=i.useState(()=>{try{const l=localStorage.getItem(a);return new Set(l?JSON.parse(l):[])}catch{return new Set}});return{bookmarks:s,toggle:(l,c)=>{const d=`${l}/${c}`;n(u=>{const x=new Set(u);return x.has(d)?x.delete(d):x.add(d),localStorage.setItem(a,JSON.stringify([...x])),x})},isBookmarked:(l,c)=>s.has(`${l}/${c}`)}}function ys({sessionId:t,selectedDatabases:a}){const{databases:s,loadDatabases:n,loadTables:r,tables:o,invalidateSession:l}=me(),{openTableTab:c,openQueryTab:d}=te(),[u,x]=i.useState(new Set),[f,j]=i.useState(""),[v,S]=i.useState(!1),[h,b]=i.useState(null),[k,y]=i.useState(null),{bookmarks:R,toggle:F,isBookmarked:M}=vs(t);i.useEffect(()=>{n(t)},[t,n]),i.useEffect(()=>{S(!1),j("")},[t]);const W=()=>{l(t),n(t),x(new Set),j("")},O=w=>{j(w),w&&D.forEach(_=>{x(P=>new Set([...P,_])),o[`${t}/${_}`]||r(t,_)})},N=async w=>{const _=new Set(u);_.has(w)?_.delete(w):(_.add(w),await r(t,w)),x(_)},p=()=>{const w=!v;S(w),w&&D.forEach(_=>{[...R].some(E=>E.startsWith(`${_}/`))&&(x(E=>new Set([...E,_])),o[`${t}/${_}`]||r(t,_))})},T=s[t]??[],D=a&&a.length>0?T.filter(w=>a.includes(w)):T,I=f.toLowerCase(),U=D.map(w=>{let P=o[`${t}/${w}`]??[];return v&&(P=P.filter(E=>M(w,E.name))),I&&(P=P.filter(E=>E.name.toLowerCase().includes(I))),{db:w,tbls:P}}).filter(({db:w,tbls:_})=>v?_.length>0:!I||_.length>0||w.toLowerCase().includes(I)),m=(w,_,P)=>{w.preventDefault(),w.stopPropagation(),b({x:w.clientX,y:w.clientY,db:_,table:P})},$=()=>b(null),Q=async(w,_)=>{if(!confirm(`Drop table ${w}.${_}? This cannot be undone.`))return;await A.dropTable(t,w,_);const P=`${t}/${w}`;me.setState(E=>({tables:{...E.tables,[P]:(E.tables[P]??[]).filter(G=>G.name!==_)}})),$()},J=async(w,_)=>{confirm(`Truncate table ${w}.${_}? All rows will be deleted.`)&&(await A.truncateTable(t,w,_),$())},H=v&&R.size===0;return e.jsxs("div",{className:"py-1",onClick:$,children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[e.jsx("span",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide",children:"Databases"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:p,title:v?"Show all tables":"Show bookmarks only",className:`p-0.5 transition-colors ${v?"text-yellow-400":"text-slate-500 hover:text-slate-300"}`,children:e.jsx(Te,{size:10,fill:v?"currentColor":"none"})}),e.jsx("button",{onClick:W,className:"p-0.5 text-slate-500 hover:text-slate-300 transition-colors",children:e.jsx(je,{size:10})})]})]}),e.jsx("div",{className:"px-2 pb-1",children:e.jsxs("div",{className:"flex items-center gap-1.5 bg-surface-800 rounded px-2 py-1",children:[e.jsx(Ze,{size:10,className:"text-slate-500 flex-shrink-0"}),e.jsx("input",{type:"text",value:f,onChange:w=>O(w.target.value),placeholder:v?"Filter bookmarks…":"Filter tables…",className:"bg-transparent text-xs text-slate-300 placeholder-slate-600 flex-1 outline-none min-w-0"}),f&&e.jsx("button",{onClick:()=>j(""),className:"text-slate-500 hover:text-slate-300",children:e.jsx(we,{size:10})})]})}),H?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-center",children:[e.jsx(Te,{size:18,className:"text-slate-700"}),e.jsxs("p",{className:"text-xs text-slate-600",children:["No bookmarks yet.",e.jsx("br",{}),"Hover a table and click ★ to add one."]})]}):U.map(({db:w,tbls:_})=>{const P=u.has(w);return e.jsxs("div",{children:[e.jsxs("button",{className:"flex items-center gap-1.5 w-full px-2 py-1 hover:bg-surface-800 text-slate-300 group",onClick:()=>N(w),onContextMenu:E=>m(E,w),children:[P?e.jsx(Re,{size:12,className:"flex-shrink-0"}):e.jsx(Xe,{size:12,className:"flex-shrink-0"}),e.jsx(Ye,{size:12,className:"flex-shrink-0 text-yellow-400"}),e.jsx("span",{className:"text-xs truncate flex-1 text-left",children:w}),e.jsx("span",{role:"button",title:"New query on this database",onClick:E=>{E.stopPropagation(),d(t,w)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:text-brand-400",children:e.jsx(re,{size:10})})]}),P&&_.map(E=>{const G=M(w,E.name);return e.jsxs("button",{className:"flex items-center gap-1.5 w-full pl-7 pr-2 py-0.5 hover:bg-surface-800 text-slate-400 hover:text-slate-200 group",onClick:()=>c(t,w,E.name),onContextMenu:X=>m(X,w,E.name),children:[e.jsx(Pe,{size:11,className:"flex-shrink-0 text-slate-500"}),e.jsx("span",{className:"text-xs truncate flex-1 text-left",children:E.name}),e.jsx("span",{role:"button",title:G?"Remove bookmark":"Bookmark table",onClick:X=>{X.stopPropagation(),F(w,E.name)},className:`p-0.5 transition-colors ${G?"text-yellow-400":"opacity-0 group-hover:opacity-100 text-slate-500 hover:text-yellow-400"}`,children:e.jsx(Te,{size:10,fill:G?"currentColor":"none"})})]},E.name)})]},w)}),h&&e.jsx("div",{className:"fixed bg-surface-800 border border-surface-700 rounded shadow-lg z-50 py-1 w-44",style:{top:h.y,left:h.x},onClick:w=>w.stopPropagation(),children:h.table?e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-surface-700 text-slate-200",onClick:()=>{c(t,h.db,h.table),$()},children:[e.jsx(Pe,{size:12})," Open Table"]}),e.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-surface-700 text-slate-200",onClick:()=>{d(t,h.db),$()},children:[e.jsx(re,{size:12})," New Query"]}),e.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-surface-700 text-slate-200",onClick:()=>{y({db:h.db,table:h.table}),$()},children:[e.jsx(ne,{size:12})," Import CSV"]}),e.jsx("hr",{className:"border-surface-700 my-1"}),e.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-surface-700 text-yellow-400",onClick:()=>J(h.db,h.table),children:[e.jsx(Nt,{size:12})," Truncate"]}),e.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-surface-700 text-red-400",onClick:()=>Q(h.db,h.table),children:[e.jsx(Ie,{size:12})," Drop Table"]})]}):e.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-surface-700 text-slate-200",onClick:()=>{d(t,h.db),$()},children:[e.jsx(re,{size:12})," New Query"]})}),k&&e.jsx(it,{open:!!k,onClose:()=>y(null),sessionId:t,database:k.db,table:k.table})]})}const js={sm:"w-7 h-7",md:"w-9 h-9",lg:"w-14 h-14"},ws={sm:"text-sm",md:"text-base",lg:"text-xl"};function ct({size:t="md",showText:a=!0,className:s=""}){return e.jsxs("div",{className:`flex items-center gap-2 ${s}`,children:[e.jsxs("svg",{viewBox:"0 0 128 128",xmlns:"http://www.w3.org/2000/svg",className:`${js[t]} flex-shrink-0`,children:[e.jsx("rect",{x:"4",y:"4",width:"120",height:"120",rx:"24",fill:"#f0f9ff"}),e.jsxs("g",{fill:"none",stroke:"#2563eb",strokeWidth:"3",strokeLinecap:"round",children:[e.jsx("path",{d:"M 28 34 Q 38 26 48 34 T 68 34 T 88 34 T 100 34"}),e.jsx("path",{d:"M 28 50 Q 38 42 48 50 T 68 50 T 88 50 T 100 50"}),e.jsx("path",{d:"M 28 66 Q 38 58 48 66 T 68 66 T 88 66 T 100 66"})]}),e.jsxs("g",{fill:"none",stroke:"#0891b2",strokeWidth:"2.5",strokeLinecap:"round",children:[e.jsx("line",{x1:"28",y1:"82",x2:"100",y2:"82"}),e.jsx("line",{x1:"28",y1:"94",x2:"100",y2:"94"}),e.jsx("line",{x1:"52",y1:"82",x2:"52",y2:"94"}),e.jsx("line",{x1:"76",y1:"82",x2:"76",y2:"94"})]}),e.jsx("circle",{cx:"64",cy:"74",r:"3",fill:"#0284c7"})]}),a&&e.jsx("span",{className:`font-semibold text-slate-100 ${ws[t]} tracking-tight`,children:"Lagun"})]})}function Ss(){const{sessions:t,activeSessionId:a}=ee(),[s,n]=i.useState(!1),[r,o]=i.useState(!1),[l,c]=i.useState(!1);return e.jsxs("aside",{className:"w-64 flex-shrink-0 bg-surface-900 border-r border-surface-800 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-3 border-b border-surface-800",children:[e.jsx(ct,{size:"sm",showText:!0}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(!0),title:"Import connections",className:"p-1",children:e.jsx(ne,{size:14})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>o(!0),title:"Export connections",className:"p-1",children:e.jsx(Se,{size:14})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>n(!0),title:"New connection",className:"p-1",children:e.jsx(Ct,{size:14})})]})]}),e.jsx("div",{className:"flex-shrink-0 border-b border-surface-800",children:e.jsx(hs,{onNew:()=>n(!0)})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:a&&(()=>{const d=t.find(u=>u.id===a);return e.jsx(ys,{sessionId:a,selectedDatabases:d==null?void 0:d.selected_databases})})()}),e.jsx(lt,{open:s,onClose:()=>n(!1)}),e.jsx(ps,{open:r,onClose:()=>o(!1)}),e.jsx(gs,{open:l,onClose:()=>c(!1)})]})}function Ns(){const{tabs:t,activeTabId:a,setActiveTab:s,closeTab:n}=te();return t.length===0?null:e.jsx("div",{className:"flex items-center bg-surface-900 border-b border-surface-800 overflow-x-auto flex-shrink-0",children:t.map(r=>e.jsxs("button",{onClick:()=>s(r.id),className:fe("flex items-center gap-1.5 px-3 py-2 text-xs border-r border-surface-800 whitespace-nowrap min-w-0 group transition-colors",a===r.id?"bg-surface-950 text-slate-100 border-t-2 border-t-brand-500":"text-slate-400 hover:text-slate-200 hover:bg-surface-800"),children:[r.type==="query"?e.jsx(re,{size:12,className:"flex-shrink-0"}):e.jsx(kt,{size:12,className:"flex-shrink-0"}),e.jsx("span",{className:"truncate max-w-[120px]",children:r.label}),e.jsx("span",{role:"button",onClick:o=>{o.stopPropagation(),n(r.id)},className:"ml-0.5 opacity-0 group-hover:opacity-100 hover:text-red-400 transition-opacity",children:e.jsx(we,{size:10})})]},r.id))})}const Cs="modulepreload",ks=function(t){return"/"+t},Qe={},Le=function(a,s,n){let r=Promise.resolve();if(s&&s.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));r=Promise.allSettled(s.map(d=>{if(d=ks(d),d in Qe)return;Qe[d]=!0;const u=d.endsWith(".css"),x=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${x}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":Cs,u||(f.as="script"),f.crossOrigin="",f.href=d,c&&f.setAttribute("nonce",c),document.head.appendChild(f),u)return new Promise((j,v)=>{f.addEventListener("load",j),f.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return a().catch(o)})};function Es(){var t;return((t=crypto.randomUUID)==null?void 0:t.call(crypto))??"10000000-1000-4000-8000-100000000000".replace(/[018]/g,a=>(+a^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+a/4).toString(16))}const Oe=Ce()(ze(t=>({entries:[],addEntry:a=>t(s=>({entries:[{...a,id:Es(),timestamp:new Date().toISOString()},...s.entries].slice(0,200)})),clearLog:()=>t({entries:[]})}),{name:"lagun-query-log",version:1,partialize:t=>({entries:t.entries})})),Ts=[100,500,1e3,5e3,1e4];function $s({value:t,onChange:a,onRun:s,running:n,database:r,schema:o,limit:l,onLimitChange:c}){const d=f=>{(f.ctrlKey||f.metaKey)&&f.key==="Enter"&&(f.preventDefault(),n||s())},u=i.useRef(o??{});u.current=o??{};const x=i.useMemo(()=>[We({dialect:ue,defaultSchema:r}),ue.language.data.of({autocomplete:f=>pt({dialect:ue,schema:u.current,defaultSchema:r})(f)})],[r]);return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-900 border-b border-surface-800",children:[e.jsx("div",{className:"flex items-center gap-2",children:r&&e.jsx("span",{className:"text-xs text-slate-500 bg-surface-800 px-2 py-0.5 rounded",children:r})}),e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-slate-500",children:[e.jsx("span",{children:"Limit"}),e.jsx("select",{value:l,onChange:f=>c(Number(f.target.value)),className:"bg-surface-800 border border-surface-700 rounded px-1.5 py-0.5 text-xs text-slate-300 focus:outline-none focus:ring-1 focus:ring-brand-500",children:Ts.map(f=>e.jsx("option",{value:f,children:f.toLocaleString()},f))})]}),e.jsx("kbd",{className:"hidden sm:inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono text-slate-500 bg-surface-800 border border-surface-700 rounded",children:"Ctrl+↵"}),e.jsxs(B,{variant:"primary",size:"sm",onClick:s,disabled:n||!t.trim(),title:"Run (Ctrl+Enter)",children:[n?e.jsx(ae,{size:12,className:"animate-spin"}):e.jsx(Et,{size:12}),"Run"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden",onKeyDown:d,children:e.jsx(Je,{value:t,onChange:a,extensions:[x],theme:Ve,className:"h-full text-sm",style:{height:"100%"},basicSetup:{lineNumbers:!0,highlightActiveLine:!0,autocompletion:!0,foldGutter:!0}})})]})}function _s({x:t,y:a,items:s,onClose:n}){const r=i.useRef(null),[o,l]=i.useState({left:t,top:a});return i.useLayoutEffect(()=>{if(!r.current)return;const{width:c,height:d}=r.current.getBoundingClientRect();l({left:Math.min(t,window.innerWidth-c-8),top:Math.min(a,window.innerHeight-d-8)})},[t,a]),i.useEffect(()=>{const c=u=>{u.key==="Escape"&&n()},d=u=>{r.current&&!r.current.contains(u.target)&&n()};return window.addEventListener("keydown",c),window.addEventListener("mousedown",d),()=>{window.removeEventListener("keydown",c),window.removeEventListener("mousedown",d)}},[n]),tt.createPortal(e.jsx("div",{ref:r,className:"fixed z-[9999] bg-surface-900 border border-surface-700 rounded-md shadow-2xl py-1 min-w-[180px]",style:{left:o.left,top:o.top},onContextMenu:c=>c.preventDefault(),children:s.map((c,d)=>c.type==="separator"?e.jsx("div",{className:"border-t border-surface-700 my-1"},d):e.jsxs("button",{className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left ${c.danger?"text-red-400 hover:bg-red-950/40":"text-slate-300 hover:bg-surface-800"}`,onClick:c.onClick,children:[c.icon,c.label]},d))}),document.body)}async function He(t){if(navigator.clipboard){await navigator.clipboard.writeText(t);return}const a=document.createElement("textarea");a.value=t,a.style.position="fixed",a.style.opacity="0",document.body.appendChild(a),a.focus(),a.select();const s=document.execCommand("copy");if(document.body.removeChild(a),!s)throw new Error("Copy failed")}const Ds=Lt.withParams({backgroundColor:"#0f172a",foregroundColor:"#cbd5e1",headerBackgroundColor:"#1e293b",headerTextColor:"#94a3b8",borderColor:"#1e293b",rowHoverColor:"#1e293b",selectedRowBackgroundColor:"#1e3a5f",oddRowBackgroundColor:"#0f172a",fontFamily:"ui-monospace, monospace",fontSize:12,cellTextColor:"#cbd5e1",headerFontSize:12,headerFontWeight:600}),Is=new Set(["datetime","timestamp","date","time"]);function Rs(t){const a=o=>String(o).padStart(2,"0"),s=new Date,n=`${s.getFullYear()}-${a(s.getMonth()+1)}-${a(s.getDate())}`,r=`${a(s.getHours())}:${a(s.getMinutes())}:${a(s.getSeconds())}`;return t==="date"?n:t==="time"?r:`${n} ${r}`}const dt=i.forwardRef(function({result:a,onCellEdit:s,primaryKeyColumns:n=[],editable:r=!1,selectable:o,onSelectionChange:l,columns:c,onDeleteRows:d},u){const[x,f]=i.useState(null),j=i.useRef(null),v=i.useRef(null);i.useImperativeHandle(u,()=>({isAnyFilterPresent:()=>{var p;return((p=v.current)==null?void 0:p.isAnyFilterPresent())??!1},getFilteredData:()=>{var T;const p=[];return(T=v.current)==null||T.forEachNodeAfterFilterAndSort(D=>{D.data&&p.push(a.columns.map(I=>D.data[I]??null))}),{columns:a.columns,rows:p}}}));const S=i.useMemo(()=>a.columns.map(p=>({field:p,headerName:p,editable:r&&p!=="__rowIndex",resizable:!0,sortable:!0,filter:!0,cellStyle:{fontFamily:"ui-monospace, monospace",fontSize:"12px"},headerClass:"text-xs font-semibold"})),[a.columns,r]),h=i.useMemo(()=>a.rows.map((p,T)=>{const D={__ag_rowId:String(T)};return a.columns.forEach((I,U)=>{D[I]=p[U]}),D}),[a.rows,a.columns]),b=i.useCallback(p=>p.data.__ag_rowId,[]),k=i.useMemo(()=>o?{mode:"multiRow",checkboxes:!0,headerCheckbox:!0,enableClickSelection:!1}:void 0,[o]),y=i.useMemo(()=>({minWidth:80,flex:1}),[]),R=i.useCallback(p=>{!s||!p.colDef.field||s({column:p.colDef.field,newValue:p.newValue,data:p.data})},[s]),F=i.useCallback(p=>{l==null||l(p.api.getSelectedRows())},[l]),M=i.useCallback(p=>{const T=p.event;if(!(T!=null&&T.shiftKey)){j.current=p.rowIndex??null;return}const D=p.rowIndex??0,I=j.current??D,U=Math.min(I,D),m=Math.max(I,D);p.api.deselectAll(),p.api.forEachNode($=>{$.rowIndex!==null&&$.rowIndex>=U&&$.rowIndex<=m&&$.setSelected(!0)})},[]),W=i.useCallback(p=>{const T=p.event;if(!T)return;T.preventDefault();const D=p.api.getSelectedRows();f({x:T.clientX,y:T.clientY,columnName:p.colDef.field??"",cellValue:p.value,rowData:p.data??{},selectedRows:D})},[]),O=i.useCallback(()=>f(null),[]),N=i.useMemo(()=>{if(!x)return[];const p=c==null?void 0:c.find($=>$.name===x.columnName),T=p&&Is.has(p.data_type.toLowerCase()),D=x.selectedRows.length>0?x.selectedRows:[x.rowData],{__ag_rowId:I,...U}=x.rowData,m=[{type:"item",label:"Copy cell",icon:e.jsx($t,{size:12}),onClick:()=>{He(String(x.cellValue??"")).catch(()=>{}),O()}},{type:"item",label:"Copy row as JSON",icon:e.jsx(_t,{size:12}),onClick:()=>{He(JSON.stringify(U,null,2)).catch(()=>{}),O()}}];if(r&&(p!=null&&p.is_nullable&&(m.push({type:"separator"}),m.push({type:"item",label:"Set to NULL",icon:e.jsx(Tt,{size:12}),onClick:()=>{s==null||s({column:x.columnName,newValue:null,data:x.rowData}),O()}})),T)){const $=Rs(p.data_type.toLowerCase());m.push({type:"item",label:`Set to NOW()  ${$}`,icon:e.jsx(et,{size:12}),onClick:()=>{s==null||s({column:x.columnName,newValue:$,data:x.rowData}),O()}})}if(d&&n.length>0){const $=D.length>1?`Delete ${D.length} rows`:"Delete row";m.push({type:"separator"}),m.push({type:"item",label:$,danger:!0,icon:e.jsx(Ie,{size:12}),onClick:()=>{d(D),O()}})}return m},[x,c,r,s,d,n,O]);return a.error?e.jsx("div",{className:"p-4 bg-red-950/50 border border-red-800 rounded m-3",children:e.jsx("p",{className:"text-xs font-mono text-red-300",children:a.error})}):e.jsxs("div",{className:"h-full",children:[e.jsx(Ot,{theme:Ds,columnDefs:S,rowData:h,getRowId:b,onGridReady:p=>{v.current=p.api},onCellValueChanged:R,onSelectionChanged:F,onRowClicked:o?M:void 0,onCellContextMenu:W,onBodyScroll:O,defaultColDef:y,rowSelection:k,suppressContextMenu:!0,preventDefaultOnContextMenu:!0,singleClickEdit:!0,stopEditingWhenCellsLoseFocus:!0}),x&&e.jsx(_s,{x:x.x,y:x.y,items:N,onClose:O})]})});function ut({result:t,running:a}){return a?e.jsx("div",{className:"flex items-center gap-3 px-3 py-1.5 bg-surface-900 border-t border-surface-800 text-xs text-slate-400",children:e.jsx("span",{className:"animate-pulse",children:"Executing..."})}):t?e.jsx("div",{className:"flex items-center gap-4 px-3 py-1.5 bg-surface-900 border-t border-surface-800 text-xs",children:t.error?e.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[e.jsx(Dt,{size:11})," Error"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1 text-slate-400",children:[e.jsx(It,{size:11}),t.row_count.toLocaleString()," ",t.row_count===1?"row":"rows"]}),t.affected_rows!=null&&e.jsxs("span",{className:"text-slate-400",children:[t.affected_rows," affected"]}),e.jsxs("span",{className:"flex items-center gap-1 text-slate-500",children:[e.jsx(et,{size:11}),t.exec_time_ms,"ms"]}),t.insert_id?e.jsxs("span",{className:"text-slate-500",children:["insert_id=",t.insert_id]}):null]})}):null}const zs=i.lazy(()=>Le(()=>import("./TableSchemaView-1sbDFRYn.js"),__vite__mapDeps([0,1,2,3]))),xt=i.lazy(()=>Le(()=>import("./ExportDialog-AcQ1rtHi.js"),__vite__mapDeps([4,1,2,3]))),Ls=i.lazy(()=>Le(()=>Promise.resolve().then(()=>bs),void 0)),Os=[100,500,1e3,5e3,1e4];function Ps({tab:t}){return t.type==="query"?e.jsx(Fs,{tab:t}):e.jsx(Ms,{tab:t})}function Fs({tab:t}){const a=te(N=>{var p;return((p=N.tabs.find(T=>T.id===t.id))==null?void 0:p.sql)??""}),s=te(N=>N.setSql),[n,r]=i.useState(a),o=i.useRef(n);o.current=n,i.useEffect(()=>{const N=setTimeout(()=>s(t.id,n),500);return()=>clearTimeout(N)},[n,t.id,s]),i.useEffect(()=>()=>{s(t.id,o.current)},[t.id,s]),i.useEffect(()=>{r(a)},[t.id]);const[l,c]=i.useState(null),[d,u]=i.useState(!1),[x,f]=i.useState(1e3),[j,v]=i.useState(!1),[S,h]=i.useState(),b=i.useRef(null),{tables:k,columns:y,loadTables:R,loadColumns:F}=me(),M=Oe(N=>N.addEntry),W=i.useMemo(()=>{if(!t.database)return{};const N=k[`${t.sessionId}/${t.database}`]??[],p={};for(const T of N){const D=`${t.sessionId}/${t.database}/${T.name}`;p[T.name]=(y[D]??[]).map(I=>I.name)}return p},[t.sessionId,t.database,k,y]);i.useEffect(()=>{t.database&&R(t.sessionId,t.database)},[t.sessionId,t.database]),i.useEffect(()=>{if(!t.database)return;const N=setTimeout(()=>{const p=[...n.matchAll(/(?:FROM|JOIN|INTO|UPDATE|TABLE)\s+`?(?:\w+`?\.`?)?(\w+)`?/gi)],T=[...n.matchAll(/,\s*`?(?:\w+`?\.`?)?(\w+)`?\s*(?:AS\s+\w+\s*)?(?:,|WHERE\b|SET\b|ON\b|$)/gi)],D=[...new Set([...p,...T].map(I=>I[1]))];for(const I of D)F(t.sessionId,t.database,I)},300);return()=>clearTimeout(N)},[n,t.sessionId,t.database]);const O=async()=>{if(!n.trim())return;u(!0);const N=Date.now();try{const p=await A.executeQuery(t.sessionId,n,t.database,x);c(p),M({sql:n.trim(),sessionId:t.sessionId,database:t.database,rowCount:p.row_count??void 0,execTimeMs:p.exec_time_ms??Date.now()-N,error:p.error??void 0})}finally{u(!1)}};return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"h-48 flex-shrink-0 border-b border-surface-800",children:e.jsx($s,{value:n,onChange:r,onRun:O,running:d,database:t.database,schema:W,limit:x,onLimitChange:f})}),e.jsx("div",{className:"flex-1 overflow-hidden",children:l?e.jsx(dt,{ref:b,result:l}):e.jsx("div",{className:"flex items-center justify-center h-full text-slate-600 text-sm",children:"Press Ctrl+Enter to run a query"})}),e.jsxs("div",{className:"flex items-center border-t border-surface-800",children:[e.jsx("div",{className:"flex-1",children:e.jsx(ut,{result:l,running:d})}),l&&!l.error&&l.columns.length>0&&e.jsxs("button",{onClick:()=>{var N;h((N=b.current)!=null&&N.isAnyFilterPresent()?b.current.getFilteredData():void 0),v(!0)},className:"flex items-center gap-1 px-3 py-1.5 text-xs text-slate-500 hover:text-slate-300 transition-colors",title:"Export result",children:[e.jsx(Se,{size:11})," Export"]})]}),j&&t.database&&n.trim()&&e.jsx(i.Suspense,{fallback:null,children:e.jsx(xt,{open:j,onClose:()=>v(!1),sessionId:t.sessionId,database:t.database,table:"result",sql:n.trim(),rowsOverride:S})})]})}function Ms({tab:t}){const[a,s]=i.useState("schema"),[n,r]=i.useState(null),[o,l]=i.useState([]),[c,d]=i.useState(!1),[u,x]=i.useState(!1),[f,j]=i.useState(1e3),[v,S]=i.useState(null),[h,b]=i.useState([]),[k,y]=i.useState(!1),[R,F]=i.useState(),M=i.useRef(null),[W,O]=i.useState(!1),[N,p]=i.useState(""),[T,D]=i.useState(""),[I,U]=i.useState(""),[m,$]=i.useState(!1),Q=Oe(C=>C.addEntry),J=o.filter(C=>C.is_primary_key).map(C=>C.name),H=async(C,q,L)=>{if(!t.database||!t.table)return;const V=C??f,g=q!==void 0?q:N,K=L!==void 0?L:I;b([]),n===null?d(!0):x(!0);const se=Date.now();try{const de=await A.getColumns(t.sessionId,t.database,t.table);l(de);let Ee=`SELECT * FROM \`${t.database}\`.\`${t.table}\``;const pe=[];if(g.trim()&&de.length>0){const mt=g.replace(/\\/g,"\\\\").replace(/'/g,"''").replace(/%/g,"\\%").replace(/_/g,"\\_"),ft=de.map(ht=>`\`${ht.name}\` LIKE '%${mt}%'`);pe.push(`(${ft.join(" OR ")})`)}K.trim()&&pe.push(`(${K.trim()})`),pe.length>0&&(Ee+=` WHERE ${pe.join(" AND ")}`);const ge=await A.executeQuery(t.sessionId,Ee,void 0,V);r(ge),Q({sql:Ee,sessionId:t.sessionId,database:t.database,rowCount:ge.row_count??void 0,execTimeMs:ge.exec_time_ms??Date.now()-se,error:ge.error??void 0})}finally{d(!1),x(!1)}};i.useEffect(()=>{a==="data"&&!n&&H()},[a]),i.useEffect(()=>{s("schema"),r(null),l([]),p(""),D(""),U(""),$(!1)},[t.sessionId,t.database,t.table]),i.useEffect(()=>{if(a!=="data")return;const C=setTimeout(()=>{H(void 0,N,I)},400);return()=>clearTimeout(C)},[N]);const w=async C=>{if(!t.database||!t.table||J.length===0)return;const q={};J.forEach(g=>{q[g]=C.data[g]});const L=Date.now(),V=await A.cellUpdate(t.sessionId,{database:t.database,table:t.table,primary_key:q,column:C.column,new_value:C.newValue});V.ok?(S(`✓ ${V.sql_executed}`),Q({sql:V.sql_executed,sessionId:t.sessionId,database:t.database,affectedRows:V.affected_rows??void 0,execTimeMs:Date.now()-L}),H()):(S(`✗ ${V.error}`),Q({sql:V.sql_executed||`UPDATE ${t.database}.${t.table}`,sessionId:t.sessionId,database:t.database,execTimeMs:Date.now()-L,error:V.error??void 0})),setTimeout(()=>S(null),4e3)},_=async C=>{if(!t.database||!t.table||J.length===0)return;const q=C.map(V=>Object.fromEntries(J.map(g=>[g,V[g]]))),L=await A.rowDelete(t.sessionId,{database:t.database,table:t.table,primary_keys:q});L.ok?(S(`✓ Deleted ${L.affected_rows} row${L.affected_rows!==1?"s":""}`),Q({sql:`DELETE FROM \`${t.database}\`.\`${t.table}\` (${L.affected_rows} row${L.affected_rows!==1?"s":""})`,sessionId:t.sessionId,database:t.database,affectedRows:L.affected_rows,execTimeMs:0}),H()):S(`✗ ${L.error}`),setTimeout(()=>S(null),4e3)},P=C=>{j(C),n&&H(C)},E=i.useCallback(()=>{U(T),H(void 0,N,T)},[T,N]),G=()=>{D(""),U(""),H(void 0,N,"")},X=()=>{p("")},le=i.useRef(E);le.current=E;const he=i.useMemo(()=>We({dialect:ue}),[]),ie=i.useMemo(()=>{const C=o.map(q=>({label:q.name,type:"property",boost:99}));return ue.language.data.of({autocomplete:q=>{const L=q.matchBefore(/\w+/);return!L&&!q.explicit?null:{from:L?L.from:q.pos,options:C,validFor:/^\w*$/}}})},[o]),ce=i.useMemo(()=>gt.highest(bt.of([{key:"Enter",run:()=>(le.current(),!0)},{key:"Mod-Enter",run:()=>(le.current(),!0)}])),[]);return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-surface-900 border-b border-surface-800",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:[t.database,".",t.table]}),e.jsx("div",{className:"flex-1"}),a==="data"&&e.jsxs("div",{className:"relative flex items-center",children:[e.jsx(Ze,{size:11,className:"absolute left-2 text-slate-500 pointer-events-none"}),e.jsx("input",{type:"text",value:N,onChange:C=>p(C.target.value),placeholder:"Search all columns…",className:"bg-surface-800 border border-surface-700 rounded pl-6 pr-6 py-0.5 text-xs text-slate-300 placeholder-slate-600 focus:outline-none focus:ring-1 focus:ring-brand-500 w-44"}),N&&e.jsx("button",{onClick:X,className:"absolute right-1.5 text-slate-500 hover:text-slate-300",children:e.jsx(we,{size:10})})]}),a==="data"&&e.jsxs("button",{onClick:()=>$(C=>!C),className:`flex items-center gap-1 px-2 py-0.5 text-xs rounded transition-colors ${m||I?"text-brand-400 bg-brand-950 border border-brand-800":"text-slate-500 hover:text-slate-300"}`,title:"Toggle WHERE filter",children:[e.jsx(Rt,{size:11}),I?"Filtered":"Filter"]}),a==="data"&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-slate-500",children:[e.jsx("span",{children:"Limit"}),e.jsx("select",{value:f,onChange:C=>P(Number(C.target.value)),className:"bg-surface-800 border border-surface-700 rounded px-1.5 py-0.5 text-xs text-slate-300 focus:outline-none focus:ring-1 focus:ring-brand-500",children:Os.map(C=>e.jsx("option",{value:C,children:C.toLocaleString()},C))})]}),a==="data"&&u&&e.jsx(je,{size:12,className:"animate-spin text-slate-400"}),e.jsxs("div",{className:"flex rounded overflow-hidden border border-surface-700",children:[e.jsx("button",{className:`px-2.5 py-0.5 text-xs transition-colors ${a==="schema"?"bg-brand-600 text-white":"bg-surface-800 text-slate-400 hover:text-slate-200"}`,onClick:()=>s("schema"),children:"Schema"}),e.jsx("button",{className:`px-2.5 py-0.5 text-xs transition-colors ${a==="data"?"bg-brand-600 text-white":"bg-surface-800 text-slate-400 hover:text-slate-200"}`,onClick:()=>s("data"),children:"Data"})]}),a==="data"&&e.jsxs("button",{onClick:()=>O(!0),className:"flex items-center gap-1 px-2 py-0.5 text-xs text-slate-500 hover:text-slate-300 transition-colors",title:"Import data",children:[e.jsx(ne,{size:11})," Import"]}),a==="data"&&n&&!n.error&&e.jsxs("button",{onClick:()=>{var C;h.length===0&&((C=M.current)!=null&&C.isAnyFilterPresent())?F(M.current.getFilteredData()):F(void 0),y(!0)},className:"flex items-center gap-1 px-2 py-0.5 text-xs text-slate-500 hover:text-slate-300 transition-colors",title:"Export data",children:[e.jsx(Se,{size:11})," Export"]}),a==="data"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>H(),title:"Refresh",disabled:c||u,children:e.jsx(je,{size:12,className:c||u?"animate-spin":""})})]}),a==="data"&&m&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-surface-900 border-b border-surface-700",children:[e.jsx("span",{className:"text-xs text-slate-500 font-mono shrink-0",children:"WHERE"}),e.jsx("div",{className:"flex-1 rounded overflow-hidden border border-surface-700 focus-within:ring-1 focus-within:ring-brand-500",children:e.jsx(Je,{value:T,onChange:C=>{D(C),!C.trim()&&I&&(U(""),H(void 0,N,""))},extensions:[he,ie,ce],theme:Ve,height:"28px",placeholder:"e.g. id = 5 AND name LIKE 'John%'",basicSetup:{lineNumbers:!1,foldGutter:!1,highlightActiveLine:!1,autocompletion:!0}})}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("kbd",{className:"hidden sm:inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono text-slate-500 bg-surface-800 border border-surface-700 rounded",children:"Ctrl+↵"}),e.jsx("button",{onClick:E,className:"px-2.5 py-0.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded transition-colors",children:"Apply"})]}),I&&e.jsx("button",{onClick:G,className:"px-2 py-0.5 text-xs text-slate-500 hover:text-slate-300 transition-colors shrink-0",children:"Clear"})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:a==="schema"&&t.database&&t.table?e.jsx(i.Suspense,{fallback:e.jsx("div",{className:"flex items-center justify-center h-full text-slate-500 text-sm",children:"Loading schema…"}),children:e.jsx(zs,{sessionId:t.sessionId,database:t.database,table:t.table})}):a==="data"?c?e.jsxs("div",{className:"flex items-center justify-center h-full text-slate-500 text-sm",children:["Loading ",t.table,"…"]}):n?e.jsx(dt,{ref:M,result:n,editable:J.length>0,primaryKeyColumns:J,onCellEdit:w,onDeleteRows:_,selectable:!0,onSelectionChange:b,columns:o}):e.jsx("div",{className:"flex items-center justify-center h-full text-slate-600 text-sm",children:"No data loaded"}):null}),v&&e.jsx("div",{className:"px-3 py-1.5 bg-surface-900 border-t border-surface-800",children:e.jsx("p",{className:"text-xs font-mono text-slate-400 truncate",children:v})}),a==="data"&&n&&e.jsx(ut,{result:n,running:!1}),k&&t.database&&t.table&&e.jsx(i.Suspense,{fallback:null,children:e.jsx(xt,{open:k,onClose:()=>y(!1),sessionId:t.sessionId,database:t.database,table:t.table,pkValues:h.length>0?h.map(C=>{const q=J.length>0?J:o.map(L=>L.name);return Object.fromEntries(q.map(L=>[L,C[L]]))}):void 0,rowsOverride:R,pkColumnsForSql:J})}),W&&t.database&&e.jsx(i.Suspense,{fallback:null,children:e.jsx(Ls,{open:W,onClose:()=>O(!1),sessionId:t.sessionId,database:t.database,table:t.table,onImportComplete:()=>H()})})]})}function As(t){const a=new Date(t),s=String(a.getHours()).padStart(2,"0"),n=String(a.getMinutes()).padStart(2,"0"),r=String(a.getSeconds()).padStart(2,"0");return`${s}:${n}:${r}`}function qs(t){return t.affectedRows!=null?`${t.affectedRows} affected`:t.rowCount!=null?`${t.rowCount} rows`:"—"}function Bs(){const[t,a]=i.useState(!1),{entries:s,clearLog:n}=Oe();return e.jsxs("div",{className:"flex-shrink-0 border-t border-surface-800 bg-surface-950",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 h-7 cursor-pointer select-none",onClick:()=>a(r=>!r),children:[e.jsx(re,{size:12,className:"text-slate-500"}),e.jsx("span",{className:"text-xs text-slate-400 font-medium",children:"Query Log"}),s.length>0&&e.jsx("span",{className:"text-xs bg-surface-800 text-slate-400 rounded px-1 py-0.5 leading-none",children:s.length}),e.jsx("div",{className:"flex-1"}),t&&s.length>0&&e.jsx("button",{onClick:r=>{r.stopPropagation(),n()},className:"text-xs text-slate-500 hover:text-slate-300 transition-colors px-1",children:"Clear"}),t?e.jsx(Re,{size:12,className:"text-slate-500"}):e.jsx(zt,{size:12,className:"text-slate-500"})]}),t&&e.jsx("div",{className:"h-[180px] overflow-y-auto",children:s.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-slate-600 text-xs",children:"No queries logged yet"}):e.jsxs("table",{className:"w-full text-xs border-collapse",children:[e.jsx("thead",{className:"sticky top-0 bg-surface-900",children:e.jsxs("tr",{className:"text-slate-500",children:[e.jsx("th",{className:"text-left px-2 py-1 font-medium w-16",children:"Time"}),e.jsx("th",{className:"text-left px-2 py-1 font-medium",children:"SQL"}),e.jsx("th",{className:"text-left px-2 py-1 font-medium w-24",children:"Rows"}),e.jsx("th",{className:"text-left px-2 py-1 font-medium w-16",children:"ms"}),e.jsx("th",{className:"text-left px-2 py-1 font-medium w-12",children:"Status"})]})}),e.jsx("tbody",{children:s.map(r=>e.jsxs("tr",{className:`border-t border-surface-800 ${r.error?"bg-red-950/30":""}`,children:[e.jsx("td",{className:"px-2 py-0.5 text-slate-500 tabular-nums",children:As(r.timestamp)}),e.jsx("td",{className:"px-2 py-0.5 font-mono text-slate-300 max-w-0 w-full truncate",title:r.sql,children:r.sql.length>80?r.sql.slice(0,80)+"…":r.sql}),e.jsx("td",{className:"px-2 py-0.5 text-slate-400 tabular-nums",children:qs(r)}),e.jsx("td",{className:"px-2 py-0.5 text-slate-400 tabular-nums",children:r.execTimeMs}),e.jsx("td",{className:"px-2 py-0.5",children:r.error?e.jsx("span",{className:"text-red-400",title:r.error,children:"✗"}):e.jsx("span",{className:"text-green-400",children:"✓"})})]},r.id))})]})})]})}function Us(){const{tabs:t,activeTabId:a}=te();return e.jsxs("div",{className:"flex h-screen overflow-hidden bg-surface-950 text-slate-100",children:[e.jsx(Ss,{}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-0 overflow-hidden",children:[e.jsx(Ns,{}),e.jsx("div",{className:"flex-1 overflow-hidden",children:t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-slate-500 gap-4",children:[e.jsx(ct,{size:"lg",showText:!1,className:"opacity-40"}),e.jsx("p",{className:"text-sm",children:"Select a table from the sidebar or open a query tab"})]}):t.map(s=>e.jsx("div",{className:`h-full ${a===s.id?"":"hidden"}`,children:e.jsx(Ps,{tab:s})},s.id))}),e.jsx(Bs,{})]})]})}function Qs(){const t=ee(a=>a.loadSessions);return i.useEffect(()=>{t().then(()=>{const a=new Set(ee.getState().sessions.map(r=>r.id)),{activeSessionId:s}=ee.getState();s&&!a.has(s)&&ee.getState().setActiveSession(null);const{tabs:n}=te.getState();for(const r of n)a.has(r.sessionId)||te.getState().closeTab(r.id)})},[t]),e.jsx(Us,{})}_e.createRoot(document.getElementById("root")).render(e.jsx(Ke.StrictMode,{children:e.jsx(Qs,{})}));export{B,Y as I,ke as M,Z as S,A as a,He as c,me as u};
