@dotaz/server 0.0.29 → 0.0.30

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/bin/dotaz.js CHANGED
@@ -1,49 +1,49 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var T=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function Y(e){let t=e.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"");return t==="localhost"||t==="::1"||/^127(\.\d{1,3}){3}$/.test(t)}function qt(e,t=process.env){let n=Y(e),r=vr(t.DOTAZ_ALLOWED_HOSTS,(s)=>We(s.toLowerCase()));return{requireLoopbackHost:n,allowedHosts:r}}function Ke(e,t){let n=We(Ft(e));if(t.requireLoopbackHost)return Y(n)||t.allowedHosts.has(n);if(t.allowedHosts.size>0)return t.allowedHosts.has(n);return!0}function K(e,t){if(!Ke(e,t))return{ok:!1,status:403,reason:"Host not allowed"};if(!Tr(e))return{ok:!1,status:403,reason:"Cross-site requests are not allowed"};if(!Ar(e))return{ok:!1,status:403,reason:"Origin not allowed"};return{ok:!0}}function W(e,t){if(t==="json")return Response.json({error:e.reason},{status:e.status});return new Response(e.reason,{status:e.status})}function Tr(e){let t=e.headers.get("sec-fetch-site");return t===null||t==="same-origin"||t==="none"}function Ar(e){let t=e.headers.get("origin");if(t===null)return!0;let n;try{n=new URL(t)}catch{return!1}let r=Ft(e);if(n.host===r)return!0;return Y(n.hostname)&&Y(We(r))}function Ft(e){return(e.headers.get("host")??new URL(e.url).host).trim().toLowerCase()}function We(e){if(e.startsWith("[")){let t=e.indexOf("]");return t===-1?e:e.slice(1,t)}return e.split(":")[0]??e}function vr(e,t){let n=new Set;if(!e)return n;for(let r of e.split(",")){let s=r.trim();if(s)n.add(t(s))}return n}var b,D,Se,R,_;var P=T(()=>{b=class b extends Error{code;constructor(e,t,n){super(t,n);this.name="DatabaseError",this.code=e}};D=class D extends b{constructor(e,t,n){super(e,t,n);this.name="ConnectionError"}};Se=class Se extends b{constructor(e,t){super("AUTH_FAILED",e,t);this.name="AuthenticationError"}};R=class R extends b{constructor(e,t,n){super(e,t,n);this.name="QueryError"}};_=class _ extends b{constructor(e,t,n){super(e,t,n);this.name="ConstraintError"}}});function Bt(){return{type:"response",id:0,success:!1,error:"Invalid JSON"}}async function Qt(e,t){let n=e.id??0,r=t(e.method);if(!r)return{type:"response",id:n,success:!1,error:`Unknown method: ${e.method}`};try{let s=await r(e.params);return{type:"response",id:n,success:!0,payload:s}}catch(s){return{type:"response",id:n,success:!1,error:s instanceof Error?s.message:String(s),errorCode:s instanceof b?s.code:void 0}}}function Yt(e){let t=typeof e==="string"?e:new TextDecoder().decode(e),n;try{n=JSON.parse(t)}catch{return null}if(typeof n!=="object"||n===null||typeof n.method!=="string")return null;let{id:r,method:s,params:i}=n;return{id:r,method:s,params:i}}var Kt=T(()=>{P()});function Wt(e){return`"${e.replace(/"/g,'""')}"`}function F(e){let t=new Set,n=[];for(let r of e)for(let s of Object.keys(r))if(!t.has(s))t.add(s),n.push(s);return n}function Gt(e,t){let n=[...e];for(let r of t??[])if(!n.includes(r))n.push(r);return n}function Rr(e){if(e===null||e===void 0)return"";if(typeof e==="object")return JSON.stringify(e);return String(e)}function Ge(e){if(e===null||e===void 0)return"NULL";if(typeof e==="number")return String(e);if(typeof e==="boolean")return e?"TRUE":"FALSE";if(typeof e==="string")return`'${e.replace(/'/g,"''")}'`;if(typeof e==="object")return`'${JSON.stringify(e).replace(/'/g,"''")}'`;return String(e)}function Nr(e){if(e===null||e===void 0)return"NULL";if(typeof e==="object")return JSON.stringify(e);return String(e)}function jt(e){return e.replace(/\|/g,"\\|").replace(/\n/g," ")}function ze(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function zt(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Dr(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");if(!/^[a-zA-Z_]/.test(t))t="_"+t;return t}function _r(e,t,n){if(!e)return n(t);return`${n(e)}.${n(t)}`}function Vt(e){let t=e.quoteIdentifier??Wt,n=e.qualifiedTableName??_r(e.schema,e.table,t);switch(e.format){case"csv":return new Jt(e.delimiter??",",e.includeHeaders??!0);case"json":return new Xt;case"sql":return new Zt(n,e.batchSize??100,t);case"markdown":return new en;case"sql_update":if(!e.keyColumns||e.keyColumns.length===0)throw Error("SQL UPDATE export requires key columns");return new tn(n,t,e.keyColumns);case"html":return new nn;case"xml":return new rn}}class Jt{delimiter;includeHeaders;columns=null;constructor(e,t){this.delimiter=e;this.includeHeaders=t}preamble(){return""}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let n=this.columns,r=[];if(t&&this.includeHeaders)r.push(n.map((s)=>this.escapeField(s)).join(this.delimiter));for(let s of e){let i=n.map((o)=>this.escapeField(Rr(s[o])));r.push(i.join(this.delimiter))}return r.join(`
3
+ var C=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function G(e){let t=e.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"");return t==="localhost"||t==="::1"||/^127(\.\d{1,3}){3}$/.test(t)}function Xt(e,t=process.env){let n=G(e),r=es(t.DOTAZ_ALLOWED_HOSTS,(s)=>Xe(s.toLowerCase()));return{requireLoopbackHost:n,allowedHosts:r}}function Je(e,t){let n=Xe(Zt(e));if(t.requireLoopbackHost)return G(n)||t.allowedHosts.has(n);if(t.allowedHosts.size>0)return t.allowedHosts.has(n);return!0}function J(e,t){if(!Je(e,t))return{ok:!1,status:403,reason:"Host not allowed"};if(!Xr(e))return{ok:!1,status:403,reason:"Cross-site requests are not allowed"};if(!Zr(e))return{ok:!1,status:403,reason:"Origin not allowed"};return{ok:!0}}function X(e,t){if(t==="json")return Response.json({error:e.reason},{status:e.status});return new Response(e.reason,{status:e.status})}function Xr(e){let t=e.headers.get("sec-fetch-site");return t===null||t==="same-origin"||t==="none"}function Zr(e){let t=e.headers.get("origin");if(t===null)return!0;let n;try{n=new URL(t)}catch{return!1}let r=Zt(e);if(n.host===r)return!0;return G(n.hostname)&&G(Xe(r))}function Zt(e){return(e.headers.get("host")??new URL(e.url).host).trim().toLowerCase()}function Xe(e){if(e.startsWith("[")){let t=e.indexOf("]");return t===-1?e:e.slice(1,t)}return e.split(":")[0]??e}function es(e,t){let n=new Set;if(!e)return n;for(let r of e.split(",")){let s=r.trim();if(s)n.add(t(s))}return n}var b,_,Ce,N,I;var q=C(()=>{b=class b extends Error{code;constructor(e,t,n){super(t,n);this.name="DatabaseError",this.code=e}};_=class _ extends b{constructor(e,t,n){super(e,t,n);this.name="ConnectionError"}};Ce=class Ce extends b{constructor(e,t){super("AUTH_FAILED",e,t);this.name="AuthenticationError"}};N=class N extends b{constructor(e,t,n){super(e,t,n);this.name="QueryError"}};I=class I extends b{constructor(e,t,n){super(e,t,n);this.name="ConstraintError"}}});function tn(){return{type:"response",id:0,success:!1,error:"Invalid JSON"}}async function nn(e,t){let n=e.id??0,r=t(e.method);if(!r)return{type:"response",id:n,success:!1,error:`Unknown method: ${e.method}`};try{let s=await r(e.params);return{type:"response",id:n,success:!0,payload:s}}catch(s){return{type:"response",id:n,success:!1,error:s instanceof Error?s.message:String(s),errorCode:s instanceof b?s.code:void 0}}}function rn(e){let t=typeof e==="string"?e:new TextDecoder().decode(e),n;try{n=JSON.parse(t)}catch{return null}if(typeof n!=="object"||n===null||typeof n.method!=="string")return null;let{id:r,method:s,params:i}=n;return{id:r,method:s,params:i}}var sn=C(()=>{q()});function on(e){return`"${e.replace(/"/g,'""')}"`}function W(e){let t=new Set,n=[];for(let r of e)for(let s of Object.keys(r))if(!t.has(s))t.add(s),n.push(s);return n}function ln(e,t){let n=[...e];for(let r of t??[])if(!n.includes(r))n.push(r);return n}function ts(e){if(e===null||e===void 0)return"";if(typeof e==="object")return JSON.stringify(e);return String(e)}function tt(e){if(e===null||e===void 0)return"NULL";if(typeof e==="number")return String(e);if(typeof e==="boolean")return e?"TRUE":"FALSE";if(typeof e==="string")return`'${e.replace(/'/g,"''")}'`;if(typeof e==="object")return`'${JSON.stringify(e).replace(/'/g,"''")}'`;return String(e)}function ns(e){if(e===null||e===void 0)return"NULL";if(typeof e==="object")return JSON.stringify(e);return String(e)}function an(e){return e.replace(/\|/g,"\\|").replace(/\n/g," ")}function et(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function cn(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function rs(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");if(!/^[a-zA-Z_]/.test(t))t="_"+t;return t}function ss(e,t,n){if(!e)return n(t);return`${n(e)}.${n(t)}`}function un(e){let t=e.quoteIdentifier??on,n=e.qualifiedTableName??ss(e.schema,e.table,t);switch(e.format){case"csv":return new dn(e.delimiter??",",e.includeHeaders??!0);case"json":return new pn;case"sql":return new mn(n,e.batchSize??100,t);case"markdown":return new fn;case"sql_update":if(!e.keyColumns||e.keyColumns.length===0)throw Error("SQL UPDATE export requires key columns");return new hn(n,t,e.keyColumns);case"html":return new gn;case"xml":return new yn}}class dn{delimiter;includeHeaders;columns=null;constructor(e,t){this.delimiter=e;this.includeHeaders=t}preamble(){return""}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=W(e);let n=this.columns,r=[];if(t&&this.includeHeaders)r.push(n.map((s)=>this.escapeField(s)).join(this.delimiter));for(let s of e){let i=n.map((o)=>this.escapeField(ts(s[o])));r.push(i.join(this.delimiter))}return r.join(`
4
4
  `)+`
5
5
  `}epilogue(){return""}escapeField(e){if(e.includes(this.delimiter)||e.includes('"')||e.includes(`
6
- `)||e.includes("\r"))return`"${e.replace(/"/g,'""')}"`;return e}}class Xt{hasWritten=!1;preamble(){return`[
6
+ `)||e.includes("\r"))return`"${e.replace(/"/g,'""')}"`;return e}}class pn{hasWritten=!1;preamble(){return`[
7
7
  `}formatBatch(e){if(e.length===0)return"";return e.map((n)=>{let r=this.hasWritten?`,
8
8
  `:"";return this.hasWritten=!0,r+" "+JSON.stringify(n)}).join("")}epilogue(){return`
9
9
  ]
10
- `}}class Zt{tableName;batchSize;quoteIdentifier;columns=null;constructor(e,t,n){this.tableName=e;this.batchSize=t;this.quoteIdentifier=n}preamble(){return""}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let t=this.columns,r=t.map((i)=>this.quoteIdentifier(i)).join(", "),s=[];for(let i=0;i<e.length;i+=this.batchSize){let a=e.slice(i,i+this.batchSize).map((c)=>`(${t.map((l)=>Ge(c[l])).join(", ")})`);s.push(`INSERT INTO ${this.tableName} (${r}) VALUES
10
+ `}}class mn{tableName;batchSize;quoteIdentifier;columns=null;constructor(e,t,n){this.tableName=e;this.batchSize=t;this.quoteIdentifier=n}preamble(){return""}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=W(e);let t=this.columns,r=t.map((i)=>this.quoteIdentifier(i)).join(", "),s=[];for(let i=0;i<e.length;i+=this.batchSize){let a=e.slice(i,i+this.batchSize).map((c)=>`(${t.map((l)=>tt(c[l])).join(", ")})`);s.push(`INSERT INTO ${this.tableName} (${r}) VALUES
11
11
  ${a.join(`,
12
12
  `)};
13
13
  `)}return s.join(`
14
- `)}epilogue(){return""}}class en{columns=null;preamble(){return""}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let n=this.columns,r=[];if(t)r.push("| "+n.map(jt).join(" | ")+" |"),r.push("| "+n.map(()=>"---").join(" | ")+" |");for(let s of e){let i=n.map((o)=>jt(Nr(s[o])));r.push("| "+i.join(" | ")+" |")}return r.join(`
14
+ `)}epilogue(){return""}}class fn{columns=null;preamble(){return""}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=W(e);let n=this.columns,r=[];if(t)r.push("| "+n.map(an).join(" | ")+" |"),r.push("| "+n.map(()=>"---").join(" | ")+" |");for(let s of e){let i=n.map((o)=>an(ns(s[o])));r.push("| "+i.join(" | ")+" |")}return r.join(`
15
15
  `)+`
16
- `}epilogue(){return""}}class tn{tableName;quoteIdentifier;keyColumns;columns=null;constructor(e,t,n){this.tableName=e;this.quoteIdentifier=t;this.keyColumns=n}preamble(){return""}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let t=this.columns,n=new Set(this.keyColumns),r=t.filter((i)=>!n.has(i)),s=[];for(let i of e){if(r.length===0)continue;for(let c of this.keyColumns){if(!Object.hasOwn(i,c))throw Error(`SQL UPDATE export key column "${c}" is missing from exported rows`);if(i[c]===null||i[c]===void 0)throw Error(`SQL UPDATE export key column "${c}" has no value`)}let o=r.map((c)=>`${this.quoteIdentifier(c)} = ${Ge(i[c])}`).join(", "),a=this.keyColumns.map((c)=>`${this.quoteIdentifier(c)} = ${Ge(i[c])}`).join(" AND ");s.push(`UPDATE ${this.tableName} SET ${o} WHERE ${a};
17
- `)}return s.join("")}epilogue(){return""}}class nn{columns=null;preamble(){return`<table>
18
- `}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let n=this.columns,r=[];if(t){r.push(" <thead>"),r.push(" <tr>");for(let s of n)r.push(` <th>${ze(s)}</th>`);r.push(" </tr>"),r.push(" </thead>"),r.push(" <tbody>")}for(let s of e){r.push(" <tr>");for(let i of n){let o=s[i],a=o===null||o===void 0?"":typeof o==="object"?ze(JSON.stringify(o)):ze(String(o));r.push(` <td>${a}</td>`)}r.push(" </tr>")}return r.join(`
16
+ `}epilogue(){return""}}class hn{tableName;quoteIdentifier;keyColumns;columns=null;constructor(e,t,n){this.tableName=e;this.quoteIdentifier=t;this.keyColumns=n}preamble(){return""}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=W(e);let t=this.columns,n=new Set(this.keyColumns),r=t.filter((i)=>!n.has(i)),s=[];for(let i of e){if(r.length===0)continue;for(let c of this.keyColumns){if(!Object.hasOwn(i,c))throw Error(`SQL UPDATE export key column "${c}" is missing from exported rows`);if(i[c]===null||i[c]===void 0)throw Error(`SQL UPDATE export key column "${c}" has no value`)}let o=r.map((c)=>`${this.quoteIdentifier(c)} = ${tt(i[c])}`).join(", "),a=this.keyColumns.map((c)=>`${this.quoteIdentifier(c)} = ${tt(i[c])}`).join(" AND ");s.push(`UPDATE ${this.tableName} SET ${o} WHERE ${a};
17
+ `)}return s.join("")}epilogue(){return""}}class gn{columns=null;preamble(){return`<table>
18
+ `}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=W(e);let n=this.columns,r=[];if(t){r.push(" <thead>"),r.push(" <tr>");for(let s of n)r.push(` <th>${et(s)}</th>`);r.push(" </tr>"),r.push(" </thead>"),r.push(" <tbody>")}for(let s of e){r.push(" <tr>");for(let i of n){let o=s[i],a=o===null||o===void 0?"":typeof o==="object"?et(JSON.stringify(o)):et(String(o));r.push(` <td>${a}</td>`)}r.push(" </tr>")}return r.join(`
19
19
  `)+`
20
20
  `}epilogue(){return` </tbody>
21
21
  </table>
22
- `}}class rn{columns=null;preamble(){return`<?xml version="1.0" encoding="UTF-8"?>
22
+ `}}class yn{columns=null;preamble(){return`<?xml version="1.0" encoding="UTF-8"?>
23
23
  <rows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
24
- `}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let t=this.columns,n=[];for(let r of e){n.push(" <row>");for(let s of t){let i=r[s],o=Dr(s);if(i===null||i===void 0)n.push(` <${o} xsi:nil="true"/>`);else{let a=typeof i==="object"?zt(JSON.stringify(i)):zt(String(i));n.push(` <${o}>${a}</${o}>`)}}n.push(" </row>")}return n.join(`
24
+ `}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=W(e);let t=this.columns,n=[];for(let r of e){n.push(" <row>");for(let s of t){let i=r[s],o=rs(s);if(i===null||i===void 0)n.push(` <${o} xsi:nil="true"/>`);else{let a=typeof i==="object"?cn(JSON.stringify(i)):cn(String(i));n.push(` <${o}>${a}</${o}>`)}}n.push(" </row>")}return n.join(`
25
25
  `)+`
26
26
  `}epilogue(){return`</rows>
27
- `}}var sn=()=>{};var Ii;var M=T(()=>{Ii=Object.freeze({__dotaz_sentinel:"DEFAULT"})});function we(e,t){let n=t.getDriverType()==="mysql"?"CHAR":"TEXT";return`CAST(${e} AS ${n})`}function Ve(e){return e.includes(".")}function Je(e){let t=e.indexOf(".");return{table:e.substring(0,t),column:e.substring(t+1)}}function Xe(e,t){return(n)=>{if(Ve(n)){let{table:r,column:s}=Je(n),i=e.find((o)=>o.referencedTable===r);if(i)return`${t.quoteIdentifier(i.alias)}.${t.quoteIdentifier(s)}`}return`t0.${t.quoteIdentifier(n)}`}}function Ee(e,t,n=0,r){if(!e||e.length===0)return{sql:"",params:[]};let s=[],i=[],o=n;for(let a of e){let c=r?r(a.column):t.quoteIdentifier(a.column);switch(a.operator){case"eq":o++,s.push(`${c} = ${t.placeholder(o)}`),i.push(a.value);break;case"neq":o++,s.push(`${c} != ${t.placeholder(o)}`),i.push(a.value);break;case"gt":o++,s.push(`${c} > ${t.placeholder(o)}`),i.push(a.value);break;case"gte":o++,s.push(`${c} >= ${t.placeholder(o)}`),i.push(a.value);break;case"lt":o++,s.push(`${c} < ${t.placeholder(o)}`),i.push(a.value);break;case"lte":o++,s.push(`${c} <= ${t.placeholder(o)}`),i.push(a.value);break;case"like":o++,s.push(`${c} LIKE ${t.placeholder(o)}`),i.push(a.value);break;case"notLike":o++,s.push(`${c} NOT LIKE ${t.placeholder(o)}`),i.push(a.value);break;case"in":{let u=Array.isArray(a.value)?a.value:[a.value],l=u.map(()=>(o++,t.placeholder(o)));s.push(`${c} IN (${l.join(", ")})`),i.push(...u);break}case"notIn":{let u=Array.isArray(a.value)?a.value:[a.value],l=u.map(()=>(o++,t.placeholder(o)));s.push(`${c} NOT IN (${l.join(", ")})`),i.push(...u);break}case"isNull":s.push(`${c} IS NULL`);break;case"isNotNull":s.push(`${c} IS NOT NULL`);break}}if(s.length===0)return{sql:"",params:[]};return{sql:`WHERE ${s.join(" AND ")}`,params:i}}function be(e,t,n){if(!e||e.length===0)return"";return`ORDER BY ${e.map((s)=>{let i=n?n(s.column):t.quoteIdentifier(s.column),o=s.direction==="desc"?"DESC":"ASC";return`${i} ${o}`}).join(", ")}`}function Ze(e,t){return e.map((n)=>{let r=t.qualifyTable(n.referencedSchema,n.referencedTable),s=t.quoteIdentifier(n.alias),i;if(Ve(n.fkColumn)){let{table:a,column:c}=Je(n.fkColumn),u=e.find((l)=>l.referencedTable===a);if(u)i=`${t.quoteIdentifier(u.alias)}.${t.quoteIdentifier(c)}`;else i=`t0.${t.quoteIdentifier(n.fkColumn)}`}else i=`t0.${t.quoteIdentifier(n.fkColumn)}`;let o=`${s}.${t.quoteIdentifier(n.referencedColumn)}`;return`LEFT JOIN ${r} AS ${s} ON ${i} = ${o}`}).join(" ")}var Ce=T(()=>{M()});async function et(e,t,n,r,s){let i=Mr(t.format==="csv"?t.encoding:void 0),o=cn(t,e),a=0;if(t.format==="csv"&&t.utf8Bom&&(t.encoding??"utf-8")==="utf-8")await n.write(new Uint8Array([239,187,191]));let c=o.preamble();if(c)await n.write(i(c));let{sql:u,params:l}=Te(t,e),m=t.batchSize??Ir,f=e.iterate(u,l,m,r),g=!0;for await(let h of f){let y=h;if(t.limit!==void 0){let p=t.limit-a;if(p<=0)break;if(y.length>p)y=y.slice(0,p)}let w=o.formatBatch(y,g);if(await n.write(i(w)),a+=y.length,s?.(a),g=!1,t.limit!==void 0&&a>=t.limit)break}let d=o.epilogue();if(d)await n.write(i(d));return await n.end(),{rowCount:a}}async function on(e,t,n,r,s){let o=Bun.file(n).writer(),a={write(c){o.write(c)},async end(){await o.end()}};try{let c=await et(e,t,a,r,s),u=await Bun.file(n).stat();return{rowCount:c.rowCount,sizeBytes:u?.size??0}}catch(c){await o.end();try{let{unlink:u}=await import("fs/promises");await u(n)}catch{}throw c}}async function an(e,t){let n=t.limit??10,{sql:r,params:s}=Te(t,e),i=s.length;i++;let o=e.placeholder(i),a=`${r} LIMIT ${o}`,u=(await e.execute(a,[...s,n])).rows,l=cn(t,e),m=[],f=l.preamble();if(f)m.push(f);m.push(l.formatBatch(u,!0));let g=l.epilogue();if(g)m.push(g);return m.join("")}function Te(e,t){let n=e.autoJoins,r=n&&n.length>0,s=xr(e),i=t.qualifyTable(e.schema,e.table),o=r?Xe(n,t):void 0,a=Ee(e.filters,t,0,o),c=be(e.sort,t,o);if(r){let m=Ze(n,t),f="t0.*";if(s&&s.length>0)f=s.map((d)=>{if(d.includes("."))return`${o(d)} AS ${t.quoteIdentifier(d)}`;return`t0.${t.quoteIdentifier(d)}`}).join(", ");let g=[`SELECT ${f} FROM ${i} AS t0 ${m}`];if(a.sql)g.push(a.sql);if(c)g.push(c);return{sql:g.join(" "),params:[...a.params]}}let l=[`SELECT ${s&&s.length>0?s.map((m)=>t.quoteIdentifier(m)).join(", "):"*"} FROM ${i}`];if(a.sql)l.push(a.sql);if(c)l.push(c);return{sql:l.join(" "),params:[...a.params]}}function xr(e){if(e.format!=="sql_update"||!e.columns||e.columns.length===0||!e.keyColumns)return e.columns;return Gt(e.columns,e.keyColumns)}function cn(e,t){return Vt({format:e.format,schema:e.schema,table:e.table,delimiter:e.delimiter,includeHeaders:e.includeHeaders,batchSize:e.batchSize,qualifiedTableName:t.qualifyTable(e.schema,e.table),quoteIdentifier:(n)=>t.quoteIdentifier(n),keyColumns:e.keyColumns})}function Pr(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t[n]=r<=255?r:63}return t}function kr(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<=255)t[n]=r;else t[n]=Lr[r]??63}return t}function Mr(e){switch(e){case"iso-8859-1":return Pr;case"windows-1252":return kr;default:return(t)=>t}}var Ir=1000,Lr;var tt=T(()=>{sn();Ce();Lr={8364:128,8218:130,402:131,8222:132,8230:133,8224:134,8225:135,710:136,8240:137,352:138,8249:139,338:140,381:142,8216:145,8217:146,8220:147,8221:148,8226:149,8211:150,8212:151,732:152,8482:153,353:154,8250:155,339:156,382:158,376:159}});async function*nt(e,t){let{delimiter:n,hasHeader:r,batchSize:s,maxRows:i,maxBufferSize:o=67108864}=t,a=new TextDecoder("utf-8"),c=e.getReader(),u="",l=0,m=!1,f="",g=[],d=1,h=null,y=0,w=[],p=!1;function S(E){if(E.length===1&&E[0]==="")return 0;if(h===null){if(r)return h=E,0;h=E.map((C,N)=>`col${N+1}`)}if(w.push(Ur(E,h)),y++,i!==void 0&&y>=i)return 2;if(w.length>=s)return 1;return 0}try{while(!p){let E=await c.read();if(E.done)u+=a.decode(new Uint8Array(0),{stream:!1}),p=!0;else u+=a.decode(E.value,{stream:!0});if(u.length>o)throw new Ae(`buffer size exceeded ${o/1048576}MB \u2014 possible malformed input or extremely large field`,d);while(l<u.length){let C=u[l];if(m)if(C==='"')if(l+1<u.length)if(u[l+1]==='"')f+='"',l+=2;else m=!1,l++;else if(p)m=!1,l++;else break;else{if(C===`
28
- `)d++;else if(C==="\r"){if(d++,l+1<u.length){if(u[l+1]===`
27
+ `}}var wn=()=>{};var jo;var K=C(()=>{jo=Object.freeze({__dotaz_sentinel:"DEFAULT"})});function Te(e,t){let n=t.getDriverType()==="mysql"?"CHAR":"TEXT";return`CAST(${e} AS ${n})`}function nt(e){return e.includes(".")}function rt(e){let t=e.indexOf(".");return{table:e.substring(0,t),column:e.substring(t+1)}}function st(e,t){return(n)=>{if(nt(n)){let{table:r,column:s}=rt(n),i=e.find((o)=>o.referencedTable===r);if(i)return`${t.quoteIdentifier(i.alias)}.${t.quoteIdentifier(s)}`}return`t0.${t.quoteIdentifier(n)}`}}function Ae(e,t,n=0,r){if(!e||e.length===0)return{sql:"",params:[]};let s=[],i=[],o=n;for(let a of e){let c=r?r(a.column):t.quoteIdentifier(a.column);switch(a.operator){case"eq":o++,s.push(`${c} = ${t.placeholder(o)}`),i.push(a.value);break;case"neq":o++,s.push(`${c} != ${t.placeholder(o)}`),i.push(a.value);break;case"gt":o++,s.push(`${c} > ${t.placeholder(o)}`),i.push(a.value);break;case"gte":o++,s.push(`${c} >= ${t.placeholder(o)}`),i.push(a.value);break;case"lt":o++,s.push(`${c} < ${t.placeholder(o)}`),i.push(a.value);break;case"lte":o++,s.push(`${c} <= ${t.placeholder(o)}`),i.push(a.value);break;case"like":o++,s.push(`${c} LIKE ${t.placeholder(o)}`),i.push(a.value);break;case"notLike":o++,s.push(`${c} NOT LIKE ${t.placeholder(o)}`),i.push(a.value);break;case"in":{let u=Array.isArray(a.value)?a.value:[a.value],l=u.map(()=>(o++,t.placeholder(o)));s.push(`${c} IN (${l.join(", ")})`),i.push(...u);break}case"notIn":{let u=Array.isArray(a.value)?a.value:[a.value],l=u.map(()=>(o++,t.placeholder(o)));s.push(`${c} NOT IN (${l.join(", ")})`),i.push(...u);break}case"isNull":s.push(`${c} IS NULL`);break;case"isNotNull":s.push(`${c} IS NOT NULL`);break}}if(s.length===0)return{sql:"",params:[]};return{sql:`WHERE ${s.join(" AND ")}`,params:i}}function ve(e,t,n){if(!e||e.length===0)return"";return`ORDER BY ${e.map((s)=>{let i=n?n(s.column):t.quoteIdentifier(s.column),o=s.direction==="desc"?"DESC":"ASC";return`${i} ${o}`}).join(", ")}`}function it(e,t){return e.map((n)=>{let r=t.qualifyTable(n.referencedSchema,n.referencedTable),s=t.quoteIdentifier(n.alias),i;if(nt(n.fkColumn)){let{table:a,column:c}=rt(n.fkColumn),u=e.find((l)=>l.referencedTable===a);if(u)i=`${t.quoteIdentifier(u.alias)}.${t.quoteIdentifier(c)}`;else i=`t0.${t.quoteIdentifier(n.fkColumn)}`}else i=`t0.${t.quoteIdentifier(n.fkColumn)}`;let o=`${s}.${t.quoteIdentifier(n.referencedColumn)}`;return`LEFT JOIN ${r} AS ${s} ON ${i} = ${o}`}).join(" ")}var Re=C(()=>{K()});async function ot(e,t,n,r,s){let i=ds(t.format==="csv"?t.encoding:void 0),o=bn(t,e),a=0;if(t.format==="csv"&&t.utf8Bom&&(t.encoding??"utf-8")==="utf-8")await n.write(new Uint8Array([239,187,191]));let c=o.preamble();if(c)await n.write(i(c));let{sql:u,params:l}=Ne(t,e),d=t.batchSize??os,f=e.iterate(u,l,d,r),h=!0;for await(let g of f){let y=g;if(t.limit!==void 0){let m=t.limit-a;if(m<=0)break;if(y.length>m)y=y.slice(0,m)}let S=o.formatBatch(y,h);if(await n.write(i(S)),a+=y.length,s?.(a),h=!1,t.limit!==void 0&&a>=t.limit)break}let p=o.epilogue();if(p)await n.write(i(p));return await n.end(),{rowCount:a}}async function Sn(e,t,n,r,s){let o=Bun.file(n).writer(),a={write(c){o.write(c)},async end(){await o.end()}};try{let c=await ot(e,t,a,r,s),u=await Bun.file(n).stat();return{rowCount:c.rowCount,sizeBytes:u?.size??0}}catch(c){await o.end();try{let{unlink:u}=await import("fs/promises");await u(n)}catch{}throw c}}async function En(e,t){let n=t.limit??10,{sql:r,params:s}=Ne(t,e),i=s.length;i++;let o=e.placeholder(i),a=`${r} LIMIT ${o}`,u=(await e.execute(a,[...s,n])).rows,l=bn(t,e),d=[],f=l.preamble();if(f)d.push(f);d.push(l.formatBatch(u,!0));let h=l.epilogue();if(h)d.push(h);return d.join("")}function Ne(e,t){let n=e.autoJoins,r=n&&n.length>0,s=as(e),i=t.qualifyTable(e.schema,e.table),o=r?st(n,t):void 0,a=Ae(e.filters,t,0,o),c=ve(e.sort,t,o);if(r){let d=it(n,t),f="t0.*";if(s&&s.length>0)f=s.map((p)=>{if(p.includes("."))return`${o(p)} AS ${t.quoteIdentifier(p)}`;return`t0.${t.quoteIdentifier(p)}`}).join(", ");let h=[`SELECT ${f} FROM ${i} AS t0 ${d}`];if(a.sql)h.push(a.sql);if(c)h.push(c);return{sql:h.join(" "),params:[...a.params]}}let l=[`SELECT ${s&&s.length>0?s.map((d)=>t.quoteIdentifier(d)).join(", "):"*"} FROM ${i}`];if(a.sql)l.push(a.sql);if(c)l.push(c);return{sql:l.join(" "),params:[...a.params]}}function as(e){if(e.format!=="sql_update"||!e.columns||e.columns.length===0||!e.keyColumns)return e.columns;return ln(e.columns,e.keyColumns)}function bn(e,t){return un({format:e.format,schema:e.schema,table:e.table,delimiter:e.delimiter,includeHeaders:e.includeHeaders,batchSize:e.batchSize,qualifiedTableName:t.qualifyTable(e.schema,e.table),quoteIdentifier:(n)=>t.quoteIdentifier(n),keyColumns:e.keyColumns})}function ls(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t[n]=r<=255?r:63}return t}function us(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<=255)t[n]=r;else t[n]=cs[r]??63}return t}function ds(e){switch(e){case"iso-8859-1":return ls;case"windows-1252":return us;default:return(t)=>t}}var os=1000,cs;var at=C(()=>{wn();Re();cs={8364:128,8218:130,402:131,8222:132,8230:133,8224:134,8225:135,710:136,8240:137,352:138,8249:139,338:140,381:142,8216:145,8217:146,8220:147,8221:148,8226:149,8211:150,8212:151,732:152,8482:153,353:154,8250:155,339:156,382:158,376:159}});async function*ct(e,t){let{delimiter:n,hasHeader:r,batchSize:s,maxRows:i,maxBufferSize:o=67108864}=t,a=new TextDecoder("utf-8"),c=e.getReader(),u="",l=0,d=!1,f="",h=[],p=1,g=null,y=0,S=[],m=!1;function w(E){if(E.length===1&&E[0]==="")return 0;if(g===null){if(r)return g=E,0;g=E.map((T,D)=>`col${D+1}`)}if(S.push(ps(E,g)),y++,i!==void 0&&y>=i)return 2;if(S.length>=s)return 1;return 0}try{while(!m){let E=await c.read();if(E.done)u+=a.decode(new Uint8Array(0),{stream:!1}),m=!0;else u+=a.decode(E.value,{stream:!0});if(u.length>o)throw new De(`buffer size exceeded ${o/1048576}MB \u2014 possible malformed input or extremely large field`,p);while(l<u.length){let T=u[l];if(d)if(T==='"')if(l+1<u.length)if(u[l+1]==='"')f+='"',l+=2;else d=!1,l++;else if(m)d=!1,l++;else break;else{if(T===`
28
+ `)p++;else if(T==="\r"){if(p++,l+1<u.length){if(u[l+1]===`
29
29
  `){f+=`\r
30
- `,l+=2;continue}}else if(!p)break}f+=C,l++}else if(C==='"')m=!0,l++;else if(C===n)g.push(f),f="",l++;else if(C==="\r"||C===`
31
- `){if(C==="\r")if(l+1<u.length){if(l++,u[l]===`
32
- `)l++}else if(p)l++;else break;else l++;g.push(f),f="",d++;let N=S(g);switch(g=[],N){case 2:if(w.length>0)yield{columns:h,rows:w},w=[];return;case 1:yield{columns:h,rows:w},w=[];break}}else f+=C,l++}if(l>0)u=u.slice(l),l=0}if(m)throw new Ae("Unclosed quote",d);if(f!==""||g.length>0)g.push(f),S(g);if(w.length>0)yield{columns:h??[],rows:w}}finally{c.releaseLock()}}function Ur(e,t){let n={};for(let r=0;r<t.length;r++){let s=r<e.length?e[r]:null;n[t[r]]=s===""?null:$r(s)}return n}function $r(e){if(e===null||e==="")return null;let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+$/.test(e)){let n=parseInt(e,10);if(Number.isSafeInteger(n))return n}if(/^-?\d+\.\d+$/.test(e)){let n=parseFloat(e);if(Number.isFinite(n))return n}return e}var Ae;var ln=T(()=>{Ae=class Ae extends Error{lineNumber;constructor(e,t){super(`CSV parse error at line ${t}: ${e}`);this.name="CsvParseError",this.lineNumber=t}}});async function ve(e,t,n,r,s){let i=n.mappings.filter((m)=>m.tableColumn!==null);if(i.length===0)throw Error("No columns mapped for import");if(n.format==="json")return qr(e,t,n,i,r,s);let o=e.qualifyTable(n.schema,n.table),a=i.map((m)=>m.tableColumn),c=n.batchSize??un,u={delimiter:n.delimiter??",",hasHeader:n.hasHeader??!0,batchSize:c},l=`__import_${crypto.randomUUID()}`;await e.reserveSession(l);try{await e.beginTransaction(l);let m=0;for await(let{rows:f}of nt(t,u)){if(r?.aborted)throw Error("Import cancelled");let g=f.map((d)=>pn(d,i));await e.importBatch(o,a,g,l),m+=f.length,s?.(m)}return await e.commit(l),{rowCount:m}}catch(m){try{await e.rollback(l)}catch(f){console.debug("Rollback after import error failed:",f instanceof Error?f.message:f)}throw m}finally{await e.releaseSession(l)}}async function dn(e,t){let n=t.limit??20;if(t.format==="json")return Fr(e);let r={delimiter:t.delimiter??",",hasHeader:t.hasHeader??!0,batchSize:n,maxRows:n},s=[],i=[];for await(let o of nt(e,r))i=o.columns,s.push(...o.rows);return{fileColumns:i,rows:s.slice(0,n),totalRows:void 0}}async function qr(e,t,n,r,s,i){let o=await fn(t),a=mn(o),c=e.qualifyTable(n.schema,n.table),u=r.map((f)=>f.tableColumn),l=n.batchSize??un,m=`__import_${crypto.randomUUID()}`;await e.reserveSession(m);try{await e.beginTransaction(m);let f=0;for(let g=0;g<a.length;g+=l){if(s?.aborted)throw Error("Import cancelled");let d=a.slice(g,g+l),h=d.map((y)=>pn(y,r));await e.importBatch(c,u,h,m),f+=d.length,i?.(f)}return await e.commit(m),{rowCount:f}}catch(f){try{await e.rollback(m)}catch(g){console.debug("Rollback after import error failed:",g instanceof Error?g.message:g)}throw f}finally{await e.releaseSession(m)}}async function Fr(e){let t=await fn(e),n=mn(t);return{fileColumns:Hr(n),rows:n.slice(0,20),totalRows:n.length}}function mn(e){let t=JSON.parse(e);if(!Array.isArray(t))throw Error("JSON import expects an array of objects");let n=[];for(let r of t){if(typeof r!=="object"||r===null||Array.isArray(r))throw Error("Each JSON array element must be an object");n.push(r)}return n}function pn(e,t){let n={};for(let r of t)n[r.tableColumn]=e[r.fileColumn]??null;return n}function Hr(e){let t=new Set,n=[];for(let r of e)for(let s of Object.keys(r))if(!t.has(s))t.add(s),n.push(s);return n}async function fn(e){let t=e.getReader(),n=new TextDecoder("utf-8"),r="";while(!0){let{done:s,value:i}=await t.read();if(s)break;r+=n.decode(i,{stream:!0})}return r+=n.decode(new Uint8Array(0),{stream:!1}),t.releaseLock(),r}var un=100;var rt=T(()=>{ln()});function Re(e){return e.columns.length>0?e.rowCount:e.affectedRows??e.rowCount}function j(e){if(e===void 0||e==="")return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95||t>=128}function H(e){let t=[],n="",r=0;while(r<e.length){let i=e[r],o=r+1<e.length?e[r+1]:"";if(i==="-"&&o==="-"){let a=e.indexOf(`
33
- `,r);if(a===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,a+1),r=a+1;continue}if(i==="/"&&o==="*"){let a=e.indexOf("*/",r+2);if(a===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,a+2),r=a+2;continue}if(i==="$"&&!j(e[r-1])){let a=e.slice(r).match(/^(\$[a-zA-Z0-9_]*\$)/);if(a){let c=a[1],u=e.indexOf(c,r+c.length);if(u===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,u+c.length),r=u+c.length;continue}}if(i==="'"){n+=i,r++;while(r<e.length)if(e[r]==="'")if(n+=e[r],r++,r<e.length&&e[r]==="'")n+=e[r],r++;else break;else n+=e[r],r++;continue}if(i==='"'){n+=i,r++;while(r<e.length)if(e[r]==='"')if(n+=e[r],r++,r<e.length&&e[r]==='"')n+=e[r],r++;else break;else n+=e[r],r++;continue}if(i===";"){let a=n.trim();if(a.length>0)t.push(a);n="",r++;continue}n+=i,r++}let s=n.trim();if(s.length>0)t.push(s);return t}function Ne(e,t){let n=1,r=1,s=Math.min(t-1,e.length);for(let i=0;i<s;i++)if(e[i]===`
34
- `)n++,r=1;else r++;return{line:n,column:r}}function z(e){let t="",n=0;while(n<e.length){let r=e[n],s=n+1<e.length?e[n+1]:"";if(r==="-"&&s==="-"){let i=e.indexOf(`
35
- `,n);t+=" ",n=i===-1?e.length:i+1;continue}if(r==="/"&&s==="*"){let i=e.indexOf("*/",n+2);t+=" ",n=i===-1?e.length:i+2;continue}if(r==="$"&&!j(e[n-1])){let i=e.slice(n).match(/^(\$[a-zA-Z0-9_]*\$)/);if(i){let o=i[1],a=e.indexOf(o,n+o.length);t+=" ",n=a===-1?e.length:a+o.length;continue}}if(r==="'"){t+=" ",n++;while(n<e.length)if(e[n]==="'")if(n++,n<e.length&&e[n]==="'")n++;else break;else n++;continue}if(r==='"'){t+=" ",n++;while(n<e.length)if(e[n]==='"')if(n++,n<e.length&&e[n]==='"')n++;else break;else n++;continue}t+=r,n++}return t}function jr(e){return st(zr(e))}function gn(e){let t=H(e);if(t.length===0)return!1;return t.every((n)=>jr(n)==="read")}function zr(e){return z(e).replace(/\s+/g," ").trim().toUpperCase()}function st(e){let t=e.replace(/^[(\s]+/,""),n=t.match(/^[A-Z_]+/)?.[0];if(!n)return"unknown";if(/\bSET_CONFIG\s*\(/.test(t))return"unknown";if(n==="WITH"){let r=Gr(t);if(r===null)return"unknown";let s=Vr(t.slice(0,r));if(s!=="read")return s;return st(t.slice(r))}if(n==="EXPLAIN")return Xr(t);if(n==="PRAGMA")return Jr(t);if(n==="COPY")return/\bFROM\b/.test(t)?"write":"unknown";if(n==="SELECT"&&/\bINTO\b/.test(t))return"unknown";if(Br.has(n))return"read";if(Qr.has(n))return"write";if(hn.has(n))return"ddl";return"unknown"}function Gr(e){let t=0,n=-1;for(let r=0;r<=e.length;r++){let s=r<e.length?e[r]:" ";if(s==="("||s===")"){t+=s==="("?1:-1,n=-1;continue}if(/[A-Z0-9_]/.test(s)){if(n===-1)n=r;continue}if(n!==-1&&t===0&&Yr.has(e.slice(n,r)))return n;n=-1}return null}function Vr(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===")"){t--;continue}if(r!=="(")continue;if(t++,t!==1)continue;let s=e.slice(n+1).match(/^\s*([A-Z_]+)/)?.[1];if(!s)continue;if(Kr.has(s))return"write";if(hn.has(s))return"ddl";if(s==="WITH")return"unknown"}return"read"}function Jr(e){if(e.includes("="))return"unknown";let t=e.match(/^PRAGMA\s+(?:[A-Z0-9_]+\s*\.\s*)?([A-Z0-9_]+)\s*(\()?/);if(!t)return"unknown";if(!t[2])return"read";return Wr.has(t[1])?"read":"unknown"}function Xr(e){let t=e.slice(7).trim(),n=!1;if(t.startsWith("(")){let r=Zr(t);if(r===-1)return"unknown";let s=t.slice(1,r);n=/\bANALYZE\b/.test(s)&&!/\bANALYZE\s+(FALSE|OFF|0)\b/.test(s),t=t.slice(r+1).trim()}else while(!0){let r=t.match(/^(ANALYZE|VERBOSE|QUERY PLAN|EXTENDED|PARTITIONS|FORMAT\s*=\s*[A-Z]+)\b\s*/);if(!r)break;if(r[1]==="ANALYZE")n=!0;t=t.slice(r[0].length)}if(!n)return"read";if(t.length===0)return"unknown";return st(t)}function Zr(e){let t=0;for(let n=0;n<e.length;n++)if(e[n]==="(")t++;else if(e[n]===")"&&--t===0)return n;return-1}function De(e,t){if(!e||typeof e!=="object")return;let n=e;if(n.position!=null){let r=Number(n.position);if(!Number.isNaN(r)&&r>0){let{line:s,column:i}=Ne(t,r);return{line:s,column:i,offset:r}}}if(e instanceof Error){let r=e.message.match(/at offset (\d+)/);if(r){let s=Number(r[1])+1,{line:i,column:o}=Ne(t,s);return{line:i,column:o,offset:s}}}return}var Br,Qr,hn,Yr,Kr,Wr;var G=T(()=>{Br=new Set(["SELECT","SHOW","DESCRIBE","DESC","VALUES","TABLE"]),Qr=new Set(["INSERT","UPDATE","DELETE","MERGE","REPLACE","TRUNCATE","CALL","DO"]),hn=new Set(["CREATE","ALTER","DROP","GRANT","REVOKE","VACUUM","REINDEX","ATTACH","DETACH"]),Yr=new Set(["SELECT","INSERT","UPDATE","DELETE","MERGE","REPLACE","VALUES","TABLE"]),Kr=new Set(["INSERT","UPDATE","DELETE","MERGE","REPLACE"]),Wr=new Set(["TABLE_INFO","TABLE_XINFO","TABLE_LIST","INDEX_LIST","INDEX_INFO","INDEX_XINFO","FOREIGN_KEY_LIST","FOREIGN_KEY_CHECK","DATABASE_LIST","COLLATION_LIST","FUNCTION_LIST","MODULE_LIST","PRAGMA_LIST","COMPILE_OPTIONS","INTEGRITY_CHECK","QUICK_CHECK"])});function _e(e,t){if(t===void 0)return Sn.every((r)=>_e(e,r));let n=wn(e,t,{allowComments:!0});if(n===null)return!1;for(let r=0;r<n.length;r++){if(n[r]!==";")continue;for(let s=r+1;s<n.length;s++){let i=n[s];if(i===";"||i===" "||i==="\t"||i===`
36
- `||i==="\r"||i==="\f"||i==="\v")continue;return!1}return!0}return!0}function ot(e,t){if(t===void 0)return Sn.every((s)=>ot(e,s));let n=wn(e,t,{allowComments:!1});if(n===null)return!1;let r=0;for(let s of n){if(s===";")return!1;if(s==="(")r++;if(s===")"&&--r<0)return!1}return r===0}function wn(e,t,n){let r=t==="mysql",s=t==="postgresql",i=t==="sqlite",o=r||s,a=r,c=s,u=r||i,l=i,m=r,f=r,g="",d=0,h=e.length;while(d<h){let y=e[d],w=d+1<h?e[d+1]:"";if(y==="-"&&w==="-"){let p=!0;if(f&&d+2<h){let S=e.charCodeAt(d+2);if(S>127)return null;p=S<=32||S===127}if(p){if(!n.allowComments)return null;let S=yn(e,d);if(S===null)return null;g+=" ",d=S;continue}}if(y==="#"&&m){if(!n.allowComments)return null;let p=yn(e,d);if(p===null)return null;g+=" ",d=p;continue}if(y==="/"&&w==="*"){if(!n.allowComments)return null;if(r&&/^[!+]|^[Mm]!/.test(e.slice(d+2,d+4)))return null;if(s){let S=0,E=d;while(E<h)if(e[E]==="/"&&e[E+1]==="*")S++,E+=2;else if(e[E]==="*"&&e[E+1]==="/"){if(S--,E+=2,S===0)break}else E++;if(S!==0)return null;g+=" ",d=E;continue}let p=e.indexOf("*/",d+2);g+=" ",d=p===-1?h:p+2;continue}if(y==="$"&&c){let p=es(e,d);if(p){let S=d>0?e[d-1]:"";if(j(S)||S==="$")return null;let E=e.indexOf(p,d+p.length);if(E===-1)return null;g+=" ",d=E+p.length;continue}}if(i&&(y==="$"||y==="@"||y===":"||y==="#")){let p=d+1,S=0;while(p<h)if(j(e[p])||e[p]==="$")S++,p++;else if(e[p]===":"&&e[p+1]===":")p+=2;else break;if(e[p]==="("&&S>0)return null}if(y==="'"){let p=it(e,d,"'",o);if(p===-1)return null;g+=" ",d=p;continue}if(y==='"'){let p=it(e,d,'"',a);if(p===-1)return null;g+=" ",d=p;continue}if(y==="`"&&u){let p=it(e,d,"`",!1);if(p===-1)return null;g+=" ",d=p;continue}if(y==="["&&l){let p=e.indexOf("]",d+1);if(p===-1)return null;g+=" ",d=p+1;continue}g+=y,d++}return g}function yn(e,t){for(let n=t;n<e.length;n++){if(e[n]===`
30
+ `,l+=2;continue}}else if(!m)break}f+=T,l++}else if(T==='"')d=!0,l++;else if(T===n)h.push(f),f="",l++;else if(T==="\r"||T===`
31
+ `){if(T==="\r")if(l+1<u.length){if(l++,u[l]===`
32
+ `)l++}else if(m)l++;else break;else l++;h.push(f),f="",p++;let D=w(h);switch(h=[],D){case 2:if(S.length>0)yield{columns:g,rows:S},S=[];return;case 1:yield{columns:g,rows:S},S=[];break}}else f+=T,l++}if(l>0)u=u.slice(l),l=0}if(d)throw new De("Unclosed quote",p);if(f!==""||h.length>0)h.push(f),w(h);if(S.length>0)yield{columns:g??[],rows:S}}finally{c.releaseLock()}}function ps(e,t){let n={};for(let r=0;r<t.length;r++){let s=r<e.length?e[r]:null;n[t[r]]=s===""?null:ms(s)}return n}function ms(e){if(e===null||e==="")return null;let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+$/.test(e)){let n=parseInt(e,10);if(Number.isSafeInteger(n))return n}if(/^-?\d+\.\d+$/.test(e)){let n=parseFloat(e);if(Number.isFinite(n))return n}return e}var De;var Cn=C(()=>{De=class De extends Error{lineNumber;constructor(e,t){super(`CSV parse error at line ${t}: ${e}`);this.name="CsvParseError",this.lineNumber=t}}});async function _e(e,t,n,r,s){let i=n.mappings.filter((d)=>d.tableColumn!==null);if(i.length===0)throw Error("No columns mapped for import");if(n.format==="json")return fs(e,t,n,i,r,s);let o=e.qualifyTable(n.schema,n.table),a=i.map((d)=>d.tableColumn),c=n.batchSize??Tn,u={delimiter:n.delimiter??",",hasHeader:n.hasHeader??!0,batchSize:c},l=`__import_${crypto.randomUUID()}`;await e.reserveSession(l);try{await e.beginTransaction(l);let d=0;for await(let{rows:f}of ct(t,u)){if(r?.aborted)throw Error("Import cancelled");let h=f.map((p)=>Rn(p,i));await e.importBatch(o,a,h,l),d+=f.length,s?.(d)}return await e.commit(l),{rowCount:d}}catch(d){try{await e.rollback(l)}catch(f){console.debug("Rollback after import error failed:",f instanceof Error?f.message:f)}throw d}finally{await e.releaseSession(l)}}async function An(e,t){let n=t.limit??20;if(t.format==="json")return hs(e);let r={delimiter:t.delimiter??",",hasHeader:t.hasHeader??!0,batchSize:n,maxRows:n},s=[],i=[];for await(let o of ct(e,r))i=o.columns,s.push(...o.rows);return{fileColumns:i,rows:s.slice(0,n),totalRows:void 0}}async function fs(e,t,n,r,s,i){let o=await Nn(t),a=vn(o),c=e.qualifyTable(n.schema,n.table),u=r.map((f)=>f.tableColumn),l=n.batchSize??Tn,d=`__import_${crypto.randomUUID()}`;await e.reserveSession(d);try{await e.beginTransaction(d);let f=0;for(let h=0;h<a.length;h+=l){if(s?.aborted)throw Error("Import cancelled");let p=a.slice(h,h+l),g=p.map((y)=>Rn(y,r));await e.importBatch(c,u,g,d),f+=p.length,i?.(f)}return await e.commit(d),{rowCount:f}}catch(f){try{await e.rollback(d)}catch(h){console.debug("Rollback after import error failed:",h instanceof Error?h.message:h)}throw f}finally{await e.releaseSession(d)}}async function hs(e){let t=await Nn(e),n=vn(t);return{fileColumns:gs(n),rows:n.slice(0,20),totalRows:n.length}}function vn(e){let t=JSON.parse(e);if(!Array.isArray(t))throw Error("JSON import expects an array of objects");let n=[];for(let r of t){if(typeof r!=="object"||r===null||Array.isArray(r))throw Error("Each JSON array element must be an object");n.push(r)}return n}function Rn(e,t){let n={};for(let r of t)n[r.tableColumn]=e[r.fileColumn]??null;return n}function gs(e){let t=new Set,n=[];for(let r of e)for(let s of Object.keys(r))if(!t.has(s))t.add(s),n.push(s);return n}async function Nn(e){let t=e.getReader(),n=new TextDecoder("utf-8"),r="";while(!0){let{done:s,value:i}=await t.read();if(s)break;r+=n.decode(i,{stream:!0})}return r+=n.decode(new Uint8Array(0),{stream:!1}),t.releaseLock(),r}var Tn=100;var lt=C(()=>{Cn()});function Oe(e){return e.columns.length>0?e.rowCount:e.affectedRows??e.rowCount}function Z(e){if(e===void 0||e==="")return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95||t>=128}function x(e){let t=[],n="",r=0;while(r<e.length){let i=e[r],o=r+1<e.length?e[r+1]:"";if(i==="-"&&o==="-"){let a=e.indexOf(`
33
+ `,r);if(a===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,a+1),r=a+1;continue}if(i==="/"&&o==="*"){let a=e.indexOf("*/",r+2);if(a===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,a+2),r=a+2;continue}if(i==="$"&&!Z(e[r-1])){let a=e.slice(r).match(/^(\$[a-zA-Z0-9_]*\$)/);if(a){let c=a[1],u=e.indexOf(c,r+c.length);if(u===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,u+c.length),r=u+c.length;continue}}if(i==="'"){n+=i,r++;while(r<e.length)if(e[r]==="'")if(n+=e[r],r++,r<e.length&&e[r]==="'")n+=e[r],r++;else break;else n+=e[r],r++;continue}if(i==='"'){n+=i,r++;while(r<e.length)if(e[r]==='"')if(n+=e[r],r++,r<e.length&&e[r]==='"')n+=e[r],r++;else break;else n+=e[r],r++;continue}if(i===";"){let a=n.trim();if(a.length>0)t.push(a);n="",r++;continue}n+=i,r++}let s=n.trim();if(s.length>0)t.push(s);return t}function Ie(e,t){let n=1,r=1,s=Math.min(t-1,e.length);for(let i=0;i<s;i++)if(e[i]===`
34
+ `)n++,r=1;else r++;return{line:n,column:r}}function F(e){let t="",n=0;while(n<e.length){let r=e[n],s=n+1<e.length?e[n+1]:"";if(r==="-"&&s==="-"){let i=e.indexOf(`
35
+ `,n);t+=" ",n=i===-1?e.length:i+1;continue}if(r==="/"&&s==="*"){let i=e.indexOf("*/",n+2);t+=" ",n=i===-1?e.length:i+2;continue}if(r==="$"&&!Z(e[n-1])){let i=e.slice(n).match(/^(\$[a-zA-Z0-9_]*\$)/);if(i){let o=i[1],a=e.indexOf(o,n+o.length);t+=" ",n=a===-1?e.length:a+o.length;continue}}if(r==="'"){t+=" ",n++;while(n<e.length)if(e[n]==="'")if(n++,n<e.length&&e[n]==="'")n++;else break;else n++;continue}if(r==='"'){t+=" ",n++;while(n<e.length)if(e[n]==='"')if(n++,n<e.length&&e[n]==='"')n++;else break;else n++;continue}t+=r,n++}return t}function Cs(e){return ut(Ts(e))}function _n(e){let t=x(e);if(t.length===0)return!1;return t.every((n)=>Cs(n)==="read")}function Ts(e){return F(e).replace(/\s+/g," ").trim().toUpperCase()}function ut(e){let t=e.replace(/^[(\s]+/,""),n=t.match(/^[A-Z_]+/)?.[0];if(!n)return"unknown";if(/\bSET_CONFIG\s*\(/.test(t))return"unknown";if(n==="WITH"){let r=As(t);if(r===null)return"unknown";let s=vs(t.slice(0,r));if(s!=="read")return s;return ut(t.slice(r))}if(n==="EXPLAIN")return Ns(t);if(n==="PRAGMA")return Rs(t);if(n==="COPY")return/\bFROM\b/.test(t)?"write":"unknown";if(n==="SELECT"&&/\bINTO\b/.test(t))return"unknown";if(ys.has(n))return"read";if(ws.has(n))return"write";if(Dn.has(n))return"ddl";return"unknown"}function As(e){let t=0,n=-1;for(let r=0;r<=e.length;r++){let s=r<e.length?e[r]:" ";if(s==="("||s===")"){t+=s==="("?1:-1,n=-1;continue}if(/[A-Z0-9_]/.test(s)){if(n===-1)n=r;continue}if(n!==-1&&t===0&&Ss.has(e.slice(n,r)))return n;n=-1}return null}function vs(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===")"){t--;continue}if(r!=="(")continue;if(t++,t!==1)continue;let s=e.slice(n+1).match(/^\s*([A-Z_]+)/)?.[1];if(!s)continue;if(Es.has(s))return"write";if(Dn.has(s))return"ddl";if(s==="WITH")return"unknown"}return"read"}function Rs(e){if(e.includes("="))return"unknown";let t=e.match(/^PRAGMA\s+(?:[A-Z0-9_]+\s*\.\s*)?([A-Z0-9_]+)\s*(\()?/);if(!t)return"unknown";if(!t[2])return"read";return bs.has(t[1])?"read":"unknown"}function Ns(e){let t=e.slice(7).trim(),n=!1;if(t.startsWith("(")){let r=Ds(t);if(r===-1)return"unknown";let s=t.slice(1,r);n=/\bANALYZE\b/.test(s)&&!/\bANALYZE\s+(FALSE|OFF|0)\b/.test(s),t=t.slice(r+1).trim()}else while(!0){let r=t.match(/^(ANALYZE|VERBOSE|QUERY PLAN|EXTENDED|PARTITIONS|FORMAT\s*=\s*[A-Z]+)\b\s*/);if(!r)break;if(r[1]==="ANALYZE")n=!0;t=t.slice(r[0].length)}if(!n)return"read";if(t.length===0)return"unknown";return ut(t)}function Ds(e){let t=0;for(let n=0;n<e.length;n++)if(e[n]==="(")t++;else if(e[n]===")"&&--t===0)return n;return-1}function xe(e,t){if(!e||typeof e!=="object")return;let n=e;if(n.position!=null){let r=Number(n.position);if(!Number.isNaN(r)&&r>0){let{line:s,column:i}=Ie(t,r);return{line:s,column:i,offset:r}}}if(e instanceof Error){let r=e.message.match(/at offset (\d+)/);if(r){let s=Number(r[1])+1,{line:i,column:o}=Ie(t,s);return{line:i,column:o,offset:s}}}return}var ys,ws,Dn,Ss,Es,bs;var H=C(()=>{ys=new Set(["SELECT","SHOW","DESCRIBE","DESC","VALUES","TABLE"]),ws=new Set(["INSERT","UPDATE","DELETE","MERGE","REPLACE","TRUNCATE","CALL","DO"]),Dn=new Set(["CREATE","ALTER","DROP","GRANT","REVOKE","VACUUM","REINDEX","ATTACH","DETACH"]),Ss=new Set(["SELECT","INSERT","UPDATE","DELETE","MERGE","REPLACE","VALUES","TABLE"]),Es=new Set(["INSERT","UPDATE","DELETE","MERGE","REPLACE"]),bs=new Set(["TABLE_INFO","TABLE_XINFO","TABLE_LIST","INDEX_LIST","INDEX_INFO","INDEX_XINFO","FOREIGN_KEY_LIST","FOREIGN_KEY_CHECK","DATABASE_LIST","COLLATION_LIST","FUNCTION_LIST","MODULE_LIST","PRAGMA_LIST","COMPILE_OPTIONS","INTEGRITY_CHECK","QUICK_CHECK"])});function Pe(e,t){if(t===void 0)return In.every((r)=>Pe(e,r));let n=xn(e,t,{allowComments:!0});if(n===null)return!1;for(let r=0;r<n.length;r++){if(n[r]!==";")continue;for(let s=r+1;s<n.length;s++){let i=n[s];if(i===";"||i===" "||i==="\t"||i===`
36
+ `||i==="\r"||i==="\f"||i==="\v")continue;return!1}return!0}return!0}function pt(e,t){if(t===void 0)return In.every((s)=>pt(e,s));let n=xn(e,t,{allowComments:!1});if(n===null)return!1;let r=0;for(let s of n){if(s===";")return!1;if(s==="(")r++;if(s===")"&&--r<0)return!1}return r===0}function xn(e,t,n){let r=t==="mysql",s=t==="postgresql",i=t==="sqlite",o=r||s,a=r,c=s,u=r||i,l=i,d=r,f=r,h="",p=0,g=e.length;while(p<g){let y=e[p],S=p+1<g?e[p+1]:"";if(y==="-"&&S==="-"){let m=!0;if(f&&p+2<g){let w=e.charCodeAt(p+2);if(w>127)return null;m=w<=32||w===127}if(m){if(!n.allowComments)return null;let w=On(e,p);if(w===null)return null;h+=" ",p=w;continue}}if(y==="#"&&d){if(!n.allowComments)return null;let m=On(e,p);if(m===null)return null;h+=" ",p=m;continue}if(y==="/"&&S==="*"){if(!n.allowComments)return null;if(r&&/^[!+]|^[Mm]!/.test(e.slice(p+2,p+4)))return null;if(s){let w=0,E=p;while(E<g)if(e[E]==="/"&&e[E+1]==="*")w++,E+=2;else if(e[E]==="*"&&e[E+1]==="/"){if(w--,E+=2,w===0)break}else E++;if(w!==0)return null;h+=" ",p=E;continue}let m=e.indexOf("*/",p+2);h+=" ",p=m===-1?g:m+2;continue}if(y==="$"&&c){let m=_s(e,p);if(m){let w=p>0?e[p-1]:"";if(Z(w)||w==="$")return null;let E=e.indexOf(m,p+m.length);if(E===-1)return null;h+=" ",p=E+m.length;continue}}if(i&&(y==="$"||y==="@"||y===":"||y==="#")){let m=p+1,w=0;while(m<g)if(Z(e[m])||e[m]==="$")w++,m++;else if(e[m]===":"&&e[m+1]===":")m+=2;else break;if(e[m]==="("&&w>0)return null}if(y==="'"){let m=dt(e,p,"'",o);if(m===-1)return null;h+=" ",p=m;continue}if(y==='"'){let m=dt(e,p,'"',a);if(m===-1)return null;h+=" ",p=m;continue}if(y==="`"&&u){let m=dt(e,p,"`",!1);if(m===-1)return null;h+=" ",p=m;continue}if(y==="["&&l){let m=e.indexOf("]",p+1);if(m===-1)return null;h+=" ",p=m+1;continue}h+=y,p++}return h}function On(e,t){for(let n=t;n<e.length;n++){if(e[n]===`
37
37
  `)return n+1;if(e[n]==="\r"&&e[n+1]!==`
38
- `)return null}return e.length}function es(e,t){if(e[t]!=="$")return null;let n=e.charCodeAt(t+1);if(n>=48&&n<=57)return null;let r=t+1;while(r<e.length&&j(e[r]))r++;if(e[r]!=="$")return null;return e.slice(t,r+1)}function it(e,t,n,r){let s=t+1;while(s<e.length){let i=e[s];if(r&&i==="\\")return-1;if(i===n){if(e[s+1]===n){s+=2;continue}return s+1}s++}return-1}var Sn;var at=T(()=>{G();Sn=["postgresql","mysql","sqlite"]});async function ae(e,t){let n=`__ephemeral_${crypto.randomUUID()}`;await e.reserveSession(n);try{return await t(n)}finally{try{await e.cancel(n)}catch{}try{await e.releaseSession(n)}catch{}}}class bn{logs=new Map;pendingCounts=new Map;key(e,t){return t?`${e}:${t}`:e}pendingKey(e,t,n){let r=this.key(e,t);return n?`${r}:${n}`:r}add(e,t,n,r,s,i,o,a){let c=this.key(e,o);if(!this.logs.has(c))this.logs.set(c,[]);this.logs.get(c).push({id:crypto.randomUUID(),sql:t,status:n,durationMs:r,rowCount:s,errorMessage:i,executedAt:new Date().toISOString()});let u=this.pendingKey(e,o,a);this.pendingCounts.set(u,(this.pendingCounts.get(u)??0)+1);let l=t.trim().toUpperCase();if(/^(COMMIT|END|ROLLBACK)\b/.test(l)&&!/^ROLLBACK\s+TO\b/.test(l))this.resetPendingCount(e,o,a);else if(/^(BEGIN|START\s+TRANSACTION)\b/.test(l))this.resetPendingCount(e,o,a)}getEntries(e,t){return this.logs.get(this.key(e,t))??[]}getPendingCount(e,t,n){return this.pendingCounts.get(this.pendingKey(e,t,n))??0}resetPendingCount(e,t,n){this.pendingCounts.delete(this.pendingKey(e,t,n))}clear(e,t){let n=this.key(e,t);this.logs.delete(n),this.pendingCounts.delete(n);let r=`${n}:`;for(let s of this.pendingCounts.keys())if(s.startsWith(r))this.pendingCounts.delete(s)}}function us(e){let t=z(e).replace(/\s+/g," ").trim().toUpperCase();return/^(BEGIN|START TRANSACTION|COMMIT|END|ROLLBACK|ABORT)\b/.test(t)&&!/^ROLLBACK TO\b/.test(t)&&!/^(COMMIT|ROLLBACK) PREPARED\b/.test(t)}function Ie(e,t,n){if(n===void 0||!e.isSessionReadOnly(n))return;if(!_e(t,e.getDriverType()))throw new b("READ_ONLY_SESSION",En);if(gn(t))return;throw new b("READ_ONLY_SESSION",En)}class ce{connectionManager;runningQueries=new Map;defaultTimeoutMs;appDb;sessionLog=new bn;constructor(e,t=30000,n){this.connectionManager=e,this.defaultTimeoutMs=t,this.appDb=n}async executeQuery(e,t,n,r,s,i,o,a){let c=this.connectionManager.getDriver(e,i),u=H(t);if(u.length===0)return[];if(Ie(c,t,o),!o&&u.some(us))return[{columns:[],rows:[],rowCount:0,durationMs:0,error:"Transaction control statements (BEGIN, COMMIT, ROLLBACK) require a session. Open a session tab to use manual transactions."}];let l=async(m)=>{let f=s??crypto.randomUUID(),g={queryId:f,connectionId:e,database:i,cancelled:!1,sessionId:m};this.runningQueries.set(f,g);let d=r??this.defaultTimeoutMs,h=[],y;try{if(a&&m!==void 0){y=(await c.execute("SHOW search_path",void 0,m)).rows[0]?.search_path;let p=Oe(a,c);await c.execute(`SET search_path TO ${p}`,void 0,m)}for(let w of u){if(g.cancelled){h.push(ct());break}let p=await this.executeSingle(c,w,u.length===1?n:void 0,d,g,m);if(h.push(p),p.error)break}}finally{if(y!==void 0&&m!==void 0)try{let w=Oe(y,c);await c.execute(`SET search_path TO ${w}`,void 0,m)}catch{}this.runningQueries.delete(f),this.logHistory(e,t,h,i,o)}return h};if(!o&&(u.length>1||a))return ae(c,l);return l(o)}async cancelQuery(e){let t=this.runningQueries.get(e);if(!t)return!1;t.cancelled=!0;try{let n=this.connectionManager.getDriver(t.connectionId,t.database);if(t.sessionId!==void 0)await n.cancel(t.sessionId);else await n.cancel(void 0,t.poolQueryKey)}catch(n){console.debug("Cancel query failed (driver may have completed):",n instanceof Error?n.message:n)}return!0}async cancelAllForConnection(e){let t=[];for(let[r,s]of this.runningQueries)if(s.connectionId===e)t.push(r);let n=0;for(let r of t)if(await this.cancelQuery(r))n++;return n}getRunningQueryIds(){return[...this.runningQueries.keys()]}async explainQuery(e,t,n,r,s,i){let o=this.connectionManager.getDriver(e,r),a=o.getDriverType();if(!_e(t,a))throw Error("EXPLAIN takes a single statement \u2014 select the one to explain");Ie(o,`EXPLAIN ${n?"ANALYZE ":""}${t}`,s);let c=performance.now(),u=async(l)=>{let m;try{if(i&&l!==void 0){m=(await o.execute("SHOW search_path",void 0,l)).rows[0]?.search_path;let N=Oe(i,o);await o.execute(`SET search_path TO ${N}`,void 0,l)}if(a==="sqlite"){let C=l!==void 0?await o.execute(`EXPLAIN QUERY PLAN ${t}`,void 0,l):await o.execute(`EXPLAIN QUERY PLAN ${t}`),N=Math.round(performance.now()-c),v=ds(C.rows),L=C.rows.map((q)=>`${q.id}|${q.parent}|${q.notused??0}|${q.detail}`).join(`
39
- `);return{nodes:v,rawText:L,durationMs:N}}let f=a==="mysql",g=f?n?"EXPLAIN ANALYZE":"EXPLAIN FORMAT=JSON":n?"EXPLAIN (ANALYZE, FORMAT JSON)":"EXPLAIN (FORMAT JSON)",d=l!==void 0?await o.execute(`${g} ${t}`,void 0,l):await o.execute(`${g} ${t}`),h=Math.round(performance.now()-c),y,w,p;if(f&&n)return p=d.rows.map((C)=>Object.values(C)[0]).join(`
40
- `),w=[{operation:p,children:[]}],{nodes:w,rawText:p,durationMs:h};let S=d.rows[0]?.["QUERY PLAN"]??d.rows[0]?.EXPLAIN??JSON.stringify(d.rows);if(y=typeof S==="string"?JSON.parse(S):S,w=(Array.isArray(y)?y:[y]).map((C)=>Cn(C.Plan??C)),n)p=JSON.stringify(y,null,2);else try{p=(l!==void 0?await o.execute(`EXPLAIN ${t}`,void 0,l):await o.execute(`EXPLAIN ${t}`)).rows.map((v)=>Object.values(v)[0]).join(`
41
- `)}catch{p=JSON.stringify(y,null,2)}return{nodes:w,rawText:p,durationMs:h}}catch(f){let g=Math.round(performance.now()-c);return{nodes:[],rawText:"",durationMs:g,error:f instanceof Error?f.message:String(f)}}finally{if(m!==void 0&&l!==void 0)try{let f=Oe(m,o);await o.execute(`SET search_path TO ${f}`,void 0,l)}catch{}}};if(!s&&i)return ae(o,u);return u(s)}async executeSingle(e,t,n,r,s,i){let o=performance.now(),c=r===0?null:this.createTimeout(r),u=i===void 0?Symbol():void 0;s.poolQueryKey=u;try{let l=i!==void 0?e.execute(t,n,i):e.execute(t,n,void 0,u),m=c?await Promise.race([l,c.promise]):await l;if(s.cancelled)return ct(performance.now()-o);return{...m,durationMs:Math.round(performance.now()-o)}}catch(l){let m=Math.round(performance.now()-o);if(c?.fired)try{if(i!==void 0)await e.cancel(i);else await e.cancel(void 0,u)}catch{}if(s.cancelled)return ct(m);if(c?.fired){let d=t.trim().toUpperCase();if(/^(COMMIT|END)\b/.test(d))return{columns:[],rows:[],rowCount:0,durationMs:m,errorCode:"COMMIT_UNCERTAIN",error:"Connection lost or timed out during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying."};if(/^(INSERT|UPDATE|DELETE|MERGE)\b/.test(d))return{columns:[],rows:[],rowCount:0,durationMs:m,errorCode:"STATEMENT_UNCERTAIN",error:"Statement timed out but may have been executed by the server. Verify your data before retrying."}}let f=De(l,t),g=l instanceof b?l.code:void 0;return{columns:[],rows:[],rowCount:0,durationMs:m,error:l instanceof Error?l.message:String(l),errorCode:g,errorPosition:f}}finally{c?.cancel()}}createTimeout(e){let t,n=!1;return{promise:new Promise((s,i)=>{t=setTimeout(()=>{n=!0,i(Error(`Query timed out after ${e}ms`))},e)}),cancel:()=>clearTimeout(t),get fired(){return n}}}logHistory(e,t,n,r,s){let i=n.some((u)=>u.error),o=n.reduce((u,l)=>u+(l.durationMs??0),0),a=n.reduce((u,l)=>u+Re(l),0),c=n.find((u)=>u.error)?.error;if(this.sessionLog.add(e,t,i?"error":"success",Math.round(o),a,c,r,s),!this.appDb)return;try{this.appDb.addHistory({connectionId:e,database:r,sql:t,status:i?"error":"success",durationMs:Math.round(o),rowCount:a,errorMessage:c})}catch(u){console.debug("History logging failed:",u instanceof Error?u.message:u)}}}function ct(e=0){return{columns:[],rows:[],rowCount:0,durationMs:Math.round(e),error:"Query was cancelled"}}function Oe(e,t){return e.split(",").map((n)=>{let r=n.trim();if(r.startsWith('"')&&r.endsWith('"'))r=r.slice(1,-1).replace(/""/g,'"');return t.quoteIdentifier(r)}).join(", ")}function Cn(e){let t=e.Plans??[],{"Node Type":n,"Relation Name":r,Plans:s,...i}=e;return{operation:String(e["Node Type"]??"Unknown"),relation:e["Relation Name"]?String(e["Relation Name"]):void 0,cost:typeof e["Total Cost"]==="number"?e["Total Cost"]:void 0,actualTime:typeof e["Actual Total Time"]==="number"?e["Actual Total Time"]:void 0,estimatedRows:typeof e["Plan Rows"]==="number"?e["Plan Rows"]:void 0,actualRows:typeof e["Actual Rows"]==="number"?e["Actual Rows"]:void 0,extra:Object.keys(i).length>0?i:void 0,children:t.map((o)=>Cn(o))}}function ds(e){let t=new Map,n=new Map;for(let r of e){let s=Number(r.id??r.selectid??0),i=Number(r.parent??0),o=String(r.detail??""),a={operation:o,children:[]},c=o.match(/^(SCAN|SEARCH|USE TEMP B-TREE)\s+(.*)/i);if(c){a.operation=c[1];let l=c[2].match(/^(\S+)/);if(l)a.relation=l[1]}if(t.set(s,a),!n.has(i))n.set(i,[]);n.get(i).push(a)}for(let[r,s]of t)s.children=n.get(r)??[];return n.get(0)??[...t.values()].filter((r,s)=>{let i=e[s],o=Number(i?.parent??0);return!t.has(o)})}var En="This session is read-only and cannot execute writes. Submit the statement with `dotaz propose` so it can be approved and run in the app.";var xe=T(()=>{at();G();P();Ce();G()});function V(e){switch(e.type){case"postgresql":return e.database;case"sqlite":return e.path;case"mysql":return e.database}}function k(e){return U[e.type].hasHost}function Tn(e){if(!k(e))return e;let t={...e,password:""};if(t.type==="postgresql"&&t.sshTunnel)t.sshTunnel={...t.sshTunnel,password:t.sshTunnel.password!==void 0?"":void 0,keyPassphrase:t.sshTunnel.keyPassphrase!==void 0?"":void 0};return t}function An(e,t){if(!k(e))return e;let n={...e,password:t.password??e.password??""};if(n.type==="postgresql"&&n.sshTunnel)n.sshTunnel={...n.sshTunnel,password:t.sshPassword??n.sshTunnel.password,keyPassphrase:t.sshKeyPassphrase??n.sshTunnel.keyPassphrase};return n}var U;var le=T(()=>{U={postgresql:{label:"PostgreSQL",hasPassword:!0,hasHost:!0,defaultPort:5432,supportsMultiDatabase:!0},sqlite:{label:"SQLite",hasPassword:!1,hasHost:!1,supportsMultiDatabase:!1},mysql:{label:"MySQL",hasPassword:!0,hasHost:!0,defaultPort:3306,supportsMultiDatabase:!0}}});import{createCipheriv as ms,createDecipheriv as ps,hkdfSync as io,randomBytes as fs}from"crypto";class dt{keyPromise;constructor(e){this.keyPromise=gs(e)}async encrypt(e){let t=await this.keyPromise,n=crypto.getRandomValues(new Uint8Array(lt)),r=new TextEncoder().encode(e),s=await crypto.subtle.encrypt({name:ut,iv:n},t,r),i=new Uint8Array(n.length+s.byteLength);return i.set(n,0),i.set(new Uint8Array(s),n.length),Buffer.from(i).toString("base64")}async decrypt(e){let t=await this.keyPromise,n=new Uint8Array(Buffer.from(e,"base64")),r=n.slice(0,lt),s=n.slice(lt),i=await crypto.subtle.decrypt({name:ut,iv:r},t,s);return new TextDecoder().decode(i)}}async function gs(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new TextEncoder().encode("dotaz-encryption-salt"),info:new TextEncoder().encode("dotaz-aes-key")},n,{name:ut,length:hs},!1,["encrypt","decrypt"])}function J(e,t){let n=new Uint8Array(fs(ue)),r=ms("aes-256-gcm",t,n),s=r.update(e,"utf8"),i=r.final(),o=new Uint8Array(r.getAuthTag()),a=new Uint8Array(s.length+i.length);a.set(s,0),a.set(i,s.length);let c=new Uint8Array(n.length+o.length+a.length);return c.set(n,0),c.set(o,n.length),c.set(a,n.length+o.length),Le+Buffer.from(c).toString("base64")}function ys(e,t){if(!e.startsWith(Le))return e;let n=new Uint8Array(Buffer.from(e.slice(Le.length),"base64")),r=n.subarray(0,ue),s=n.subarray(ue,ue+vn),i=n.subarray(ue+vn),o=ps("aes-256-gcm",t,r);return o.setAuthTag(s),o.update(i).toString("utf8")+o.final("utf8")}function de(e){return e.startsWith(Le)}function Pe(e,t){try{return ys(e,t)}catch{return null}}var ut="AES-GCM",lt=12,hs=256,Le="enc:v1:",ue=12,vn=16;var mt=()=>{};function ws(e){e.run(`
38
+ `)return null}return e.length}function _s(e,t){if(e[t]!=="$")return null;let n=e.charCodeAt(t+1);if(n>=48&&n<=57)return null;let r=t+1;while(r<e.length&&Z(e[r]))r++;if(e[r]!=="$")return null;return e.slice(t,r+1)}function dt(e,t,n,r){let s=t+1;while(s<e.length){let i=e[s];if(r&&i==="\\")return-1;if(i===n){if(e[s+1]===n){s+=2;continue}return s+1}s++}return-1}var In;var mt=C(()=>{H();In=["postgresql","mysql","sqlite"]});async function de(e,t){let n=`__ephemeral_${crypto.randomUUID()}`;await e.reserveSession(n);try{return await t(n)}finally{try{await e.cancel(n)}catch{}try{await e.releaseSession(n)}catch{}}}class Ln{logs=new Map;pendingCounts=new Map;key(e,t){return t?`${e}:${t}`:e}pendingKey(e,t,n){let r=this.key(e,t);return n?`${r}:${n}`:r}add(e,t,n,r,s,i,o,a){let c=this.key(e,o);if(!this.logs.has(c))this.logs.set(c,[]);this.logs.get(c).push({id:crypto.randomUUID(),sql:t,status:n,durationMs:r,rowCount:s,errorMessage:i,executedAt:new Date().toISOString()});let u=this.pendingKey(e,o,a);this.pendingCounts.set(u,(this.pendingCounts.get(u)??0)+1);let l=t.trim().toUpperCase();if(/^(COMMIT|END|ROLLBACK)\b/.test(l)&&!/^ROLLBACK\s+TO\b/.test(l))this.resetPendingCount(e,o,a);else if(/^(BEGIN|START\s+TRANSACTION)\b/.test(l))this.resetPendingCount(e,o,a)}getEntries(e,t){return this.logs.get(this.key(e,t))??[]}getPendingCount(e,t,n){return this.pendingCounts.get(this.pendingKey(e,t,n))??0}resetPendingCount(e,t,n){this.pendingCounts.delete(this.pendingKey(e,t,n))}clear(e,t){let n=this.key(e,t);this.logs.delete(n),this.pendingCounts.delete(n);let r=`${n}:`;for(let s of this.pendingCounts.keys())if(s.startsWith(r))this.pendingCounts.delete(s)}}function $s(e){let t=F(e).replace(/\s+/g," ").trim().toUpperCase();return/^(BEGIN|START TRANSACTION|COMMIT|END|ROLLBACK|ABORT)\b/.test(t)&&!/^ROLLBACK TO\b/.test(t)&&!/^(COMMIT|ROLLBACK) PREPARED\b/.test(t)}function ke(e,t,n){if(n===void 0||!e.isSessionReadOnly(n))return;if(!Pe(t,e.getDriverType()))throw new b("READ_ONLY_SESSION",Pn);if(_n(t))return;throw new b("READ_ONLY_SESSION",Pn)}class pe{connectionManager;runningQueries=new Map;defaultTimeoutMs;appDb;sessionLog=new Ln;constructor(e,t=30000,n){this.connectionManager=e,this.defaultTimeoutMs=t,this.appDb=n}async executeQuery(e,t,n,r,s,i,o,a){let c=this.connectionManager.getDriver(e,i),u=x(t);if(u.length===0)return[];if(ke(c,t,o),!o&&u.some($s))return[{columns:[],rows:[],rowCount:0,durationMs:0,error:"Transaction control statements (BEGIN, COMMIT, ROLLBACK) require a session. Open a session tab to use manual transactions."}];let l=async(d)=>{let f=s??crypto.randomUUID(),h={queryId:f,connectionId:e,database:i,cancelled:!1,sessionId:d};this.runningQueries.set(f,h);let p=r??this.defaultTimeoutMs,g=[],y;try{if(a&&d!==void 0){y=(await c.execute("SHOW search_path",void 0,d)).rows[0]?.search_path;let m=Le(a,c);await c.execute(`SET search_path TO ${m}`,void 0,d)}for(let S of u){if(h.cancelled){g.push(ft());break}let m=await this.executeSingle(c,S,u.length===1?n:void 0,p,h,d);if(g.push(m),m.error)break}}finally{if(y!==void 0&&d!==void 0)try{let S=Le(y,c);await c.execute(`SET search_path TO ${S}`,void 0,d)}catch{}this.runningQueries.delete(f),this.logHistory(e,t,g,i,o)}return g};if(!o&&(u.length>1||a))return de(c,l);return l(o)}async cancelQuery(e){let t=this.runningQueries.get(e);if(!t)return!1;t.cancelled=!0;try{let n=this.connectionManager.getDriver(t.connectionId,t.database);if(t.sessionId!==void 0)await n.cancel(t.sessionId);else await n.cancel(void 0,t.poolQueryKey)}catch(n){console.debug("Cancel query failed (driver may have completed):",n instanceof Error?n.message:n)}return!0}async cancelAllForConnection(e){let t=[];for(let[r,s]of this.runningQueries)if(s.connectionId===e)t.push(r);let n=0;for(let r of t)if(await this.cancelQuery(r))n++;return n}getRunningQueryIds(){return[...this.runningQueries.keys()]}async explainQuery(e,t,n,r,s,i){let o=this.connectionManager.getDriver(e,r),a=o.getDriverType();if(!Pe(t,a))throw Error("EXPLAIN takes a single statement \u2014 select the one to explain");ke(o,`EXPLAIN ${n?"ANALYZE ":""}${t}`,s);let c=performance.now(),u=async(l)=>{let d;try{if(i&&l!==void 0){d=(await o.execute("SHOW search_path",void 0,l)).rows[0]?.search_path;let D=Le(i,o);await o.execute(`SET search_path TO ${D}`,void 0,l)}if(a==="sqlite"){let T=l!==void 0?await o.execute(`EXPLAIN QUERY PLAN ${t}`,void 0,l):await o.execute(`EXPLAIN QUERY PLAN ${t}`),D=Math.round(performance.now()-c),R=Fs(T.rows),U=T.rows.map((j)=>`${j.id}|${j.parent}|${j.notused??0}|${j.detail}`).join(`
39
+ `);return{nodes:R,rawText:U,durationMs:D}}let f=a==="mysql",h=f?n?"EXPLAIN ANALYZE":"EXPLAIN FORMAT=JSON":n?"EXPLAIN (ANALYZE, FORMAT JSON)":"EXPLAIN (FORMAT JSON)",p=l!==void 0?await o.execute(`${h} ${t}`,void 0,l):await o.execute(`${h} ${t}`),g=Math.round(performance.now()-c),y,S,m;if(f&&n)return m=p.rows.map((T)=>Object.values(T)[0]).join(`
40
+ `),S=[{operation:m,children:[]}],{nodes:S,rawText:m,durationMs:g};let w=p.rows[0]?.["QUERY PLAN"]??p.rows[0]?.EXPLAIN??JSON.stringify(p.rows);if(y=typeof w==="string"?JSON.parse(w):w,S=(Array.isArray(y)?y:[y]).map((T)=>kn(T.Plan??T)),n)m=JSON.stringify(y,null,2);else try{m=(l!==void 0?await o.execute(`EXPLAIN ${t}`,void 0,l):await o.execute(`EXPLAIN ${t}`)).rows.map((R)=>Object.values(R)[0]).join(`
41
+ `)}catch{m=JSON.stringify(y,null,2)}return{nodes:S,rawText:m,durationMs:g}}catch(f){let h=Math.round(performance.now()-c);return{nodes:[],rawText:"",durationMs:h,error:f instanceof Error?f.message:String(f)}}finally{if(d!==void 0&&l!==void 0)try{let f=Le(d,o);await o.execute(`SET search_path TO ${f}`,void 0,l)}catch{}}};if(!s&&i)return de(o,u);return u(s)}async executeSingle(e,t,n,r,s,i){let o=performance.now(),c=r===0?null:this.createTimeout(r),u=i===void 0?Symbol():void 0;s.poolQueryKey=u;try{let l=i!==void 0?e.execute(t,n,i):e.execute(t,n,void 0,u),d=c?await Promise.race([l,c.promise]):await l;if(s.cancelled)return ft(performance.now()-o);return{...d,durationMs:Math.round(performance.now()-o)}}catch(l){let d=Math.round(performance.now()-o);if(c?.fired)try{if(i!==void 0)await e.cancel(i);else await e.cancel(void 0,u)}catch{}if(s.cancelled)return ft(d);if(c?.fired){let p=t.trim().toUpperCase();if(/^(COMMIT|END)\b/.test(p))return{columns:[],rows:[],rowCount:0,durationMs:d,errorCode:"COMMIT_UNCERTAIN",error:"Connection lost or timed out during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying."};if(/^(INSERT|UPDATE|DELETE|MERGE)\b/.test(p))return{columns:[],rows:[],rowCount:0,durationMs:d,errorCode:"STATEMENT_UNCERTAIN",error:"Statement timed out but may have been executed by the server. Verify your data before retrying."}}let f=xe(l,t),h=l instanceof b?l.code:void 0;return{columns:[],rows:[],rowCount:0,durationMs:d,error:l instanceof Error?l.message:String(l),errorCode:h,errorPosition:f}}finally{c?.cancel()}}createTimeout(e){let t,n=!1;return{promise:new Promise((s,i)=>{t=setTimeout(()=>{n=!0,i(Error(`Query timed out after ${e}ms`))},e)}),cancel:()=>clearTimeout(t),get fired(){return n}}}logHistory(e,t,n,r,s){let i=n.some((u)=>u.error),o=n.reduce((u,l)=>u+(l.durationMs??0),0),a=n.reduce((u,l)=>u+Oe(l),0),c=n.find((u)=>u.error)?.error;if(this.sessionLog.add(e,t,i?"error":"success",Math.round(o),a,c,r,s),!this.appDb)return;try{this.appDb.addHistory({connectionId:e,database:r,sql:t,status:i?"error":"success",durationMs:Math.round(o),rowCount:a,errorMessage:c})}catch(u){console.debug("History logging failed:",u instanceof Error?u.message:u)}}}function ft(e=0){return{columns:[],rows:[],rowCount:0,durationMs:Math.round(e),error:"Query was cancelled"}}function Le(e,t){return e.split(",").map((n)=>{let r=n.trim();if(r.startsWith('"')&&r.endsWith('"'))r=r.slice(1,-1).replace(/""/g,'"');return t.quoteIdentifier(r)}).join(", ")}function kn(e){let t=e.Plans??[],{"Node Type":n,"Relation Name":r,Plans:s,...i}=e;return{operation:String(e["Node Type"]??"Unknown"),relation:e["Relation Name"]?String(e["Relation Name"]):void 0,cost:typeof e["Total Cost"]==="number"?e["Total Cost"]:void 0,actualTime:typeof e["Actual Total Time"]==="number"?e["Actual Total Time"]:void 0,estimatedRows:typeof e["Plan Rows"]==="number"?e["Plan Rows"]:void 0,actualRows:typeof e["Actual Rows"]==="number"?e["Actual Rows"]:void 0,extra:Object.keys(i).length>0?i:void 0,children:t.map((o)=>kn(o))}}function Fs(e){let t=new Map,n=new Map;for(let r of e){let s=Number(r.id??r.selectid??0),i=Number(r.parent??0),o=String(r.detail??""),a={operation:o,children:[]},c=o.match(/^(SCAN|SEARCH|USE TEMP B-TREE)\s+(.*)/i);if(c){a.operation=c[1];let l=c[2].match(/^(\S+)/);if(l)a.relation=l[1]}if(t.set(s,a),!n.has(i))n.set(i,[]);n.get(i).push(a)}for(let[r,s]of t)s.children=n.get(r)??[];return n.get(0)??[...t.values()].filter((r,s)=>{let i=e[s],o=Number(i?.parent??0);return!t.has(o)})}var Pn="This session is read-only and cannot execute writes. Submit the statement with `dotaz propose` so it can be approved and run in the app.";var Me=C(()=>{mt();H();q();Re();H()});function ee(e){switch(e.type){case"postgresql":return e.database;case"sqlite":return e.path;case"mysql":return e.database}}function B(e){return Y[e.type].hasHost}function Mn(e){if(!B(e))return e;let t={...e,password:""};if(t.type==="postgresql"&&t.sshTunnel)t.sshTunnel={...t.sshTunnel,password:t.sshTunnel.password!==void 0?"":void 0,keyPassphrase:t.sshTunnel.keyPassphrase!==void 0?"":void 0};return t}function Un(e,t){if(!B(e))return e;let n={...e,password:t.password??e.password??""};if(n.type==="postgresql"&&n.sshTunnel)n.sshTunnel={...n.sshTunnel,password:t.sshPassword??n.sshTunnel.password,keyPassphrase:t.sshKeyPassphrase??n.sshTunnel.keyPassphrase};return n}var Y;var me=C(()=>{Y={postgresql:{label:"PostgreSQL",hasPassword:!0,hasHost:!0,defaultPort:5432,supportsMultiDatabase:!0},sqlite:{label:"SQLite",hasPassword:!1,hasHost:!1,supportsMultiDatabase:!1},mysql:{label:"MySQL",hasPassword:!0,hasHost:!0,defaultPort:3306,supportsMultiDatabase:!0}}});import{createCipheriv as Hs,createDecipheriv as Bs,hkdfSync as Ea,randomBytes as Qs}from"crypto";class yt{keyPromise;constructor(e){this.keyPromise=Ys(e)}async encrypt(e){let t=await this.keyPromise,n=crypto.getRandomValues(new Uint8Array(ht)),r=new TextEncoder().encode(e),s=await crypto.subtle.encrypt({name:gt,iv:n},t,r),i=new Uint8Array(n.length+s.byteLength);return i.set(n,0),i.set(new Uint8Array(s),n.length),Buffer.from(i).toString("base64")}async decrypt(e){let t=await this.keyPromise,n=new Uint8Array(Buffer.from(e,"base64")),r=n.slice(0,ht),s=n.slice(ht),i=await crypto.subtle.decrypt({name:gt,iv:r},t,s);return new TextDecoder().decode(i)}}async function Ys(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new TextEncoder().encode("dotaz-encryption-salt"),info:new TextEncoder().encode("dotaz-aes-key")},n,{name:gt,length:Ks},!1,["encrypt","decrypt"])}function te(e,t){let n=new Uint8Array(Qs(fe)),r=Hs("aes-256-gcm",t,n),s=r.update(e,"utf8"),i=r.final(),o=new Uint8Array(r.getAuthTag()),a=new Uint8Array(s.length+i.length);a.set(s,0),a.set(i,s.length);let c=new Uint8Array(n.length+o.length+a.length);return c.set(n,0),c.set(o,n.length),c.set(a,n.length+o.length),Ue+Buffer.from(c).toString("base64")}function js(e,t){if(!e.startsWith(Ue))return e;let n=new Uint8Array(Buffer.from(e.slice(Ue.length),"base64")),r=n.subarray(0,fe),s=n.subarray(fe,fe+qn),i=n.subarray(fe+qn),o=Bs("aes-256-gcm",t,r);return o.setAuthTag(s),o.update(i).toString("utf8")+o.final("utf8")}function he(e){return e.startsWith(Ue)}function qe(e,t){try{return js(e,t)}catch{return null}}var gt="AES-GCM",ht=12,Ks=256,Ue="enc:v1:",fe=12,qn=16;var wt=()=>{};function zs(e){e.run(`
42
42
  CREATE TABLE IF NOT EXISTS schema_version (
43
43
  version INTEGER PRIMARY KEY,
44
44
  applied_at TEXT NOT NULL DEFAULT (datetime('now'))
45
45
  )
46
- `)}function Es(e){return e.prepare("SELECT MAX(version) as version FROM schema_version").get()?.version??0}function Rn(e){ws(e);let t=Es(e),n=Ss.filter((r)=>r.version>t);for(let r of n){if(r.disableForeignKeys)e.run("PRAGMA foreign_keys = OFF");e.run("BEGIN");try{r.up(e),e.run("INSERT INTO schema_version (version) VALUES (?)",[r.version]),e.run("COMMIT")}catch(s){throw e.run("ROLLBACK"),s}if(r.disableForeignKeys)e.run("PRAGMA foreign_keys = ON")}return n.length}var Ss;var Nn=T(()=>{Ss=[{version:1,description:"Create connections, query_history, saved_views, settings tables",up:(e)=>{e.run(`
46
+ `)}function Vs(e){return e.prepare("SELECT MAX(version) as version FROM schema_version").get()?.version??0}function $n(e){zs(e);let t=Vs(e),n=Ws.filter((r)=>r.version>t);for(let r of n){if(r.disableForeignKeys)e.run("PRAGMA foreign_keys = OFF");e.run("BEGIN");try{r.up(e),e.run("INSERT INTO schema_version (version) VALUES (?)",[r.version]),e.run("COMMIT")}catch(s){throw e.run("ROLLBACK"),s}if(r.disableForeignKeys)e.run("PRAGMA foreign_keys = ON")}return n.length}var Ws;var Fn=C(()=>{Ws=[{version:1,description:"Create connections, query_history, saved_views, settings tables",up:(e)=>{e.run(`
47
47
  CREATE TABLE connections (
48
48
  id TEXT PRIMARY KEY,
49
49
  name TEXT NOT NULL,
@@ -114,8 +114,19 @@ ${a.join(`,
114
114
  INSERT INTO connections_new (id, name, type, config, created_at, updated_at, read_only, color, group_name)
115
115
  SELECT id, name, type, config, created_at, updated_at, read_only, color, group_name
116
116
  FROM connections
117
- `),e.run("DROP TABLE connections"),e.run("ALTER TABLE connections_new RENAME TO connections")}}]});import bs from"bun:sqlite";class me{db;localKey=null;constructor(e){this.db=new bs(e,{create:!0}),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA foreign_keys = ON"),Rn(this.db)}static getInstance(e){if(!X){let t=e??Cs();X=new me(t)}return X}static create(e){return new me(e)}close(){this.db.close()}transaction(e){return this.db.transaction(e)()}static resetInstance(){if(X)X.db.close(),X=null}setLocalKey(e,t){this.localKey=e,this.migratePasswords(t??null)}encryptConfigJson(e){if(this.localKey&&k(e)){let t={...e,password:J(e.password,this.localKey)};if(e.type==="postgresql"&&e.sshTunnel){let n={...e.sshTunnel};if(n.password)n.password=J(n.password,this.localKey);if(n.keyPassphrase)n.keyPassphrase=J(n.keyPassphrase,this.localKey);t={...t,sshTunnel:n}}return JSON.stringify(t)}return JSON.stringify(e)}decryptConfig(e){if(this.localKey&&k(e)&&de(e.password)){let t=(r)=>Pe(r,this.localKey)??"",n={...e,password:t(e.password)};if(e.type==="postgresql"&&e.sshTunnel){let r={...e.sshTunnel};if(r.password&&de(r.password))r.password=t(r.password);if(r.keyPassphrase&&de(r.keyPassphrase))r.keyPassphrase=t(r.keyPassphrase);n={...n,sshTunnel:r}}return n}return e}migratePasswords(e){if(!this.localKey)return;let t=this.localKey,n=(r)=>{if(!de(r))return{value:J(r,t),changed:!0};if(Pe(r,t)!==null)return{value:r,changed:!1};if(e){let s=Pe(r,e);if(s!==null)return{value:J(s,t),changed:!0}}return{value:r,changed:!1}};this.transaction(()=>{let r=this.db.prepare("SELECT id, config FROM connections").all(),s=this.db.prepare("UPDATE connections SET config = ? WHERE id = ?");for(let i of r)try{let o=JSON.parse(i.config);if(!k(o))continue;let a=!1,c={...o},u=n(o.password);if(u.changed)c={...c,password:u.value},a=!0;if(o.type==="postgresql"&&o.sshTunnel){let l={...o.sshTunnel},m=!1;if(l.password){let f=n(l.password);if(f.changed)l.password=f.value,m=!0}if(l.keyPassphrase){let f=n(l.keyPassphrase);if(f.changed)l.keyPassphrase=f.value,m=!0}if(m)c={...c,sshTunnel:l},a=!0}if(a)s.run(JSON.stringify(c),i.id)}catch{}})}toConnectionInfo(e){let t=On(e.config,`connection "${e.name}"`);return{id:e.id,name:e.name,config:this.decryptConfig(t),state:"disconnected",readOnly:e.read_only===1?!0:void 0,color:e.color??void 0,groupName:e.group_name??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}listConnections(){return this.db.prepare("SELECT * FROM connections ORDER BY group_name NULLS LAST, name").all().map((t)=>this.toConnectionInfo(t))}getConnectionById(e){let t=this.db.prepare("SELECT * FROM connections WHERE id = ?").get(e);return t?this.toConnectionInfo(t):null}createConnection(e){let t=crypto.randomUUID();return this.createConnectionWithId(t,e)}createConnectionWithId(e,t){let n=new Date().toISOString();return this.db.prepare("INSERT INTO connections (id, name, type, config, read_only, color, group_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e,t.name,t.config.type,this.encryptConfigJson(t.config),t.readOnly?1:0,t.color||null,t.groupName||null,n,n),this.getConnectionById(e)}updateConnection(e){let t=this.getConnectionById(e.id);if(!t)throw Error(`Connection not found: ${e.id}`);let n=new Date().toISOString();return this.db.prepare("UPDATE connections SET name = ?, type = ?, config = ?, read_only = ?, color = ?, group_name = ?, updated_at = ? WHERE id = ?").run(e.name,e.config.type,this.encryptConfigJson(e.config),e.readOnly??t.readOnly?1:0,e.color!==void 0?e.color||null:t.color??null,e.groupName!==void 0?e.groupName||null:t.groupName??null,n,e.id),this.getConnectionById(e.id)}setConnectionGroup(e,t){this.db.prepare("UPDATE connections SET group_name = ? WHERE id = ?").run(t,e);let n=this.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);return n}listConnectionGroups(){return this.db.prepare("SELECT DISTINCT group_name FROM connections WHERE group_name IS NOT NULL ORDER BY group_name").all().map((t)=>t.group_name)}renameConnectionGroup(e,t){this.db.prepare("UPDATE connections SET group_name = ? WHERE group_name = ?").run(t,e)}deleteConnectionGroup(e){this.db.prepare("UPDATE connections SET group_name = NULL WHERE group_name = ?").run(e)}setConnectionReadOnly(e,t){this.db.prepare("UPDATE connections SET read_only = ? WHERE id = ?").run(t?1:0,e);let n=this.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);return n}deleteConnection(e){this.db.prepare("DELETE FROM connections WHERE id = ?").run(e)}getSetting(e){return this.db.prepare("SELECT value FROM settings WHERE key = ?").get(e)?.value??null}getNumberSetting(e){let t=this.getSetting(e)??Z[e]??null;if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}getBooleanSetting(e){let t=this.getSetting(e)??Z[e]??null;if(t===null)return null;if(t==="true")return!0;if(t==="false")return!1;return null}setSetting(e,t){this.db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,t)}getAllSettings(){let e=this.db.prepare("SELECT key, value FROM settings").all(),t={};for(let n of e)t[n.key]=n.value;return t}listSavedViews(e,t,n){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? AND schema_name = ? AND table_name = ? ORDER BY name").all(e,t,n).map(pt)}createSavedView(e){let t=crypto.randomUUID(),n=new Date().toISOString();return this.db.prepare("INSERT INTO saved_views (id, connection_id, schema_name, table_name, name, config, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(t,e.connectionId,e.schemaName,e.tableName,e.name,JSON.stringify(e.config),n,n),this.getSavedViewById(t)}updateSavedView(e){let t=new Date().toISOString();this.db.prepare("UPDATE saved_views SET name = ?, config = ?, updated_at = ? WHERE id = ?").run(e.name,JSON.stringify(e.config),t,e.id);let n=this.getSavedViewById(e.id);if(!n)throw Error(`Saved view not found: ${e.id}`);return n}deleteSavedView(e){this.db.prepare("DELETE FROM saved_views WHERE id = ?").run(e)}listSavedViewsByConnection(e){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? ORDER BY table_name, name").all(e).map(pt)}getSavedViewById(e){let t=this.db.prepare("SELECT * FROM saved_views WHERE id = ?").get(e);return t?pt(t):null}addHistory(e){let t=this.db.prepare("INSERT INTO query_history (connection_id, database, sql, status, duration_ms, row_count, error_message) VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING *").get(e.connectionId,e.database??null,e.sql,e.status,e.durationMs??null,e.rowCount??null,e.errorMessage??null);return this.pruneHistory(),Dn(t)}pruneHistory(){let e=this.getNumberSetting("maxHistoryEntries");if(e===null||e<=0)return;this.db.prepare("DELETE FROM query_history WHERE id NOT IN (SELECT id FROM query_history ORDER BY executed_at DESC, id DESC LIMIT ?)").run(e)}listHistory(e){let t=e.limit??100,n=e.offset??0,r=[],s=[];if(e.connectionId)r.push("connection_id = ?"),s.push(e.connectionId);if(e.search)r.push("sql LIKE ?"),s.push(`%${e.search}%`);if(e.startDate)r.push("executed_at >= ?"),s.push(e.startDate+" 00:00:00");if(e.endDate){let c=new Date(e.endDate+"T00:00:00Z");c.setUTCDate(c.getUTCDate()+1);let u=c.getUTCFullYear(),l=String(c.getUTCMonth()+1).padStart(2,"0"),m=String(c.getUTCDate()).padStart(2,"0");r.push("executed_at < ?"),s.push(`${u}-${l}-${m} 00:00:00`)}let o=`SELECT * FROM query_history ${r.length>0?`WHERE ${r.join(" AND ")}`:""} ORDER BY executed_at DESC LIMIT ? OFFSET ?`;return s.push(t,n),this.db.prepare(o).all(...s).map(Dn)}clearHistory(e){if(e)this.db.prepare("DELETE FROM query_history WHERE connection_id = ?").run(e);else this.db.prepare("DELETE FROM query_history").run()}listBookmarks(e,t){if(t)return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? AND (name LIKE ? OR sql LIKE ?) ORDER BY name").all(e,`%${t}%`,`%${t}%`).map(ft);return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? ORDER BY name").all(e).map(ft)}createBookmark(e){let t=crypto.randomUUID(),n=new Date().toISOString();return this.db.prepare("INSERT INTO query_bookmarks (id, connection_id, database, name, description, sql, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(t,e.connectionId,e.database??null,e.name,e.description??"",e.sql,n,n),this.getBookmarkById(t)}updateBookmark(e){let t=new Date().toISOString();this.db.prepare("UPDATE query_bookmarks SET name = ?, description = ?, sql = ?, updated_at = ? WHERE id = ?").run(e.name,e.description??"",e.sql,t,e.id);let n=this.getBookmarkById(e.id);if(!n)throw Error(`Bookmark not found: ${e.id}`);return n}deleteBookmark(e){this.db.prepare("DELETE FROM query_bookmarks WHERE id = ?").run(e)}getBookmarkById(e){let t=this.db.prepare("SELECT * FROM query_bookmarks WHERE id = ?").get(e);return t?ft(t):null}saveWorkspace(e){this.db.prepare("INSERT INTO workspace (id, data, updated_at) VALUES ('default', ?, datetime('now')) ON CONFLICT(id) DO UPDATE SET data = excluded.data, updated_at = datetime('now')").run(e)}loadWorkspace(){return this.db.prepare("SELECT data FROM workspace WHERE id = 'default'").get()?.data??null}}function On(e,t){try{return JSON.parse(e)}catch{throw Error(`Corrupted JSON in ${t}: ${e.slice(0,100)}`)}}function pt(e){return{id:e.id,connectionId:e.connection_id,schemaName:e.schema_name,tableName:e.table_name,name:e.name,config:On(e.config,`saved view "${e.name}"`),createdAt:e.created_at,updatedAt:e.updated_at}}function ft(e){return{id:e.id,connectionId:e.connection_id,database:e.database??void 0,name:e.name,description:e.description,sql:e.sql,createdAt:e.created_at,updatedAt:e.updated_at}}function Dn(e){return{id:e.id,connectionId:e.connection_id,database:e.database??void 0,sql:e.sql,status:e.status,durationMs:e.duration_ms??void 0,rowCount:e.row_count??void 0,errorMessage:e.error_message??void 0,executedAt:e.executed_at}}function Cs(){if(!_n)throw Error("Default DB path not configured. Call setDefaultDbPath() first.");return _n()}var Z,X=null,_n;var ht=T(()=>{le();mt();Nn();Z={defaultPageSize:"100",defaultTxMode:"auto-commit",theme:"dark",queryTimeout:"30000",maxHistoryEntries:"1000",clipboardIncludeHeaders:"true",exportDefaultFormat:"csv",defaultConnectionMode:"pool",autoPin:"on-begin",autoUnpin:"never",maxSessionsPerConnection:"5",idleTransactionTimeoutMs:"300000","console.queryResponseTimeout":"300000","cli.enabled":"false"}});class gt{cm;appDb;sessions=new Map;labelCounters=new Map;pendingRestore=new Map;txFirstSeen=new Map;idleCheckTimer=null;idleCheckRunning=!1;onTransactionRollback;constructor(e,t,n){this.cm=e,this.appDb=t,this.onTransactionRollback=n,this.startIdleTransactionCheck()}dispose(){this.stopIdleTransactionCheck()}async createSession(e,t,n){let r=this.appDb.getNumberSetting("maxSessionsPerConnection")??Number(Z.maxSessionsPerConnection),i=this.sessions.get(e)?.size??0;if(r!==null&&i>=r)throw Error(`Maximum sessions per connection (${r}) reached. Destroy an existing session first.`);let o=crypto.randomUUID(),a=this.cm.getDriver(e,t);await a.reserveSession(o,{readOnly:n?.readOnly,statementTimeoutMs:n?.readOnly?this.readOnlyStatementTimeoutMs():void 0});let c=await this.confirmReadOnly(a,o,n?.readOnly),u=(this.labelCounters.get(e)??0)+1;this.labelCounters.set(e,u);let l={sessionId:o,connectionId:e,database:t,label:n?.label??`Session ${u}`,inTransaction:!1,txAborted:!1,createdAt:Date.now(),readOnly:c};if(!this.sessions.has(e))this.sessions.set(e,new Map);return this.sessions.get(e).set(o,l),l}async confirmReadOnly(e,t,n){let r=e.isSessionReadOnly(t);if(n&&!r){try{await e.releaseSession(t)}catch{}throw Error("The driver did not open this session read-only")}return n?!0:void 0}async destroySession(e){let t=this.findSession(e);if(!t)throw Error(`Session not found: ${e}`);let n=this.cm.getDriver(t.connectionId,t.database);try{await n.cancel(e)}catch{}await n.releaseSession(e),this.txFirstSeen.delete(e);let r=this.sessions.get(t.connectionId);if(r){if(r.delete(e),r.size===0)this.sessions.delete(t.connectionId)}}async destroySessionsForDatabase(e,t){let n=this.sessions.get(e);if(!n)return;for(let[r,s]of n)if(s.database===t){try{let i=this.cm.getDriver(s.connectionId,s.database);try{await i.cancel(r)}catch{}await i.releaseSession(r)}catch{}this.txFirstSeen.delete(r),n.delete(r)}if(n.size===0)this.sessions.delete(e)}listSessions(e){let t=this.sessions.get(e);if(!t)return[];let n=[];for(let r of t.values()){try{let s=this.cm.getDriver(r.connectionId,r.database);r.inTransaction=s.inTransaction(r.sessionId),r.txAborted=s.isTxAborted(r.sessionId)}catch{}n.push({...r})}return n}getSession(e){let t=this.findSession(e);if(!t)return;try{let n=this.cm.getDriver(t.connectionId,t.database);t.inTransaction=n.inTransaction(t.sessionId),t.txAborted=n.isTxAborted(t.sessionId)}catch{}return{...t}}handleSessionDead(e){let t=this.findSession(e);if(!t)return;this.txFirstSeen.delete(e);let n=this.sessions.get(t.connectionId);if(n){if(n.delete(e),n.size===0)this.sessions.delete(t.connectionId)}}handleConnectionLost(e){let t=this.sessions.get(e);if(t){for(let r of t.keys())this.txFirstSeen.delete(r);if(t.size>0)this.pendingRestore.set(e,Array.from(t.values()).map((r)=>({database:r.database,label:r.label,readOnly:r.readOnly})))}let n=`${In}:${e}:`;for(let r of this.txFirstSeen.keys())if(r.startsWith(n))this.txFirstSeen.delete(r);this.sessions.delete(e)}async handleConnectionRestored(e){let t=this.pendingRestore.get(e);if(this.pendingRestore.delete(e),!t||t.length===0)return[];let n=[];for(let s of t){let i=!1,o,a;try{a=this.cm.getDriver(e,s.database),o=crypto.randomUUID(),await a.reserveSession(o,{readOnly:s.readOnly,statementTimeoutMs:s.readOnly?this.readOnlyStatementTimeoutMs():void 0}),i=!0;let c=await this.confirmReadOnly(a,o,s.readOnly),u={sessionId:o,connectionId:e,database:s.database,label:s.label,inTransaction:!1,txAborted:!1,createdAt:Date.now(),readOnly:c};if(!this.sessions.has(e))this.sessions.set(e,new Map);this.sessions.get(e).set(o,u),n.push(u)}catch{if(i&&a&&o)try{await a.releaseSession(o)}catch{}}}let r=this.labelCounters.get(e)??0;for(let s of n){let i=s.label.match(/^Session (\d+)$/);if(i)r=Math.max(r,Number(i[1]))}return this.labelCounters.set(e,r),n}readOnlyStatementTimeoutMs(){let e=this.appDb.getNumberSetting("queryTimeout")??Number(Z.queryTimeout);return e>0?e:void 0}startIdleTransactionCheck(){this.idleCheckTimer=setInterval(()=>{this.checkIdleTransactions()},Ts)}stopIdleTransactionCheck(){if(this.idleCheckTimer)clearInterval(this.idleCheckTimer),this.idleCheckTimer=null}async checkIdleTransactions(){if(this.idleCheckRunning)return;this.idleCheckRunning=!0;try{let e=this.appDb.getNumberSetting("idleTransactionTimeoutMs")??Number(Z.idleTransactionTimeoutMs);if(!e||e<=0)return;let t=Date.now();for(let[,n]of this.sessions)for(let[r,s]of n){let i=!1,o=!1;try{let a=this.cm.getDriver(s.connectionId,s.database);i=a.inTransaction(r),o=a.isIterating(r)}catch{this.txFirstSeen.delete(r);continue}if(o)continue;if(i){if(!this.txFirstSeen.has(r))this.txFirstSeen.set(r,t);else if(t-this.txFirstSeen.get(r)>=e){try{await this.cm.getDriver(s.connectionId,s.database).rollback(r)}catch{}try{this.onTransactionRollback?.(s.connectionId,s.database,r)}catch{}this.txFirstSeen.delete(r)}}else this.txFirstSeen.delete(r)}for(let n of this.cm.listConnections()){if(n.state!=="connected")continue;let r=this.cm.getActiveDatabases(n.id);for(let s of r){let i=`${In}:${n.id}:${s}`,o=!1,a=!1;try{let c=this.cm.getDriver(n.id,s);o=c.inTransaction(),a=c.isIterating()}catch{this.txFirstSeen.delete(i);continue}if(a)continue;if(o){if(!this.txFirstSeen.has(i))this.txFirstSeen.set(i,t);else if(t-this.txFirstSeen.get(i)>=e){try{await this.cm.getDriver(n.id,s).rollback()}catch{}try{this.onTransactionRollback?.(n.id,s)}catch{}this.txFirstSeen.delete(i)}}else this.txFirstSeen.delete(i)}}}finally{this.idleCheckRunning=!1}}findSession(e){for(let t of this.sessions.values()){let n=t.get(e);if(n)return n}return}}var Ts=30000,In="__default_tx__";var xn=T(()=>{ht()});function Rs(e){return vs.includes(e)}function Ln(e){let t=(r)=>e[`${As}${r}`],n=t("provider");return{provider:Rs(n)?n:ke.provider,apiKey:t("apiKey")??ke.apiKey,model:t("model")??ke.model,endpoint:t("endpoint")??ke.endpoint}}var ke,As="ai.",vs;var Pn=T(()=>{ke={provider:"anthropic",apiKey:"",model:"claude-sonnet-4-20250514",endpoint:""},vs=["anthropic","openai","custom"]});function kn(e,t=50){let n=[],r=0;for(let[s,i]of Object.entries(e.tables))for(let o of i){if(r>=t)break;r++;let a=e.columns[`${s}.${o.name}`]??[],c=e.foreignKeys[`${s}.${o.name}`]??[],u=a.map((m)=>{let f=[m.name,m.dataType];if(m.isPrimaryKey)f.push("PK");if(!m.nullable)f.push("NOT NULL");if(m.isAutoIncrement)f.push("AUTO_INCREMENT");return f.join(" ")}),l=s==="main"||s==="public"?o.name:`${s}.${o.name}`;n.push(`TABLE ${l} (${u.join(", ")})`);for(let m of c){let f=m.referencedSchema==="main"||m.referencedSchema==="public"?m.referencedTable:`${m.referencedSchema}.${m.referencedTable}`;n.push(` FK ${m.columns.join(",")} -> ${f}(${m.referencedColumns.join(",")})`)}}return n.join(`
118
- `)}async function Ns(e,t){let r=`${e.endpoint||"https://api.anthropic.com"}/v1/messages`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:e.model,max_tokens:2048,system:`You are an expert SQL query generator. Given a database schema and a natural language request, generate a valid SQL query.
117
+ `),e.run("DROP TABLE connections"),e.run("ALTER TABLE connections_new RENAME TO connections")}},{version:10,description:"Create remote_approvers table (passkeys allowed to approve agent proposals)",up:(e)=>{e.run(`
118
+ CREATE TABLE remote_approvers (
119
+ id TEXT PRIMARY KEY,
120
+ label TEXT NOT NULL,
121
+ rp_id TEXT NOT NULL,
122
+ origin TEXT NOT NULL,
123
+ credential_id TEXT NOT NULL UNIQUE,
124
+ public_key TEXT NOT NULL,
125
+ fingerprint TEXT NOT NULL,
126
+ added_at INTEGER NOT NULL
127
+ )
128
+ `)}}]});import Gs from"bun:sqlite";class ge{db;localKey=null;constructor(e){this.db=new Gs(e,{create:!0}),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA foreign_keys = ON"),$n(this.db)}static getInstance(e){if(!ne){let t=e??Xs();ne=new ge(t)}return ne}static create(e){return new ge(e)}close(){this.db.close()}transaction(e){return this.db.transaction(e)()}static resetInstance(){if(ne)ne.db.close(),ne=null}setLocalKey(e,t){this.localKey=e,this.migratePasswords(t??null)}encryptConfigJson(e){if(this.localKey&&B(e)){let t={...e,password:te(e.password,this.localKey)};if(e.type==="postgresql"&&e.sshTunnel){let n={...e.sshTunnel};if(n.password)n.password=te(n.password,this.localKey);if(n.keyPassphrase)n.keyPassphrase=te(n.keyPassphrase,this.localKey);t={...t,sshTunnel:n}}return JSON.stringify(t)}return JSON.stringify(e)}decryptConfig(e){if(this.localKey&&B(e)&&he(e.password)){let t=(r)=>qe(r,this.localKey)??"",n={...e,password:t(e.password)};if(e.type==="postgresql"&&e.sshTunnel){let r={...e.sshTunnel};if(r.password&&he(r.password))r.password=t(r.password);if(r.keyPassphrase&&he(r.keyPassphrase))r.keyPassphrase=t(r.keyPassphrase);n={...n,sshTunnel:r}}return n}return e}migratePasswords(e){if(!this.localKey)return;let t=this.localKey,n=(r)=>{if(!he(r))return{value:te(r,t),changed:!0};if(qe(r,t)!==null)return{value:r,changed:!1};if(e){let s=qe(r,e);if(s!==null)return{value:te(s,t),changed:!0}}return{value:r,changed:!1}};this.transaction(()=>{let r=this.db.prepare("SELECT id, config FROM connections").all(),s=this.db.prepare("UPDATE connections SET config = ? WHERE id = ?");for(let i of r)try{let o=JSON.parse(i.config);if(!B(o))continue;let a=!1,c={...o},u=n(o.password);if(u.changed)c={...c,password:u.value},a=!0;if(o.type==="postgresql"&&o.sshTunnel){let l={...o.sshTunnel},d=!1;if(l.password){let f=n(l.password);if(f.changed)l.password=f.value,d=!0}if(l.keyPassphrase){let f=n(l.keyPassphrase);if(f.changed)l.keyPassphrase=f.value,d=!0}if(d)c={...c,sshTunnel:l},a=!0}if(a)s.run(JSON.stringify(c),i.id)}catch{}})}toConnectionInfo(e){let t=Qn(e.config,`connection "${e.name}"`);return{id:e.id,name:e.name,config:this.decryptConfig(t),state:"disconnected",readOnly:e.read_only===1?!0:void 0,color:e.color??void 0,groupName:e.group_name??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}listConnections(){return this.db.prepare("SELECT * FROM connections ORDER BY group_name NULLS LAST, name").all().map((t)=>this.toConnectionInfo(t))}getConnectionById(e){let t=this.db.prepare("SELECT * FROM connections WHERE id = ?").get(e);return t?this.toConnectionInfo(t):null}createConnection(e){let t=crypto.randomUUID();return this.createConnectionWithId(t,e)}createConnectionWithId(e,t){let n=new Date().toISOString();return this.db.prepare("INSERT INTO connections (id, name, type, config, read_only, color, group_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e,t.name,t.config.type,this.encryptConfigJson(t.config),t.readOnly?1:0,t.color||null,t.groupName||null,n,n),this.getConnectionById(e)}updateConnection(e){let t=this.getConnectionById(e.id);if(!t)throw Error(`Connection not found: ${e.id}`);let n=new Date().toISOString();return this.db.prepare("UPDATE connections SET name = ?, type = ?, config = ?, read_only = ?, color = ?, group_name = ?, updated_at = ? WHERE id = ?").run(e.name,e.config.type,this.encryptConfigJson(e.config),e.readOnly??t.readOnly?1:0,e.color!==void 0?e.color||null:t.color??null,e.groupName!==void 0?e.groupName||null:t.groupName??null,n,e.id),this.getConnectionById(e.id)}setConnectionGroup(e,t){this.db.prepare("UPDATE connections SET group_name = ? WHERE id = ?").run(t,e);let n=this.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);return n}listConnectionGroups(){return this.db.prepare("SELECT DISTINCT group_name FROM connections WHERE group_name IS NOT NULL ORDER BY group_name").all().map((t)=>t.group_name)}renameConnectionGroup(e,t){this.db.prepare("UPDATE connections SET group_name = ? WHERE group_name = ?").run(t,e)}deleteConnectionGroup(e){this.db.prepare("UPDATE connections SET group_name = NULL WHERE group_name = ?").run(e)}setConnectionReadOnly(e,t){this.db.prepare("UPDATE connections SET read_only = ? WHERE id = ?").run(t?1:0,e);let n=this.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);return n}deleteConnection(e){this.db.prepare("DELETE FROM connections WHERE id = ?").run(e)}getSetting(e){return this.db.prepare("SELECT value FROM settings WHERE key = ?").get(e)?.value??null}getNumberSetting(e){let t=this.getSetting(e)??re[e]??null;if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}getBooleanSetting(e){let t=this.getSetting(e)??re[e]??null;if(t===null)return null;if(t==="true")return!0;if(t==="false")return!1;return null}setSetting(e,t){this.db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,t)}getAllSettings(){let e=this.db.prepare("SELECT key, value FROM settings").all(),t={};for(let n of e)t[n.key]=n.value;return t}listSavedViews(e,t,n){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? AND schema_name = ? AND table_name = ? ORDER BY name").all(e,t,n).map(St)}createSavedView(e){let t=crypto.randomUUID(),n=new Date().toISOString();return this.db.prepare("INSERT INTO saved_views (id, connection_id, schema_name, table_name, name, config, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(t,e.connectionId,e.schemaName,e.tableName,e.name,JSON.stringify(e.config),n,n),this.getSavedViewById(t)}updateSavedView(e){let t=new Date().toISOString();this.db.prepare("UPDATE saved_views SET name = ?, config = ?, updated_at = ? WHERE id = ?").run(e.name,JSON.stringify(e.config),t,e.id);let n=this.getSavedViewById(e.id);if(!n)throw Error(`Saved view not found: ${e.id}`);return n}deleteSavedView(e){this.db.prepare("DELETE FROM saved_views WHERE id = ?").run(e)}listSavedViewsByConnection(e){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? ORDER BY table_name, name").all(e).map(St)}getSavedViewById(e){let t=this.db.prepare("SELECT * FROM saved_views WHERE id = ?").get(e);return t?St(t):null}addHistory(e){let t=this.db.prepare("INSERT INTO query_history (connection_id, database, sql, status, duration_ms, row_count, error_message) VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING *").get(e.connectionId,e.database??null,e.sql,e.status,e.durationMs??null,e.rowCount??null,e.errorMessage??null);return this.pruneHistory(),Hn(t)}pruneHistory(){let e=this.getNumberSetting("maxHistoryEntries");if(e===null||e<=0)return;this.db.prepare("DELETE FROM query_history WHERE id NOT IN (SELECT id FROM query_history ORDER BY executed_at DESC, id DESC LIMIT ?)").run(e)}listHistory(e){let t=e.limit??100,n=e.offset??0,r=[],s=[];if(e.connectionId)r.push("connection_id = ?"),s.push(e.connectionId);if(e.search)r.push("sql LIKE ?"),s.push(`%${e.search}%`);if(e.startDate)r.push("executed_at >= ?"),s.push(e.startDate+" 00:00:00");if(e.endDate){let c=new Date(e.endDate+"T00:00:00Z");c.setUTCDate(c.getUTCDate()+1);let u=c.getUTCFullYear(),l=String(c.getUTCMonth()+1).padStart(2,"0"),d=String(c.getUTCDate()).padStart(2,"0");r.push("executed_at < ?"),s.push(`${u}-${l}-${d} 00:00:00`)}let o=`SELECT * FROM query_history ${r.length>0?`WHERE ${r.join(" AND ")}`:""} ORDER BY executed_at DESC LIMIT ? OFFSET ?`;return s.push(t,n),this.db.prepare(o).all(...s).map(Hn)}clearHistory(e){if(e)this.db.prepare("DELETE FROM query_history WHERE connection_id = ?").run(e);else this.db.prepare("DELETE FROM query_history").run()}listBookmarks(e,t){if(t)return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? AND (name LIKE ? OR sql LIKE ?) ORDER BY name").all(e,`%${t}%`,`%${t}%`).map(Et);return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? ORDER BY name").all(e).map(Et)}createBookmark(e){let t=crypto.randomUUID(),n=new Date().toISOString();return this.db.prepare("INSERT INTO query_bookmarks (id, connection_id, database, name, description, sql, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(t,e.connectionId,e.database??null,e.name,e.description??"",e.sql,n,n),this.getBookmarkById(t)}updateBookmark(e){let t=new Date().toISOString();this.db.prepare("UPDATE query_bookmarks SET name = ?, description = ?, sql = ?, updated_at = ? WHERE id = ?").run(e.name,e.description??"",e.sql,t,e.id);let n=this.getBookmarkById(e.id);if(!n)throw Error(`Bookmark not found: ${e.id}`);return n}deleteBookmark(e){this.db.prepare("DELETE FROM query_bookmarks WHERE id = ?").run(e)}getBookmarkById(e){let t=this.db.prepare("SELECT * FROM query_bookmarks WHERE id = ?").get(e);return t?Et(t):null}saveWorkspace(e){this.db.prepare("INSERT INTO workspace (id, data, updated_at) VALUES ('default', ?, datetime('now')) ON CONFLICT(id) DO UPDATE SET data = excluded.data, updated_at = datetime('now')").run(e)}loadWorkspace(){return this.db.prepare("SELECT data FROM workspace WHERE id = 'default'").get()?.data??null}listRemoteApprovers(){return this.db.prepare("SELECT * FROM remote_approvers ORDER BY added_at, id").all().map(Js)}addRemoteApprover(e){this.db.prepare("INSERT INTO remote_approvers (id, label, rp_id, origin, credential_id, public_key, fingerprint, added_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.label,e.rpId,e.origin,e.credentialId,e.publicKey,e.fingerprint,e.addedAt)}removeRemoteApprover(e){return this.db.prepare("DELETE FROM remote_approvers WHERE id = ?").run(e).changes>0}}function Js(e){return{id:e.id,label:e.label,rpId:e.rp_id,origin:e.origin,credentialId:e.credential_id,publicKey:e.public_key,fingerprint:e.fingerprint,addedAt:e.added_at}}function Qn(e,t){try{return JSON.parse(e)}catch{throw Error(`Corrupted JSON in ${t}: ${e.slice(0,100)}`)}}function St(e){return{id:e.id,connectionId:e.connection_id,schemaName:e.schema_name,tableName:e.table_name,name:e.name,config:Qn(e.config,`saved view "${e.name}"`),createdAt:e.created_at,updatedAt:e.updated_at}}function Et(e){return{id:e.id,connectionId:e.connection_id,database:e.database??void 0,name:e.name,description:e.description,sql:e.sql,createdAt:e.created_at,updatedAt:e.updated_at}}function Hn(e){return{id:e.id,connectionId:e.connection_id,database:e.database??void 0,sql:e.sql,status:e.status,durationMs:e.duration_ms??void 0,rowCount:e.row_count??void 0,errorMessage:e.error_message??void 0,executedAt:e.executed_at}}function Xs(){if(!Bn)throw Error("Default DB path not configured. Call setDefaultDbPath() first.");return Bn()}var re,ne=null,Bn;var bt=C(()=>{me();wt();Fn();re={defaultPageSize:"100",defaultTxMode:"auto-commit",theme:"dark",queryTimeout:"30000",maxHistoryEntries:"1000",clipboardIncludeHeaders:"true",exportDefaultFormat:"csv",defaultConnectionMode:"pool",autoPin:"on-begin",autoUnpin:"never",maxSessionsPerConnection:"5",idleTransactionTimeoutMs:"300000","console.queryResponseTimeout":"300000","cli.enabled":"false"}});class Ct{cm;appDb;sessions=new Map;labelCounters=new Map;pendingRestore=new Map;txFirstSeen=new Map;idleCheckTimer=null;idleCheckRunning=!1;onTransactionRollback;constructor(e,t,n){this.cm=e,this.appDb=t,this.onTransactionRollback=n,this.startIdleTransactionCheck()}dispose(){this.stopIdleTransactionCheck()}async createSession(e,t,n){let r=this.appDb.getNumberSetting("maxSessionsPerConnection")??Number(re.maxSessionsPerConnection),i=this.sessions.get(e)?.size??0;if(r!==null&&i>=r)throw Error(`Maximum sessions per connection (${r}) reached. Destroy an existing session first.`);let o=crypto.randomUUID(),a=this.cm.getDriver(e,t);await a.reserveSession(o,{readOnly:n?.readOnly,statementTimeoutMs:n?.readOnly?this.readOnlyStatementTimeoutMs():void 0});let c=await this.confirmReadOnly(a,o,n?.readOnly),u=(this.labelCounters.get(e)??0)+1;this.labelCounters.set(e,u);let l={sessionId:o,connectionId:e,database:t,label:n?.label??`Session ${u}`,inTransaction:!1,txAborted:!1,createdAt:Date.now(),readOnly:c};if(!this.sessions.has(e))this.sessions.set(e,new Map);return this.sessions.get(e).set(o,l),l}async confirmReadOnly(e,t,n){let r=e.isSessionReadOnly(t);if(n&&!r){try{await e.releaseSession(t)}catch{}throw Error("The driver did not open this session read-only")}return n?!0:void 0}async destroySession(e){let t=this.findSession(e);if(!t)throw Error(`Session not found: ${e}`);let n=this.cm.getDriver(t.connectionId,t.database);try{await n.cancel(e)}catch{}await n.releaseSession(e),this.txFirstSeen.delete(e);let r=this.sessions.get(t.connectionId);if(r){if(r.delete(e),r.size===0)this.sessions.delete(t.connectionId)}}async destroySessionsForDatabase(e,t){let n=this.sessions.get(e);if(!n)return;for(let[r,s]of n)if(s.database===t){try{let i=this.cm.getDriver(s.connectionId,s.database);try{await i.cancel(r)}catch{}await i.releaseSession(r)}catch{}this.txFirstSeen.delete(r),n.delete(r)}if(n.size===0)this.sessions.delete(e)}listSessions(e){let t=this.sessions.get(e);if(!t)return[];let n=[];for(let r of t.values()){try{let s=this.cm.getDriver(r.connectionId,r.database);r.inTransaction=s.inTransaction(r.sessionId),r.txAborted=s.isTxAborted(r.sessionId)}catch{}n.push({...r})}return n}getSession(e){let t=this.findSession(e);if(!t)return;try{let n=this.cm.getDriver(t.connectionId,t.database);t.inTransaction=n.inTransaction(t.sessionId),t.txAborted=n.isTxAborted(t.sessionId)}catch{}return{...t}}handleSessionDead(e){let t=this.findSession(e);if(!t)return;this.txFirstSeen.delete(e);let n=this.sessions.get(t.connectionId);if(n){if(n.delete(e),n.size===0)this.sessions.delete(t.connectionId)}}handleConnectionLost(e){let t=this.sessions.get(e);if(t){for(let r of t.keys())this.txFirstSeen.delete(r);if(t.size>0)this.pendingRestore.set(e,Array.from(t.values()).map((r)=>({database:r.database,label:r.label,readOnly:r.readOnly})))}let n=`${Kn}:${e}:`;for(let r of this.txFirstSeen.keys())if(r.startsWith(n))this.txFirstSeen.delete(r);this.sessions.delete(e)}async handleConnectionRestored(e){let t=this.pendingRestore.get(e);if(this.pendingRestore.delete(e),!t||t.length===0)return[];let n=[];for(let s of t){let i=!1,o,a;try{a=this.cm.getDriver(e,s.database),o=crypto.randomUUID(),await a.reserveSession(o,{readOnly:s.readOnly,statementTimeoutMs:s.readOnly?this.readOnlyStatementTimeoutMs():void 0}),i=!0;let c=await this.confirmReadOnly(a,o,s.readOnly),u={sessionId:o,connectionId:e,database:s.database,label:s.label,inTransaction:!1,txAborted:!1,createdAt:Date.now(),readOnly:c};if(!this.sessions.has(e))this.sessions.set(e,new Map);this.sessions.get(e).set(o,u),n.push(u)}catch{if(i&&a&&o)try{await a.releaseSession(o)}catch{}}}let r=this.labelCounters.get(e)??0;for(let s of n){let i=s.label.match(/^Session (\d+)$/);if(i)r=Math.max(r,Number(i[1]))}return this.labelCounters.set(e,r),n}readOnlyStatementTimeoutMs(){let e=this.appDb.getNumberSetting("queryTimeout")??Number(re.queryTimeout);return e>0?e:void 0}startIdleTransactionCheck(){this.idleCheckTimer=setInterval(()=>{this.checkIdleTransactions()},Zs)}stopIdleTransactionCheck(){if(this.idleCheckTimer)clearInterval(this.idleCheckTimer),this.idleCheckTimer=null}async checkIdleTransactions(){if(this.idleCheckRunning)return;this.idleCheckRunning=!0;try{let e=this.appDb.getNumberSetting("idleTransactionTimeoutMs")??Number(re.idleTransactionTimeoutMs);if(!e||e<=0)return;let t=Date.now();for(let[,n]of this.sessions)for(let[r,s]of n){let i=!1,o=!1;try{let a=this.cm.getDriver(s.connectionId,s.database);i=a.inTransaction(r),o=a.isIterating(r)}catch{this.txFirstSeen.delete(r);continue}if(o)continue;if(i){if(!this.txFirstSeen.has(r))this.txFirstSeen.set(r,t);else if(t-this.txFirstSeen.get(r)>=e){try{await this.cm.getDriver(s.connectionId,s.database).rollback(r)}catch{}try{this.onTransactionRollback?.(s.connectionId,s.database,r)}catch{}this.txFirstSeen.delete(r)}}else this.txFirstSeen.delete(r)}for(let n of this.cm.listConnections()){if(n.state!=="connected")continue;let r=this.cm.getActiveDatabases(n.id);for(let s of r){let i=`${Kn}:${n.id}:${s}`,o=!1,a=!1;try{let c=this.cm.getDriver(n.id,s);o=c.inTransaction(),a=c.isIterating()}catch{this.txFirstSeen.delete(i);continue}if(a)continue;if(o){if(!this.txFirstSeen.has(i))this.txFirstSeen.set(i,t);else if(t-this.txFirstSeen.get(i)>=e){try{await this.cm.getDriver(n.id,s).rollback()}catch{}try{this.onTransactionRollback?.(n.id,s)}catch{}this.txFirstSeen.delete(i)}}else this.txFirstSeen.delete(i)}}}finally{this.idleCheckRunning=!1}}findSession(e){for(let t of this.sessions.values()){let n=t.get(e);if(n)return n}return}}var Zs=30000,Kn="__default_tx__";var Yn=C(()=>{bt()});function ni(e){return ti.includes(e)}function jn(e){let t=(r)=>e[`${ei}${r}`],n=t("provider");return{provider:ni(n)?n:$e.provider,apiKey:t("apiKey")??$e.apiKey,model:t("model")??$e.model,endpoint:t("endpoint")??$e.endpoint}}var $e,ei="ai.",ti;var Wn=C(()=>{$e={provider:"anthropic",apiKey:"",model:"claude-sonnet-4-20250514",endpoint:""},ti=["anthropic","openai","custom"]});function zn(e,t=50){let n=[],r=0;for(let[s,i]of Object.entries(e.tables))for(let o of i){if(r>=t)break;r++;let a=e.columns[`${s}.${o.name}`]??[],c=e.foreignKeys[`${s}.${o.name}`]??[],u=a.map((d)=>{let f=[d.name,d.dataType];if(d.isPrimaryKey)f.push("PK");if(!d.nullable)f.push("NOT NULL");if(d.isAutoIncrement)f.push("AUTO_INCREMENT");return f.join(" ")}),l=s==="main"||s==="public"?o.name:`${s}.${o.name}`;n.push(`TABLE ${l} (${u.join(", ")})`);for(let d of c){let f=d.referencedSchema==="main"||d.referencedSchema==="public"?d.referencedTable:`${d.referencedSchema}.${d.referencedTable}`;n.push(` FK ${d.columns.join(",")} -> ${f}(${d.referencedColumns.join(",")})`)}}return n.join(`
129
+ `)}async function ri(e,t){let r=`${e.endpoint||"https://api.anthropic.com"}/v1/messages`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:e.model,max_tokens:2048,system:`You are an expert SQL query generator. Given a database schema and a natural language request, generate a valid SQL query.
119
130
 
120
131
  Rules:
121
132
  - Output ONLY the SQL query \u2014 no explanations, no markdown, no code fences.
@@ -129,7 +140,7 @@ Rules:
129
140
  Database schema:
130
141
  ${t.schemaContext}
131
142
 
132
- Request: ${t.prompt}`}]})});if(!s.ok){let a=await s.text().catch(()=>"");if(s.status===401)throw Error("Invalid API key. Check your AI settings.");if(s.status===429)throw Error("Rate limited. Please wait and try again.");throw Error(`Anthropic API error (${s.status}): ${a.slice(0,200)}`)}let o=(await s.json()).content?.find((a)=>a.type==="text");return Un(o?.text??"")}async function Mn(e,t){let r=`${e.endpoint||"https://api.openai.com"}/v1/chat/completions`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({model:e.model||"gpt-4o",max_tokens:2048,messages:[{role:"system",content:`You are an expert SQL query generator. Given a database schema and a natural language request, generate a valid SQL query.
143
+ Request: ${t.prompt}`}]})});if(!s.ok){let a=await s.text().catch(()=>"");if(s.status===401)throw Error("Invalid API key. Check your AI settings.");if(s.status===429)throw Error("Rate limited. Please wait and try again.");throw Error(`Anthropic API error (${s.status}): ${a.slice(0,200)}`)}let o=(await s.json()).content?.find((a)=>a.type==="text");return Gn(o?.text??"")}async function Vn(e,t){let r=`${e.endpoint||"https://api.openai.com"}/v1/chat/completions`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({model:e.model||"gpt-4o",max_tokens:2048,messages:[{role:"system",content:`You are an expert SQL query generator. Given a database schema and a natural language request, generate a valid SQL query.
133
144
 
134
145
  Rules:
135
146
  - Output ONLY the SQL query \u2014 no explanations, no markdown, no code fences.
@@ -143,8 +154,9 @@ Rules:
143
154
  Database schema:
144
155
  ${t.schemaContext}
145
156
 
146
- Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.status===401)throw Error("Invalid API key. Check your AI settings.");if(s.status===429)throw Error("Rate limited. Please wait and try again.");throw Error(`OpenAI API error (${s.status}): ${o.slice(0,200)}`)}let i=await s.json();return Un(i.choices?.[0]?.message?.content??"")}async function Ds(e,t){if(!e.endpoint)throw Error("Custom AI endpoint URL is required. Check your AI settings.");return Mn(e,t)}function Un(e){let t=e.trim(),n=t.match(/^```(?:sql)?\s*\n?([\s\S]*?)\n?```$/);if(n)t=n[1].trim();return t}async function $n(e,t){if(!e.apiKey)throw Error("AI API key not configured. Go to AI Settings (command palette) to set it up.");switch(e.provider){case"anthropic":return Ns(e,t);case"openai":return Mn(e,t);case"custom":return Ds(e,t);default:throw Error(`Unknown AI provider: ${e.provider}`)}}function yt(e){return e!=="pending"&&e!=="approved"}class St{proposals=new Map;waiters=new Map;observers=new Set;ttlMs;now;disposed=!1;constructor(e){this.ttlMs=e?.ttlMs??3600000,this.now=e?.now??(()=>Date.now())}create(e){this.assertUsable(),this.sweep();let t=[...this.proposals.values()].filter((r)=>r.status==="pending").length;if(t>=20)throw Error(`${t} proposals are already waiting for approval \u2014 wait for the user or cancel some first`);let n={id:crypto.randomUUID(),connectionId:e.connectionId,database:e.database,sql:e.sql,reason:e.reason,status:"pending",createdAt:this.now()};return this.proposals.set(n.id,n),this.notify(n),{...n}}get(e){this.sweep();let t=this.proposals.get(e);return t?{...t}:null}list(e){this.sweep();let t=[...this.proposals.values()];if(e?.status)t=t.filter((n)=>n.status===e.status);if(e?.connectionId)t=t.filter((n)=>n.connectionId===e.connectionId);return t.map((n)=>({...n}))}resolve(e){if(this.assertUsable(),this.sweep(),!_s.includes(e.status))throw Error(`Cannot resolve a proposal to status "${e.status}"`);return this.transition(this.require(e.proposalId),e.status,e.result,e.error)}cancel(e){return this.assertUsable(),this.sweep(),this.transition(this.require(e),"cancelled")}async wait(e,t){this.assertUsable(),this.sweep();let n=this.require(e);if(yt(n.status))return{...n};return new Promise((r)=>{let s,i=(o,a)=>{if(!a&&!yt(o.status))return;if(s!==void 0)clearTimeout(s);this.removeWaiter(e,i),r({...o})};this.addWaiter(e,i),s=setTimeout(()=>{this.removeWaiter(e,i),this.sweep();let o=this.proposals.get(e);r({...o??n})},t)})}waiterCount(){let e=0;for(let t of this.waiters.values())e+=t.size;return e}dispose(){this.disposed=!0;for(let[e,t]of[...this.waiters]){let n=this.proposals.get(e);if(!n)continue;for(let r of[...t])r(n,!0)}this.waiters.clear(),this.observers.clear(),this.proposals.clear()}require(e){let t=this.proposals.get(e);if(!t)throw Error(`Proposal not found: ${e}`);return t}transition(e,t,n,r){if(!(e.status==="pending"||e.status==="approved"&&Os.includes(t)))throw Error(`Proposal ${e.id} is already ${e.status}`);if(e.status=t,e.resolvedAt=this.now(),n!==void 0)e.result=n;if(r!==void 0)e.error=r;return this.notify(e),{...e}}sweep(){let e=this.now(),t=e-this.ttlMs;for(let[n,r]of this.proposals){if(r.status==="pending"){if(r.createdAt>t)continue;r.status="expired",r.resolvedAt=e,this.notify(r);continue}if(r.status==="approved"){if((r.resolvedAt??r.createdAt)>t)continue;r.status="failed",r.error="The app claimed this proposal but never reported the outcome. The statement may have run \u2014 check the data.",r.resolvedAt=e,this.notify(r);continue}if((r.resolvedAt??r.createdAt)<=t)this.proposals.delete(n)}this.evictOverflow()}evictOverflow(){if(this.proposals.size<=500)return;for(let[e,t]of this.proposals){if(this.proposals.size<=500)return;if(!yt(t.status))continue;this.proposals.delete(e)}}onChange(e){return this.observers.add(e),()=>this.observers.delete(e)}notify(e){for(let n of[...this.observers])n({...e});let t=this.waiters.get(e.id);if(!t)return;for(let n of[...t])n(e)}addWaiter(e,t){let n=this.waiters.get(e);if(n){n.add(t);return}this.waiters.set(e,new Set([t]))}removeWaiter(e,t){let n=this.waiters.get(e);if(!n)return;if(n.delete(t),n.size===0)this.waiters.delete(e)}assertUsable(){if(this.disposed)throw Error("ProposalStore has been disposed")}}var _s,Os;var qn=T(()=>{_s=["approved","rejected","executed","failed","cancelled","expired"],Os=["executed","failed"]});function Is(e){return e.dataType!=="binary"}async function Fn(e,t,n,r){let s=performance.now(),i=await e.loadSchema(t.sessionId),o=[];for(let[f,g]of Object.entries(i.tables)){if(t.scope==="schema"&&t.schemaName&&f!==t.schemaName)continue;for(let d of g){if(d.type!=="table")continue;if(t.scope==="tables"&&t.tableNames){if(!t.tableNames.includes(d.name))continue}o.push(d)}}let a=[],c=0,u=0,l=e.getDriverType()==="postgresql",m=l?"ILIKE":"LIKE";for(let f of o){if(r())return{matches:a,searchedTables:u,totalMatches:c,cancelled:!0,elapsedMs:Math.round(performance.now()-s)};n(f.name,u,o.length);let g=`${f.schema}.${f.name}`,h=(i.columns[g]??[]).filter(Is);if(h.length===0){u++;continue}let y=[],w=[],p=0;for(let N of h){p++;let v=e.quoteIdentifier(N.name);y.push(`${we(v,e)} ${m} ${e.placeholder(p)}`),w.push(`%${t.searchTerm}%`)}let S=e.qualifyTable(f.schema,f.name);p++;let E=e.placeholder(p),C=`SELECT * FROM ${S} WHERE ${y.join(" OR ")} LIMIT ${E}`;w.push(t.resultsPerTable);try{let N=await e.execute(C,w,t.sessionId);for(let v of N.rows){let L=v;for(let q of h){let Ut=L[q.name];if(Ut==null)continue;let $t=String(Ut);if(l?$t.toLowerCase().includes(t.searchTerm.toLowerCase()):$t.toLowerCase().includes(t.searchTerm.toLowerCase())){a.push({schema:f.schema,table:f.name,column:q.name,row:L}),c++;break}}}}catch(N){console.debug(`Search: skipped ${f.schema}.${f.name}:`,N instanceof Error?N.message:N)}u++}return{matches:a,searchedTables:u,totalMatches:c,cancelled:!1,elapsedMs:Math.round(performance.now()-s)}}var Hn=T(()=>{M()});function Ps(e){let t=[],n=0;while(n<e.length){let r=e[n];if(r==="'"||r==='"'){let s=r,i=r;n++;while(n<e.length)if(e[n]===s)if(i+=e[n],n++,n<e.length&&e[n]===s)i+=e[n],n++;else break;else i+=e[n],n++;t.push({type:"string",value:i,upper:i});continue}if(/\s/.test(r)){let s="";while(n<e.length&&/\s/.test(e[n]))s+=e[n],n++;t.push({type:"whitespace",value:s,upper:s});continue}if(/[a-zA-Z_]/.test(r)){let s="";while(n<e.length&&/[a-zA-Z0-9_]/.test(e[n]))s+=e[n],n++;t.push({type:"word",value:s,upper:s.toUpperCase()});continue}t.push({type:"symbol",value:r,upper:r}),n++}return t}function ks(e,t,n){let r=n.split(" "),s=t,i=0;while(i<r.length&&s<e.length){if(e[s].type==="whitespace"){s++;continue}if(e[s].upper!==r[i])return 0;i++,s++}return i===r.length?s-t:0}function Yn(e){let t=e.trim();if(!t)return"";let n=Ps(t);for(let c of n)if(c.type==="word"){if(Ls.includes(c.upper))c.value=c.upper}let r=[],s="",i=0,o=0;while(i<n.length){let c=n[i];if(c.type==="symbol"&&c.value==="("){o++,s+=c.value,i++;continue}if(c.type==="symbol"&&c.value===")"){if(o>0)o--;s+=c.value,i++;continue}if(o>0){s+=c.value,i++;continue}if(c.type==="word"){let u=!1,l=[...Bn,...Qn].sort((m,f)=>f.split(" ").length-m.split(" ").length);for(let m of l){let f=ks(n,i,m);if(f>0){let g=[];for(let w=i;w<i+f;w++)g.push(n[w].value);let d=g.filter((w)=>w.trim()).join(" "),h=Qn.includes(m);if(Bn.includes(m)||h){let w=s.trimEnd();if(w)r.push(w);s=d}else s+=d;i+=f,u=!0;break}}if(u)continue;if(xs.includes(c.upper)){let m=s.trimEnd();if(m)r.push(m);s=" "+c.value,i++;continue}}if(c.type==="whitespace"){if(s.trimEnd())s+=" "}else s+=c.value;i++}let a=s.trimEnd();if(a)r.push(a);return r.join(`
147
- `)}var Bn,Qn,xs,Ls;var Kn=T(()=>{Bn=["SELECT","FROM","WHERE","ORDER BY","GROUP BY","HAVING","LIMIT","OFFSET","UNION","UNION ALL","INTERSECT","EXCEPT","INSERT INTO","UPDATE","SET","DELETE FROM","VALUES"],Qn=["LEFT OUTER JOIN","RIGHT OUTER JOIN","FULL OUTER JOIN","CROSS JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","NATURAL JOIN","JOIN"],xs=["ON","AND","OR"],Ls=["SELECT","DISTINCT","FROM","WHERE","AND","OR","NOT","IN","EXISTS","BETWEEN","LIKE","ILIKE","IS","NULL","TRUE","FALSE","AS","ON","USING","JOIN","INNER","LEFT","RIGHT","FULL","OUTER","CROSS","NATURAL","ORDER","BY","GROUP","HAVING","LIMIT","OFFSET","UNION","ALL","INTERSECT","EXCEPT","INSERT","INTO","VALUES","UPDATE","SET","DELETE","CREATE","ALTER","DROP","TABLE","INDEX","VIEW","PRIMARY","KEY","FOREIGN","REFERENCES","UNIQUE","CHECK","DEFAULT","CONSTRAINT","CASCADE","RESTRICT","BEGIN","COMMIT","ROLLBACK","TRANSACTION","CASE","WHEN","THEN","ELSE","END","ASC","DESC","NULLS","FIRST","LAST","COUNT","SUM","AVG","MIN","MAX","CAST","COALESCE","NULLIF","WITH","RECURSIVE","RETURNING"]});class wt{cm;constructor(e){this.cm=e}async begin(e,t,n){let r=this.cm.getDriver(e,t);if(r.inTransaction(n))throw Error("Transaction already active on this connection");await r.beginTransaction(n)}async commit(e,t,n){let r=this.cm.getDriver(e,t);if(!r.inTransaction(n))throw Error("No active transaction to commit");await r.commit(n)}async rollback(e,t,n){let r=this.cm.getDriver(e,t);if(!r.inTransaction(n))throw Error("No active transaction to rollback");await r.rollback(n)}isActive(e,t,n){try{return this.cm.getDriver(e,t).inTransaction(n)}catch{return!1}}async rollbackIfActive(e,t,n){if(this.isActive(e,t,n))await this.rollback(e,t,n)}}class Et{cm;queryExecutor;appDb;txManager;encryption;Utils;emitMessage;sessionManager;demoDbSourcePath;demoDbTargetPath;allowServerFileAccess;appVersion;mode;proposals=new St;unsubscribeProposals;uiSnapshot=null;constructor(e,t,n,r){this.cm=e;this.queryExecutor=t;this.appDb=n;this.txManager=new wt(e),this.encryption=r?.encryption,this.Utils=r?.Utils,this.emitMessage=r?.emitMessage,this.sessionManager=r?.sessionManager,this.demoDbSourcePath=r?.demoDbSourcePath,this.demoDbTargetPath=r?.demoDbTargetPath,this.allowServerFileAccess=r?.allowServerFileAccess??!0,this.appVersion=r?.appVersion??"0.0.0",this.mode=r?.mode??"web",this.unsubscribeProposals=this.proposals.onChange((s)=>{this.emitMessage?.("cli.proposal",s)})}listConnections(){return this.cm.listConnections()}createConnection(e){return this.rejectServerSqliteConfig(e.config),this.cm.createConnection(e)}updateConnection(e){return this.rejectServerSqliteConfig(e.config),this.cm.updateConnection(e)}setConnectionReadOnly(e,t){return this.cm.setConnectionReadOnly(e,t)}setConnectionGroup(e,t){return this.appDb.setConnectionGroup(e,t)}listConnectionGroups(){return this.appDb.listConnectionGroups()}renameConnectionGroup(e,t){this.appDb.renameConnectionGroup(e,t)}deleteConnectionGroup(e){this.appDb.deleteConnectionGroup(e)}async deleteConnection(e){await this.cm.deleteConnection(e)}async testConnection(e){return this.rejectServerSqliteConfig(e),this.cm.testConnection(e)}async connect(e,t,n){if(this.encryption){let r;if(n?.config){let s=n.encryptedSecrets?JSON.parse(await this.encryption.decrypt(n.encryptedSecrets)):{};r=An(n.config,s)}else if(n?.encryptedConfig)r=JSON.parse(await this.encryption.decrypt(n.encryptedConfig));if(r){this.rejectServerSqliteConfig(r);let s=this.appDb.getConnectionById(e),i=n?.name??s?.name??e;if(!s)this.appDb.createConnectionWithId(e,{name:i,config:r});else this.appDb.updateConnection({id:e,name:i,config:r})}}await this.cm.connect(e,t?{password:t}:void 0)}async disconnect(e){await this.cm.disconnect(e)}listConnectionHandles(){let e=this.cm.listConnectionHandles();if(!this.sessionManager)return e;let t=new Map;for(let n of this.cm.listConnections())for(let r of this.sessionManager.listSessions(n.id))t.set(r.sessionId,r);return e.map((n)=>{if(!n.sessionId)return n;let r=t.get(n.sessionId);if(!r)return n;return{...n,label:r.label}})}async terminateConnectionHandle(e,t,n){let r=this.listConnectionHandles().find((s)=>s.connectionId===e&&(t===void 0||s.database===t)&&s.handleId===n);if(r?.sessionId&&this.sessionManager){await this.sessionManager.destroySession(r.sessionId),this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)});return}await this.cm.terminateConnectionHandle(e,t,n)}async createSession(e,t,n){if(!this.sessionManager)throw Error("SessionManager not available");let r=await this.sessionManager.createSession(e,t,n);return this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)}),r}async destroySession(e){if(!this.sessionManager)throw Error("SessionManager not available");let t=this.sessionManager.getSession(e);if(await this.sessionManager.destroySession(e),t)this.emitMessage?.("session.changed",{connectionId:t.connectionId,sessions:this.sessionManager.listSessions(t.connectionId)})}listSessions(e){if(!this.sessionManager)return[];return this.sessionManager.listSessions(e)}getDriver(e,t){return this.cm.getDriver(e,t)}async listDatabases(e){return this.cm.listDatabases(e)}async listDatabasesForConfig(e){return this.rejectServerSqliteConfig(e),this.cm.listDatabasesForConfig(e)}async activateDatabase(e,t){await this.cm.activateDatabase(e,t)}async deactivateDatabase(e,t){if(this.sessionManager)await this.sessionManager.destroySessionsForDatabase(e,t),this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)});await this.cm.deactivateDatabase(e,t)}async executeQuery(e,t,n,r,s,i,o){return this.queryExecutor.executeQuery(e,t,n,void 0,r,s,i,o)}async executeStatements(e,t,n,r){let s=this.cm.getDriver(e,n);for(let o of t)Ie(s,o.sql,r);let i=async(o)=>{let a=s.inTransaction(o);try{if(!a)await s.beginTransaction(o);let c=[];for(let u of t){let l=performance.now();try{let m=await s.execute(u.sql,u.params,o),f=Math.round(performance.now()-l);c.push({...m,durationMs:f}),this.queryExecutor.sessionLog.add(e,u.sql,m.error?"error":"success",f,Re(m),m.error,n,o)}catch(m){let f=Math.round(performance.now()-l);throw this.queryExecutor.sessionLog.add(e,u.sql,"error",f,0,m instanceof Error?m.message:String(m),n,o),m}}if(!a)await s.commit(o);return c}catch(c){if(!a)try{await s.rollback(o)}catch(u){console.debug("Rollback after error failed:",u instanceof Error?u.message:u)}throw c}};if(r)return i(r);return ae(s,i)}submitQuery(e,t,n,r,s,i,o){let a=performance.now();this.queryExecutor.executeQuery(e,t,n,0,r,s,i,o).then((c)=>{this.emitMessage?.("query.completed",{queryId:r,results:c,durationMs:Math.round(performance.now()-a)})}).catch((c)=>{let u=c?.code;this.emitMessage?.("query.completed",{queryId:r,error:c instanceof Error?c.message:String(c),errorCode:u,durationMs:Math.round(performance.now()-a)})})}submitExplain(e,t,n,r,s,i,o){let a=performance.now();this.queryExecutor.explainQuery(e,t,n,s,i,o).then((c)=>{this.emitMessage?.("query.completed",{queryId:r,explainResult:c,durationMs:Math.round(performance.now()-a)})}).catch((c)=>{this.emitMessage?.("query.completed",{queryId:r,error:c instanceof Error?c.message:String(c),durationMs:Math.round(performance.now()-a)})})}cancelQuery(e){return this.queryExecutor.cancelQuery(e)}async beginTransaction(e,t,n){await this.txManager.begin(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}async commitTransaction(e,t,n){await this.txManager.commit(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}async rollbackTransaction(e,t,n){await this.txManager.rollback(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}getTransactionLog(e){let t=this.queryExecutor.sessionLog.getEntries(e.connectionId,e.database);if(e.statusFilter)t=t.filter((s)=>s.status===e.statusFilter);if(e.search){let s=e.search.toLowerCase();t=t.filter((i)=>i.sql.toLowerCase().includes(s))}let n=this.txManager.isActive(e.connectionId,e.database,e.sessionId),r=n?this.queryExecutor.sessionLog.getPendingCount(e.connectionId,e.database,e.sessionId):0;return{entries:t,pendingStatementCount:r,inTransaction:n}}clearTransactionLog(e,t,n){this.queryExecutor.sessionLog.clear(e,t)}listHistory(e){return this.appDb.listHistory(e)}clearHistory(e){this.appDb.clearHistory(e)}listSavedViews(e,t,n){return this.appDb.listSavedViews(e,t,n)}createSavedView(e){return this.appDb.createSavedView(e)}updateSavedView(e){return this.appDb.updateSavedView(e)}deleteSavedView(e){this.appDb.deleteSavedView(e)}listSavedViewsByConnection(e){return this.appDb.listSavedViewsByConnection(e)}getSavedViewById(e){return this.appDb.getSavedViewById(e)}listBookmarks(e,t){return this.appDb.listBookmarks(e,t)}createBookmark(e){return this.appDb.createBookmark(e)}updateBookmark(e){return this.appDb.updateBookmark(e)}deleteBookmark(e){this.appDb.deleteBookmark(e)}async searchDatabase(e){let t=this.cm.getDriver(e.connectionId,e.database);return Fn(t,{searchTerm:e.searchTerm,scope:e.scope,schemaName:e.schemaName,tableNames:e.tableNames,resultsPerTable:e.resultsPerTable??50,sessionId:e.sessionId},()=>{},()=>!1)}async exportData(e){let t=e.filePath;this.rejectServerFileAccess(t);let n=this.cm.getDriver(e.connectionId,e.database);if(!t)throw Error("Export requires a file path");let r=this.emitMessage?(i)=>this.emitMessage("export.progress",{rowCount:i}):void 0;return{...await on(n,{schema:e.schema,table:e.table,format:e.format,columns:e.columns,keyColumns:e.keyColumns,includeHeaders:e.includeHeaders,delimiter:e.delimiter,encoding:e.encoding,utf8Bom:e.utf8Bom,batchSize:e.batchSize,filters:e.filters,sort:e.sort,limit:e.limit,autoJoins:e.autoJoins},t,void 0,r),filePath:t}}async exportPreview(e){let t=this.cm.getDriver(e.connectionId,e.database);return an(t,{schema:e.schema,table:e.table,format:e.format,columns:e.columns,keyColumns:e.keyColumns,delimiter:e.delimiter,filters:e.filters,sort:e.sort,limit:e.limit,autoJoins:e.autoJoins})}async exportPreviewRows(e){let t=this.cm.getDriver(e.connectionId,e.database),{sql:n,params:r}=Te({schema:e.schema,table:e.table,format:"csv",columns:e.columns,filters:e.filters,sort:e.sort,autoJoins:e.autoJoins},t),s=r.length+1,i=`${n} LIMIT ${t.placeholder(s)}`,a=(await t.execute(i,[...r,e.limit])).rows,c=a.length>0?Object.keys(a[0]):e.columns??[];return{rows:a,columns:c}}async importData(e){this.rejectServerFileAccess(e.filePath);let t=this.cm.getDriver(e.connectionId,e.database),n=this.resolveImportStream(e.filePath,e.fileContent),r=this.emitMessage?(s)=>this.emitMessage("import.progress",{rowCount:s}):void 0;return ve(t,n,{schema:e.schema,table:e.table,format:e.format,delimiter:e.delimiter,hasHeader:e.hasHeader,mappings:e.mappings,batchSize:e.batchSize},void 0,r)}async importPreview(e){this.rejectServerFileAccess(e.filePath);let t=this.resolveImportPreviewStream(e.filePath,e.fileContent),n=await dn(t,{format:e.format,delimiter:e.delimiter,hasHeader:e.hasHeader,limit:e.limit});if(e.filePath)try{let r=Bun.file(e.filePath);n.fileSizeBytes=r.size}catch{}return n}rejectServerFileAccess(e){if(!this.allowServerFileAccess&&e!==void 0)throw Error("Server file access is not available in this runtime")}rejectServerSqliteConfig(e){if(e?.type==="sqlite")this.rejectServerFileAccess(e.path)}resolveImportStream(e,t){if(e)return Bun.file(e).stream();if(t!==void 0)return new ReadableStream({start(n){n.enqueue(new TextEncoder().encode(t)),n.close()}});throw Error("Import requires either filePath or fileContent")}resolveImportPreviewStream(e,t){if(e){let s=Bun.file(e).stream().getReader(),i=65536,o=0;return new ReadableStream({async pull(a){let{done:c,value:u}=await s.read();if(c){a.close();return}if(o+=u.byteLength,o>=65536){a.enqueue(u),a.close(),s.releaseLock();return}a.enqueue(u)},cancel(){s.releaseLock()}})}if(t!==void 0)return new ReadableStream({start(n){n.enqueue(new TextEncoder().encode(t)),n.close()}});throw Error("Import preview requires either filePath or fileContent")}getAllSettings(){return this.appDb.getAllSettings()}setSetting(e,t){this.appDb.setSetting(e,t)}async encryptSecrets(e){if(!this.encryption)throw Error("Encryption not available");return this.encryption.encrypt(e)}async decryptConfig(e){if(!this.encryption)throw Error("Encryption not available");return this.encryption.decrypt(e)}async showOpenDialog({filters:e,multiple:t}){if(!this.Utils)throw Error("Utils not available");let n=e&&e.length>0?e.flatMap((i)=>i.extensions.map((o)=>`*.${o}`)).join(","):"*",s=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:n,canChooseFiles:!0,canChooseDirectory:!1,allowsMultipleSelection:t??!1})).filter((i)=>i!=="");return{paths:s,cancelled:s.length===0}}async showSaveDialog({defaultName:e}){if(!this.Utils)throw Error("Utils not available");let n=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:"*",canChooseFiles:!1,canChooseDirectory:!0,allowsMultipleSelection:!1}))[0];if(!n||n==="")return{path:null,cancelled:!0};return{path:e?`${n}/${e}`:n,cancelled:!1}}formatSql(e){return Yn(e)}async generateSql(e){let t=this.cm.getDriver(e.connectionId,e.database),n=await t.loadSchema(),r=kn(n),s=Ln(this.appDb.getAllSettings());return{sql:await $n(s,{prompt:e.prompt,schemaContext:r,dialect:t.getDriverType()})}}saveWorkspace(e){this.appDb.saveWorkspace(e)}loadWorkspace(){return this.appDb.loadWorkspace()}async initializeDemo(){if(!this.demoDbSourcePath||!this.demoDbTargetPath)throw Error("Demo database paths not configured");let e=Bun.file(this.demoDbSourcePath);if(!await e.exists())throw Error('Demo database source not found. Run "bun run seed:sqlite" first.');await Bun.write(this.demoDbTargetPath,e);let t={type:"sqlite",path:this.demoDbTargetPath},n=this.appDb.createConnection({name:"Bookstore (Demo)",config:t});return await this.cm.connect(n.id),n}agentHello(){return{version:this.appVersion,mode:this.mode,pid:process.pid,protocol:Ms}}proposeWrite(e){return this.proposals.create(e)}listProposals(e){return this.proposals.list(e)}getProposal(e){return this.proposals.get(e)}async waitForProposal(e,t){return this.proposals.wait(e,t)}cancelProposal(e){return this.proposals.cancel(e)}resolveProposal(e){return this.proposals.resolve(e)}getUiSnapshot(){return this.uiSnapshot??{tabs:[],activeTabId:null,activeConnectionId:null,updatedAt:0}}setUiSnapshot(e){this.uiSnapshot=e}sendUiCommand(e){this.emitMessage?.("cli.command",e)}getSessionManager(){return this.sessionManager}dispose(){this.unsubscribeProposals(),this.proposals.dispose()}}var Ms=1;var Wn=T(()=>{le();Pn();tt();rt();qn();xe();Hn();Kn()});function Fs(e,t){if(e===void 0)return;let n=e.trim();if(n==="")return;if(!ot(n,t))throw Error("where must be a single boolean expression: no statement separators, comments, unbalanced parentheses or backslashes in quoted text")}function Hs(e,t){return e.listConnections().find((n)=>n.id===t)?.config.type}function Me(e,t){if(!t)throw Error("connectionId is required");if(!e.listConnections().some((n)=>n.id===t))throw Error(`Unknown connection: ${t}`)}async function jn(e,t){try{await e.destroySession(t)}catch(n){console.warn(`Failed to destroy agent session ${t}`,n)}}async function bt(e,t,n,r){Me(e,t);let s=await e.createSession(t,n,{readOnly:!0,label:qs});if(s.readOnly!==!0)throw await jn(e,s.sessionId),new b("READ_ONLY_SESSION","The database did not confirm a read-only agent session");try{return await r(s.sessionId)}finally{await jn(e,s.sessionId)}}function Bs(e){if(e===void 0)return $s;if(!Number.isFinite(e)||e<0)throw Error("timeoutMs must be a non-negative number");return Math.min(e,Us)}function zn(e){return{"connections.list":()=>e.listConnections(),"connections.create":({name:t,config:n,readOnly:r,color:s,groupName:i})=>e.createConnection({name:t,config:n,readOnly:r,color:s,groupName:i}),"connections.update":({id:t,name:n,config:r,readOnly:s,color:i,groupName:o})=>e.updateConnection({id:t,name:n,config:r,readOnly:s,color:i,groupName:o}),"connections.setReadOnly":({id:t,readOnly:n})=>e.setConnectionReadOnly(t,n),"connections.setGroup":({id:t,groupName:n})=>e.setConnectionGroup(t,n),"connections.listGroups":()=>e.listConnectionGroups(),"connections.renameGroup":({oldName:t,newName:n})=>{e.renameConnectionGroup(t,n)},"connections.deleteGroup":({groupName:t})=>{e.deleteConnectionGroup(t)},"connections.delete":async({id:t})=>{await e.deleteConnection(t)},"connections.test":async({config:t})=>e.testConnection(t),"connections.connect":async({connectionId:t,password:n,config:r,encryptedSecrets:s,name:i,encryptedConfig:o})=>{await e.connect(t,n,{config:r,encryptedSecrets:s,name:i,encryptedConfig:o})},"connections.disconnect":async({connectionId:t})=>{await e.disconnect(t)},"connections.listOpenHandles":()=>e.listConnectionHandles(),"connections.terminateHandle":async({connectionId:t,database:n,handleId:r})=>{await e.terminateConnectionHandle(t,n,r)},"session.create":async({connectionId:t,database:n,readOnly:r,label:s})=>e.createSession(t,n,{readOnly:r,label:s}),"session.destroy":async({sessionId:t})=>{await e.destroySession(t)},"session.list":({connectionId:t})=>e.listSessions(t),"databases.list":async({connectionId:t})=>e.listDatabases(t),"databases.listForConfig":async({config:t})=>e.listDatabasesForConfig(t),"databases.activate":async({connectionId:t,database:n})=>{await e.activateDatabase(t,n)},"databases.deactivate":async({connectionId:t,database:n})=>{await e.deactivateDatabase(t,n)},"schema.load":async({connectionId:t,database:n,sessionId:r})=>e.getDriver(t,n).loadSchema(r),"query.execute":async({connectionId:t,sql:n,queryId:r,params:s,database:i,statements:o,sessionId:a,searchPath:c})=>{if(o&&o.length>0)return e.executeStatements(t,o,i,a);return e.executeQuery(t,n,s,r,i,a,c)},"query.submit":({connectionId:t,sql:n,queryId:r,params:s,database:i,sessionId:o,searchPath:a})=>(e.submitQuery(t,n,s,r,i,o,a),{queryId:r}),"query.submitExplain":({connectionId:t,sql:n,analyze:r,queryId:s,database:i,sessionId:o,searchPath:a})=>(e.submitExplain(t,n,r??!1,s,i,o,a),{queryId:s}),"query.cancel":async({queryId:t})=>({cancelled:await e.cancelQuery(t)}),"query.format":({sql:t})=>({sql:e.formatSql(t)}),"tx.begin":async({connectionId:t,database:n,sessionId:r})=>{await e.beginTransaction(t,n,r)},"tx.commit":async({connectionId:t,database:n,sessionId:r})=>{await e.commitTransaction(t,n,r)},"tx.rollback":async({connectionId:t,database:n,sessionId:r})=>{await e.rollbackTransaction(t,n,r)},"transaction.getLog":(t)=>e.getTransactionLog(t),"transaction.clearLog":({connectionId:t,database:n,sessionId:r})=>{e.clearTransactionLog(t,n,r)},"search.searchDatabase":async(t)=>e.searchDatabase(t),"export.exportData":async(t)=>e.exportData(t),"export.preview":async(t)=>({content:await e.exportPreview(t)}),"export.previewRows":async(t)=>e.exportPreviewRows(t),"import.importData":async(t)=>e.importData(t),"import.preview":async(t)=>e.importPreview(t),"history.list":(t)=>e.listHistory(t),"history.clear":({connectionId:t})=>{e.clearHistory(t)},"views.save":({connectionId:t,schemaName:n,tableName:r,name:s,config:i})=>{if(!s?.trim())throw Error("View name is required");if(!t)throw Error("connectionId is required");if(!r)throw Error("tableName is required");if(e.listSavedViews(t,n,r).some((a)=>a.name===s.trim()))throw Error(`A view named "${s.trim()}" already exists for this table`);return e.createSavedView({connectionId:t,schemaName:n,tableName:r,name:s.trim(),config:i})},"views.update":({id:t,name:n,config:r})=>{if(!t)throw Error("View id is required");if(!n?.trim())throw Error("View name is required");let s=e.getSavedViewById(t);if(!s)throw Error(`Saved view not found: ${t}`);if(e.listSavedViews(s.connectionId,s.schemaName,s.tableName).some((o)=>o.id!==t&&o.name===n.trim()))throw Error(`A view named "${n.trim()}" already exists for this table`);return e.updateSavedView({id:t,name:n.trim(),config:r})},"views.delete":({id:t})=>{e.deleteSavedView(t)},"views.listByConnection":({connectionId:t})=>e.listSavedViewsByConnection(t),"bookmarks.list":({connectionId:t,search:n})=>e.listBookmarks(t,n),"bookmarks.create":({connectionId:t,database:n,name:r,description:s,sql:i})=>{if(!r?.trim())throw Error("Bookmark name is required");return e.createBookmark({connectionId:t,database:n,name:r.trim(),description:s,sql:i})},"bookmarks.update":({id:t,name:n,description:r,sql:s})=>{if(!t)throw Error("Bookmark id is required");if(!n?.trim())throw Error("Bookmark name is required");return e.updateBookmark({id:t,name:n.trim(),description:r,sql:s})},"bookmarks.delete":({id:t})=>{e.deleteBookmark(t)},"settings.getAll":()=>e.getAllSettings(),"settings.set":({key:t,value:n})=>{e.setSetting(t,n)},"storage.encryptSecrets":async({secrets:t})=>{if(!e.encryptSecrets)throw Error("Encryption not available");return{encryptedSecrets:await e.encryptSecrets(t)}},"storage.decryptConfig":async({encryptedConfig:t})=>{if(!e.decryptConfig)throw Error("Encryption not available");return{config:await e.decryptConfig(t)}},"ai.generateSql":async(t)=>e.generateSql(t),"workspace.save":({data:t})=>{e.saveWorkspace(t)},"workspace.load":()=>e.loadWorkspace(),"system.showOpenDialog":async(t)=>{if(!e.showOpenDialog)return{paths:[],cancelled:!0};return e.showOpenDialog(t)},"system.showSaveDialog":async(t)=>{if(!e.showSaveDialog)return{path:null,cancelled:!0};return e.showSaveDialog(t)},"agent.hello":()=>e.agentHello(),"agent.schema":async({connectionId:t,database:n})=>bt(e,t,n,(r)=>e.getDriver(t,n).loadSchema(r)),"agent.query":async({connectionId:t,database:n,sql:r,queryId:s,params:i,searchPath:o})=>{if(!r?.trim())throw Error("sql is required");if(!s)throw Error("queryId is required");return bt(e,t,n,(a)=>e.executeQuery(t,r,i,s,n,a,o))},"agent.search":async(t)=>bt(e,t.connectionId,t.database,(n)=>e.searchDatabase({...t,sessionId:n})),"agent.proposeWrite":({connectionId:t,database:n,sql:r,reason:s})=>{if(Me(e,t),!r?.trim())throw Error("sql is required");return{proposalId:e.proposeWrite({connectionId:t,database:n,sql:r.trim(),reason:s?.trim()||void 0}).id}},"agent.proposals.list":(t)=>e.listProposals(t),"agent.proposals.get":({proposalId:t})=>{if(!t)throw Error("proposalId is required");let n=e.getProposal(t);if(!n)throw Error(`Proposal not found: ${t}`);return n},"agent.proposals.wait":async({proposalId:t,timeoutMs:n})=>{if(!t)throw Error("proposalId is required");return e.waitForProposal(t,Bs(n))},"agent.proposals.cancel":({proposalId:t})=>{if(!t)throw Error("proposalId is required");e.cancelProposal(t)},"agent.proposals.resolve":({proposalId:t,status:n,result:r,error:s})=>{if(!t)throw Error("proposalId is required");if(!n)throw Error("status is required");return e.resolveProposal({proposalId:t,status:n,result:r,error:s})},"ui.state":()=>e.getUiSnapshot(),"ui.openTable":({connectionId:t,database:n,schema:r,table:s,where:i,limit:o})=>{if(Me(e,t),!s?.trim())throw Error("table is required");if(o!==void 0&&(!Number.isInteger(o)||o<=0))throw Error("limit must be a positive integer");return Fs(i,Hs(e,t)),e.sendUiCommand({kind:"open-table",connectionId:t,database:n,schema:r??"",table:s.trim(),where:i,limit:o}),{ok:!0}},"ui.openConsole":({connectionId:t,database:n,sql:r})=>(Me(e,t),e.sendUiCommand({kind:"open-console",connectionId:t,database:n,sql:r}),{ok:!0}),"ui.snapshot.set":({snapshot:t})=>{if(!t||!Array.isArray(t.tabs))throw Error("snapshot is required");e.setUiSnapshot(t)},"demo.initialize":async()=>{if(!e.initializeDemo)throw Error("Demo initialization is not available");return e.initializeDemo()}}}var Us=600000,$s=30000,qs="cli";var Gn=T(()=>{at();P()});function Qs(e){if(!e)throw Error("AppDatabase is required");return e}function Vn(e,t,n,r,s){let i=Qs(n),o=t??new ce(e,void 0,i),a=new gt(e,i,(u,l,m)=>{o.sessionLog.resetPendingCount(u,l,m)}),c=new Et(e,o,i,{encryption:s?.encryption,Utils:r,emitMessage:s?.emitMessage,sessionManager:a,demoDbSourcePath:s?.demoDbSourcePath,demoDbTargetPath:s?.demoDbTargetPath,allowServerFileAccess:s?.allowServerFileAccess,appVersion:s?.appVersion,mode:s?.mode});return{handlers:zn(c),sessionManager:a,adapter:c}}var Jn=T(()=>{xe();xn();Wn();Gn()});class Ct{inner;constructor(e){this.inner=e}log(e,t,n,r){let s=e.replace(/\s+/g," ").trim(),i=t&&t.length>0;if(r)console.debug(`[SQL ERROR] ${s}${i?` -- params: ${JSON.stringify(t)}`:""} (${n}ms)`,r);else if(n!==void 0)console.debug(`[SQL] ${s}${i?` -- params: ${JSON.stringify(t)}`:""} (${n}ms)`);else console.debug(`[SQL] ${s}${i?` -- params: ${JSON.stringify(t)}`:""}`)}async execute(e,t,n,r){let s=performance.now();try{let i=await this.inner.execute(e,t,n,r);return this.log(e,t,Math.round(performance.now()-s)),i}catch(i){throw this.log(e,t,Math.round(performance.now()-s),i),i}}async*iterate(e,t,n,r,s){this.log(e,t),yield*this.inner.iterate(e,t,n,r,s)}async importBatch(e,t,n,r){let s=`INSERT INTO ${e} (${t.join(", ")}) VALUES ... [${n.length} rows]`,i=performance.now();try{let o=await this.inner.importBatch(e,t,n,r);return this.log(s,void 0,Math.round(performance.now()-i)),o}catch(o){throw this.log(s,void 0,Math.round(performance.now()-i),o),o}}connect(e){return this.inner.connect(e)}disconnect(){return this.inner.disconnect()}isConnected(){return this.inner.isConnected()}reserveSession(e,t){return this.inner.reserveSession(e,t)}releaseSession(e){return this.inner.releaseSession(e)}getSessionIds(){return this.inner.getSessionIds()}isSessionReadOnly(e){return this.inner.isSessionReadOnly(e)}cancel(e,t){return this.inner.cancel(e,t)}ping(){return this.inner.ping()}async loadSchema(e){console.debug("[SQL] loadSchema started"+(e?` (session: ${e})`:""));let t=performance.now();try{let n=await this.inner.loadSchema(e),r=Object.values(n.tables).reduce((s,i)=>s+i.length,0);return console.debug(`[SQL] loadSchema completed \u2014 ${n.schemas.length} schemas, ${r} tables (${Math.round(performance.now()-t)}ms)`),n}catch(n){throw console.debug(`[SQL ERROR] loadSchema failed (${Math.round(performance.now()-t)}ms)`,n),n}}beginTransaction(e){return this.inner.beginTransaction(e)}commit(e){return this.inner.commit(e)}rollback(e){return this.inner.rollback(e)}inTransaction(e){return this.inner.inTransaction(e)}isTxAborted(e){return this.inner.isTxAborted(e)}isIterating(e){return this.inner.isIterating(e)}getDriverType(){return this.inner.getDriverType()}listConnectionHandles(){return this.inner.listConnectionHandles()}terminateConnectionHandle(e){return this.inner.terminateConnectionHandle(e)}quoteIdentifier(e){return this.inner.quoteIdentifier(e)}qualifyTable(e,t){return this.inner.qualifyTable(e,t)}emptyInsertSql(e){return this.inner.emptyInsertSql(e)}placeholder(e){return this.inner.placeholder(e)}}var{SQL:Ys}=globalThis.Bun;class pe{url;resetFn;initFn;systemConn=null;idleConn=null;idleTimer=null;connections=new Set;metadata=new Map;nextHandleNumber=1;constructor(e,t,n){this.url=e;this.resetFn=t;this.initFn=n}async connect(){if(this.systemConn=this.createSql("system"),this.connections.add(this.systemConn),await this.systemConn.unsafe("SELECT 1"),this.initFn)await this.initFn(this.systemConn)}getSystemConnection(){if(!this.systemConn)throw Error("ConnectionPool is not connected");return this.markUsed(this.systemConn),this.systemConn}async createConnection(){let e=this.createSql("leased");if(this.connections.add(e),this.initFn)try{await this.initFn(e)}catch(t){throw await this.destroyConnection(e),t}return e}async acquireConnection(){if(this.idleConn){let e=this.idleConn;return this.idleConn=null,this.clearIdleTimer(),this.setRole(e,"leased"),this.markUsed(e),e}return this.createConnection()}async releaseConnection(e){if(!this.connections.has(e)){try{await e.close()}catch{}return}if(!this.idleConn){if(this.resetFn||this.initFn)try{if(this.resetFn)await this.resetFn(e);if(this.initFn)await this.initFn(e)}catch{await this.destroyConnection(e);return}this.setRole(e,"idle"),this.markUsed(e),this.idleConn=e,this.scheduleIdleTimeout()}else await this.destroyConnection(e)}async destroyConnection(e){if(this.idleConn===e)this.idleConn=null,this.clearIdleTimer();if(this.systemConn===e)this.systemConn=null;this.connections.delete(e),this.metadata.delete(e);try{await e.close()}catch{}}async reconnectSystemConnection(){if(this.systemConn)await this.destroyConnection(this.systemConn);let e=this.createSql("system");this.connections.add(e);try{if(await e.unsafe("SELECT 1"),this.initFn)await this.initFn(e)}catch(t){throw await this.destroyConnection(e),t}this.systemConn=e}async disconnectAll(){this.clearIdleTimer(),this.idleConn=null;let e=[...this.connections];this.connections.clear(),this.metadata.clear(),this.systemConn=null,await Promise.allSettled(e.map((t)=>t.close()))}getConnectionId(e){return this.metadata.get(e)?.handleId}snapshot(){return[...this.connections].map((e)=>this.metadata.get(e)).filter((e)=>e!==void 0).map((e)=>({...e}))}async terminateConnection(e){let t=this.findConnectionByHandleId(e);if(!t)return!1;if(t===this.systemConn)return await this.reconnectSystemConnection(),!0;return await this.destroyConnection(t),!0}createSql(e){let t=new Ys({url:this.url,max:1}),n=Date.now();return this.metadata.set(t,{handleId:`pool-${this.nextHandleNumber}`,role:e,createdAt:n,lastUsedAt:n}),this.nextHandleNumber+=1,t}findConnectionByHandleId(e){for(let t of this.connections)if(this.metadata.get(t)?.handleId===e)return t;return}markUsed(e){let t=this.metadata.get(e);if(!t)return;t.lastUsedAt=Date.now()}setRole(e,t){let n=this.metadata.get(e);if(!n)return;n.role=t}scheduleIdleTimeout(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{if(this.idleConn)this.destroyConnection(this.idleConn)},Ks)}clearIdleTimer(){if(this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null}}var Ks=30000;var Tt=()=>{};function fe(e){let t=e instanceof Error?e.message:String(e),n=e?.errno??e?.code;if(n==="57014")return new R("QUERY_CANCELED",t,{cause:e});if(/ECONNREFUSED|connection refused/i.test(t))return new D("CONNECTION_REFUSED",t,{cause:e});if(/timeout|timed out/i.test(t))return new D("CONNECTION_TIMEOUT",t,{cause:e});if(/ENOTFOUND|getaddrinfo/i.test(t))return new D("HOST_NOT_FOUND",t,{cause:e});if(/too many connections|connection limit/i.test(t))return new D("CONNECTION_LIMIT",t,{cause:e});if(/SSL|TLS|certificate/i.test(t))return new D("SSL_ERROR",t,{cause:e});if(n?.startsWith("28")||/authentication failed|password authentication/i.test(t))return new Se(t,{cause:e});if(n==="3D000"||/database .* does not exist/i.test(t))return new D("DATABASE_NOT_FOUND",t,{cause:e});if(n==="23505"||/violates unique constraint|duplicate key/i.test(t))return new _("CONSTRAINT_UNIQUE",t,{cause:e});if(n==="23503"||/violates foreign key constraint/i.test(t))return new _("CONSTRAINT_FK",t,{cause:e});if(n==="23514"||/violates check constraint/i.test(t))return new _("CONSTRAINT_CHECK",t,{cause:e});if(n==="23502"||/violates not-null constraint/i.test(t))return new _("CONSTRAINT_NOT_NULL",t,{cause:e});if(n==="42601"||/syntax error/i.test(t))return new R("QUERY_SYNTAX",t,{cause:e});if(n==="42P01"||/relation .* does not exist/i.test(t))return new R("TABLE_NOT_FOUND",t,{cause:e});if(n==="42703"||/column .* does not exist/i.test(t))return new R("COLUMN_NOT_FOUND",t,{cause:e});if(n==="42501"||/permission denied/i.test(t))return new b("PERMISSION_DENIED",t,{cause:e});if(n==="40001")return new R("SERIALIZATION_FAILURE",t,{cause:e});if(n==="40P01")return new R("DEADLOCK_DETECTED",t,{cause:e});if(n==="25P02")return new R("TRANSACTION_ABORTED",t,{cause:e});if(n?.startsWith("42")||n?.startsWith("22"))return new R("QUERY_EXECUTION",t,{cause:e});return new b("UNKNOWN",t,{cause:e})}function ee(e){let t=e instanceof Error?e.message:String(e);if(/unable to open database|cannot open/i.test(t))return new D("CONNECTION_REFUSED",t,{cause:e});if(/UNIQUE constraint failed/i.test(t))return new _("CONSTRAINT_UNIQUE",t,{cause:e});if(/FOREIGN KEY constraint failed/i.test(t))return new _("CONSTRAINT_FK",t,{cause:e});if(/CHECK constraint failed/i.test(t))return new _("CONSTRAINT_CHECK",t,{cause:e});if(/NOT NULL constraint failed/i.test(t))return new _("CONSTRAINT_NOT_NULL",t,{cause:e});if(/no such table/i.test(t))return new R("TABLE_NOT_FOUND",t,{cause:e});if(/no such column/i.test(t))return new R("COLUMN_NOT_FOUND",t,{cause:e});if(/syntax error|near /i.test(t))return new R("QUERY_SYNTAX",t,{cause:e});if(/authorization denied|not authorized/i.test(t))return new b("PERMISSION_DENIED",t,{cause:e});return new b("UNKNOWN",t,{cause:e})}function Ue(e){let t=e instanceof Error?e.message:String(e),n=e?.errno;if(n===3024||n===1969)return new R("QUERY_CANCELED",t,{cause:e});if(/ECONNREFUSED|connection refused/i.test(t)||n===2003)return new D("CONNECTION_REFUSED",t,{cause:e});if(/timeout|timed out/i.test(t))return new D("CONNECTION_TIMEOUT",t,{cause:e});if(/ENOTFOUND|getaddrinfo/i.test(t))return new D("HOST_NOT_FOUND",t,{cause:e});if(/too many connections/i.test(t)||n===1040)return new D("CONNECTION_LIMIT",t,{cause:e});if(/SSL|TLS|certificate/i.test(t))return new D("SSL_ERROR",t,{cause:e});if(n===1045||/access denied/i.test(t))return new Se(t,{cause:e});if(n===1049||/unknown database/i.test(t))return new D("DATABASE_NOT_FOUND",t,{cause:e});if(n===1062||/duplicate entry/i.test(t))return new _("CONSTRAINT_UNIQUE",t,{cause:e});if(n===1451||n===1452||/foreign key constraint/i.test(t)||/cannot delete or update a parent row/i.test(t)||/cannot add or update a child row/i.test(t))return new _("CONSTRAINT_FK",t,{cause:e});if(n===3819||/check constraint/i.test(t))return new _("CONSTRAINT_CHECK",t,{cause:e});if(n===1048||/cannot be null/i.test(t))return new _("CONSTRAINT_NOT_NULL",t,{cause:e});if(n===1213||/deadlock found/i.test(t))return new R("DEADLOCK_DETECTED",t,{cause:e});if(n===1205||/lock wait timeout exceeded/i.test(t))return new R("SERIALIZATION_FAILURE",t,{cause:e});if(n===1064||/syntax error|you have an error in your sql syntax/i.test(t))return new R("QUERY_SYNTAX",t,{cause:e});if(n===1146||/table .* doesn't exist/i.test(t))return new R("TABLE_NOT_FOUND",t,{cause:e});if(n===1054||/unknown column/i.test(t))return new R("COLUMN_NOT_FOUND",t,{cause:e});if(n===1142||n===1143||/command denied|access denied/i.test(t))return new b("PERMISSION_DENIED",t,{cause:e});return new b("UNKNOWN",t,{cause:e})}var $e=T(()=>{P()});function te(e){let t=e;if(typeof t.affectedRows==="number")return t.affectedRows;if(typeof t.count==="number")return t.count;return 0}var Zo,ea,ta,na,ra,sa;var Xn=T(()=>{M();Zo=new Set(["integer","serial","float","numeric"]),ea=new Set(["boolean"]),ta=new Set(["timestamp","date"]),na=new Set(["text","varchar","char"]),ra=new Set(["json"]),sa=new Set(["array"])});var Zn=T(()=>{Xn();M()});var er=T(()=>{Ce();G();Zn()});function ne(e,t){let n=z(t).trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(n)){if(e.txActive=!0,"txAborted"in e)e.txAborted=!1}else if(/^(COMMIT|END)\b/.test(n)){if(e.txActive=!1,"txAborted"in e)e.txAborted=!1}else if(/^ROLLBACK\b/.test(n)&&!/^ROLLBACK\s+TO\b/.test(n)){if(e.txActive=!1,"txAborted"in e)e.txAborted=!1}}function B(e){let t=e?.code;if(typeof t==="string"&&/^(ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|ENOTCONN)$/.test(t))return!0;let n=e instanceof Error?e.message:String(e);return/ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|connection (terminated|ended|closed|lost|reset)|socket.*(closed|hang up|end)|write after end|broken pipe|network/i.test(n)}async function x(e,t){if(t?.rollback)try{await e.unsafe("ROLLBACK")}catch{}try{await e.close()}catch{}}var qe=T(()=>{er()});function Ws(e){switch(e.toLowerCase()){case"int":case"integer":case"bigint":case"smallint":case"tinyint":case"mediumint":return"integer";case"float":case"double":return"float";case"decimal":case"numeric":return"numeric";case"bit":case"boolean":case"bool":return"boolean";case"text":case"tinytext":case"mediumtext":case"longtext":return"text";case"varchar":return"varchar";case"char":return"char";case"date":return"date";case"time":return"time";case"datetime":case"timestamp":return"timestamp";case"json":return"json";case"binary":case"varbinary":case"blob":case"tinyblob":case"mediumblob":case"longblob":return"binary";case"enum":case"set":return"enum";default:return"unknown"}}class At{pool=null;connected=!1;sessions=new Map;readOnlySessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;async connect(e){if(e.type!=="mysql")throw Error("MysqlDriver requires a mysql connection config");let t=`mysql://${encodeURIComponent(e.user)}:${encodeURIComponent(e.password)}@${e.host}:${e.port}/${encodeURIComponent(e.database)}`,n=e.initSql?.trim(),r=n?async(s)=>{await s.unsafe(n)}:void 0;this.pool=new pe(t,(s)=>s.unsafe("RESET CONNECTION"),r);try{await this.pool.connect()}catch(s){let i=this.pool;throw this.pool=null,await i.disconnectAll().catch(()=>{}),s instanceof b?s:Ue(s)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,e]of this.sessions)await x(e.conn,{rollback:e.txActive});if(this.sessions.clear(),this.readOnlySessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession(e,t){if(this.ensureConnected(),this.sessions.has(e))throw Error(`Session "${e}" already exists`);let n=await this.pool.createConnection();if(t?.readOnly){let r=["SET SESSION TRANSACTION READ ONLY"];r.push("SET NAMES utf8mb4");try{for(let i of r)await n.unsafe(i);let s=Math.floor(t.statementTimeoutMs??0);if(Number.isFinite(s)&&s>0)r.push(await this.setStatementTimeout(n,s))}catch(s){throw await x(n),await this.pool.destroyConnection(n),s instanceof b?s:Ue(s)}this.readOnlySessions.set(e,r)}this.sessions.set(e,{conn:n,txActive:!1,iterating:!1,activeQueries:new Set})}async releaseSession(e){this.readOnlySessions.delete(e);let t=this.sessions.get(e);if(!t)return;if(this.sessions.delete(e),await x(t.conn,{rollback:!0}),this.pool)await this.pool.destroyConnection(t.conn)}getSessionIds(){return[...this.sessions.keys()].filter((e)=>e!==I)}isSessionReadOnly(e){return this.readOnlySessions.has(e)}async reassertReadOnly(e,t){let n=e===void 0?void 0:this.readOnlySessions.get(e);if(!n)return;for(let r of n)await t.unsafe(r)}async execute(e,t,n,r){this.ensureConnected();let s=this.resolveSession(n),i=s?s.conn:await this.pool.acquireConnection(),o=!s;if(s)await this.reassertReadOnly(n,i);let a=performance.now(),c=i.unsafe(e,t??[]),u=s?void 0:r??Symbol();if(s)s.activeQueries.add(c);else this.poolActiveQueries.set(u,c);try{let l=await c,m=Math.round(performance.now()-a),f=[...l];if(s)ne(s,e);return{columns:f.length>0?Object.keys(f[0]).map((d)=>({name:d,dataType:"unknown"})):[],rows:f,rowCount:f.length,affectedRows:te(l),durationMs:m}}catch(l){throw l instanceof b?l:Ue(l)}finally{if(s)s.activeQueries.delete(c);else if(this.poolActiveQueries.delete(u),o)await this.pool.releaseConnection(i)}}async cancel(e,t){if(e){let n=this.sessions.get(e);if(n){for(let r of n.activeQueries)r.cancel();n.activeQueries.clear()}}else if(t){let n=this.poolActiveQueries.get(t);if(n)n.cancel(),this.poolActiveQueries.delete(t)}else{for(let n of this.poolActiveQueries.values())n.cancel();this.poolActiveQueries.clear()}}async loadSchema(e){this.ensureConnected();let t=this.resolveSession(e),n=t?t.conn:this.pool.getSystemConnection(),r=await this.getSchemas(n),s=r.map((d)=>d.name),i={};for(let d of r)i[d.name]=await this.getTables(n,d.name);let[o,a,c,u]=await Promise.all([n.unsafe(`SELECT
157
+ Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.status===401)throw Error("Invalid API key. Check your AI settings.");if(s.status===429)throw Error("Rate limited. Please wait and try again.");throw Error(`OpenAI API error (${s.status}): ${o.slice(0,200)}`)}let i=await s.json();return Gn(i.choices?.[0]?.message?.content??"")}async function si(e,t){if(!e.endpoint)throw Error("Custom AI endpoint URL is required. Check your AI settings.");return Vn(e,t)}function Gn(e){let t=e.trim(),n=t.match(/^```(?:sql)?\s*\n?([\s\S]*?)\n?```$/);if(n)t=n[1].trim();return t}async function Jn(e,t){if(!e.apiKey)throw Error("AI API key not configured. Go to AI Settings (command palette) to set it up.");switch(e.provider){case"anthropic":return ri(e,t);case"openai":return Vn(e,t);case"custom":return si(e,t);default:throw Error(`Unknown AI provider: ${e.provider}`)}}function Tt(e){return e!=="pending"&&e!=="approved"}class At{proposals=new Map;waiters=new Map;observers=new Set;ttlMs;now;disposed=!1;constructor(e){this.ttlMs=e?.ttlMs??3600000,this.now=e?.now??(()=>Date.now())}create(e){this.assertUsable(),this.sweep();let t=[...this.proposals.values()].filter((r)=>r.status==="pending").length;if(t>=20)throw Error(`${t} proposals are already waiting for approval \u2014 wait for the user or cancel some first`);let n={id:crypto.randomUUID(),connectionId:e.connectionId,connectionName:e.connectionName,database:e.database,sql:e.sql,reason:e.reason,requestedBy:e.requestedBy,status:"pending",createdAt:this.now()};return this.proposals.set(n.id,n),this.notify(n),{...n}}get(e){this.sweep();let t=this.proposals.get(e);return t?{...t}:null}list(e){this.sweep();let t=[...this.proposals.values()];if(e?.status)t=t.filter((n)=>n.status===e.status);if(e?.connectionId)t=t.filter((n)=>n.connectionId===e.connectionId);return t.map((n)=>({...n}))}resolve(e){if(this.assertUsable(),this.sweep(),!ii.includes(e.status))throw Error(`Cannot resolve a proposal to status "${e.status}"`);let t=this.require(e.proposalId);if(t.status==="approved"&&t.resolvedVia==="remote")throw Error(`Proposal ${t.id} is already approved remotely`);return this.transition(t,e.status,e.result,e.error,{via:"app"})}claimRemote(e,t){this.assertUsable(),this.sweep();let n=this.require(e);if(n.status!=="pending")throw Error(`Proposal ${e} is already ${n.status}`);return this.transition(n,"approved",void 0,void 0,{via:"remote",approver:t})}rejectRemote(e,t){this.assertUsable(),this.sweep();let n=this.require(e);if(n.status!=="pending")throw Error(`Proposal ${e} is already ${n.status}`);return this.transition(n,"rejected",void 0,void 0,{via:"remote",approver:t})}settleRemote(e,t,n,r){this.assertUsable();let s=this.require(e);if(s.status!=="approved"||s.resolvedVia!=="remote")throw Error(`Proposal ${e} was not claimed by a remote approval`);return this.transition(s,t,n,r)}cancel(e){return this.assertUsable(),this.sweep(),this.transition(this.require(e),"cancelled")}async wait(e,t){this.assertUsable(),this.sweep();let n=this.require(e);if(Tt(n.status))return{...n};return new Promise((r)=>{let s,i=(o,a)=>{if(!a&&!Tt(o.status))return;if(s!==void 0)clearTimeout(s);this.removeWaiter(e,i),r({...o})};this.addWaiter(e,i),s=setTimeout(()=>{this.removeWaiter(e,i),this.sweep();let o=this.proposals.get(e);r({...o??n})},t)})}waiterCount(){let e=0;for(let t of this.waiters.values())e+=t.size;return e}dispose(){this.disposed=!0;for(let[e,t]of[...this.waiters]){let n=this.proposals.get(e);if(!n)continue;for(let r of[...t])r(n,!0)}this.waiters.clear(),this.observers.clear(),this.proposals.clear()}require(e){let t=this.proposals.get(e);if(!t)throw Error(`Proposal not found: ${e}`);return t}transition(e,t,n,r,s){if(!(e.status==="pending"||e.status==="approved"&&oi.includes(t)))throw Error(`Proposal ${e.id} is already ${e.status}`);if(e.status==="pending"&&s&&(t==="approved"||t==="rejected")){if(e.resolvedVia=s.via,s.approver!==void 0)e.approver=s.approver}if(e.status=t,e.resolvedAt=this.now(),n!==void 0)e.result=n;if(r!==void 0)e.error=r;return this.notify(e),{...e}}sweep(){let e=this.now(),t=e-this.ttlMs;for(let[n,r]of this.proposals){if(r.status==="pending"){if(r.createdAt>t)continue;r.status="expired",r.resolvedAt=e,this.notify(r);continue}if(r.status==="approved"){if(r.resolvedVia==="remote")continue;if((r.resolvedAt??r.createdAt)>t)continue;r.status="failed",r.error="The app claimed this proposal but never reported the outcome. The statement may have run \u2014 check the data.",r.resolvedAt=e,this.notify(r);continue}if((r.resolvedAt??r.createdAt)<=t)this.proposals.delete(n)}this.evictOverflow()}evictOverflow(){if(this.proposals.size<=500)return;for(let[e,t]of this.proposals){if(this.proposals.size<=500)return;if(!Tt(t.status))continue;this.proposals.delete(e)}}onChange(e){return this.observers.add(e),()=>this.observers.delete(e)}notify(e){for(let n of[...this.observers])n({...e});let t=this.waiters.get(e.id);if(!t)return;for(let n of[...t])n(e)}addWaiter(e,t){let n=this.waiters.get(e);if(n){n.add(t);return}this.waiters.set(e,new Set([t]))}removeWaiter(e,t){let n=this.waiters.get(e);if(!n)return;if(n.delete(t),n.size===0)this.waiters.delete(e)}assertUsable(){if(this.disposed)throw Error("ProposalStore has been disposed")}}var ii,oi;var Xn=C(()=>{ii=["approved","rejected","executed","failed","cancelled","expired"],oi=["executed","failed"]});function tr(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Q(e){if(!/^[A-Za-z0-9_-]*$/.test(e)||e.length%4===1)throw Error("Invalid base64url");let t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),n=atob(t),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}function ci(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}function li(e){let t="",n=0,r=0;for(let s of e){n=n<<8|s,r+=8;while(r>=5)t+=er[n>>>r-5&31],r-=5;n&=(1<<r)-1}if(r>0)t+=er[n<<5-r&31];return t}async function Nt(e){return new Uint8Array(await crypto.subtle.digest("SHA-256",new Uint8Array(e)))}async function Dt(e){return ci(await Nt(new TextEncoder().encode(e)))}async function nr(e,t,n){let r=JSON.stringify([e,t,n.id,n.connectionId,n.connectionName,n.database??null,await Dt(n.sql),n.reason??null,n.requestedBy??null,n.createdAt]);return Nt(new TextEncoder().encode(ai+r))}async function rr(e,t){let n=Q(e),r=Q(t),s=new Uint8Array(n.length+r.length);return s.set(n,0),s.set(r,n.length),li(await Nt(s)).slice(0,16)}function vt(e){return ui.test(e)||di.test(e)}function fi(e){for(let t of e)if(t.charCodeAt(0)<128&&!mi.test(t))return!0;return!1}function sr(e){return e.split(";").map((t)=>t.trim()).filter((t)=>t!=="")}function gi(e){return x(e).length!==sr(e).length}function Si(e){let t=F(e).toUpperCase(),n=0,r=!1;for(let[s]of t.matchAll(/[(),]|[A-Z_][A-Z0-9_]*/g))if(s==="(")n++,r=!1;else if(s===")")n--,r=n===0;else if(n===0&&r){if(s==="AS"||s===","){r=!1;continue}return yi.has(s)?s:null}return null}function Ei(e){return/[^\x00-\x7F]/.test(F(e))}function bi(e){return sr(e).some((t)=>{let n=t.replace(/^[(\s]+/,"");if(!hi.test(n))return!0;if(!/^WITH\b/i.test(n))return!1;let r=Si(n);return r===null||!wi.has(r)})}function ir(e){if(new TextEncoder().encode(e.sql).length>Zn)return`The SQL is longer than ${Zn/1024} KB. Approve it in the Dotaz window.`;if(vt(e.sql))return"The SQL contains invisible, bidirectional, control or bare carriage-return characters. Approve it in the Dotaz window.";if(pi.test(e.sql))return"The SQL contains comment syntax (--, /* */ or #), which some engines execute. Approve it in the Dotaz window.";if(fi(e.sql))return"The SQL contains a backtick, backslash, dollar sign or square bracket, which engines quote differently. Approve it in the Dotaz window.";if(Ei(e.sql))return"The SQL contains non-ASCII characters outside quoted strings and identifiers. Approve it in the Dotaz window.";if(gi(e.sql))return"The SQL has a semicolon inside a quoted string or identifier. Approve it in the Dotaz window.";if(bi(e.sql))return"Only INSERT, UPDATE, DELETE, REPLACE, MERGE and WITH statements can be approved remotely. Approve it in the Dotaz window.";if(e.reason&&vt(e.reason))return"The reason contains invisible, bidirectional, control or bare carriage-return characters. Approve it in the Dotaz window.";if(e.database&&vt(e.database))return"The database name contains invisible, bidirectional, control or bare carriage-return characters. Approve it in the Dotaz window.";return null}function Fe(e,t){if(e.length===0||e.length>t)return!1;return!/[\p{C}\p{Zl}\p{Zp}]/u.test(e)}var ai=`dotaz-approval/v1
158
+ `,Zn=65536,Rt=120,er="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",ui,di,pi,mi,hi,yi,wi;var He=C(()=>{H();ui=/[\p{Cf}\p{Zl}\p{Zp}\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/u,di=/\r(?!\n)/;pi=/--|\/\*|\*\/|#/,mi=/^[\t\n\r A-Za-z0-9!"#%&'()*+,\-./:;<=>?@^_{|}~]$/;hi=/^(?:INSERT|UPDATE|DELETE|REPLACE|MERGE|WITH)\b/i;yi=new Set(["SELECT","VALUES","TABLE","INSERT","UPDATE","DELETE","MERGE","REPLACE"]),wi=new Set(["INSERT","UPDATE","DELETE","MERGE","REPLACE"])});import{createHash as or,createPublicKey as Ci,timingSafeEqual as Ti,verify as Ai}from"crypto";function Pi(e){let t=0,n=()=>{if(t>=e.length)throw new A("Truncated CBOR");return e[t++]},r=(a)=>{if(a<24)return a;if(a===24)return n();if(a===25)return n()<<8|n();if(a===26)return(n()<<24>>>0)+(n()<<16)+(n()<<8)+n();throw new A("Unsupported CBOR length")},s=(a)=>{if(t+a>e.length)throw new A("Truncated CBOR");let c=e.slice(t,t+a);return t+=a,c},i=(a)=>{if(a>4)throw new A("CBOR nested too deep");let c=n(),u=c>>5,l=r(c&31);switch(u){case 0:return l;case 1:return-1-l;case 2:return s(l);case 3:return new TextDecoder("utf-8",{fatal:!0}).decode(s(l));case 5:{let d=new Map;for(let f=0;f<l;f++){let h=i(a+1);if(typeof h!=="number"&&typeof h!=="string")throw new A("Unsupported CBOR map key");if(d.has(h))throw new A("Duplicate CBOR map key");d.set(h,i(a+1))}return d}default:throw new A("Unsupported CBOR type")}},o=i(0);if(t!==e.length)throw new A("Trailing bytes after CBOR value");return o}function _t(e){let t=Pi(e);if(!(t instanceof Map))throw new A("COSE key is not a map");if(t.get(vi)!==Oi)throw new A("COSE key is not an EC2 key");if(t.get(Ri)!==Ii)throw new A("COSE key is not ES256");if(t.get(Ni)!==xi)throw new A("COSE key is not on P-256");let n=t.get(Di),r=t.get(_i);if(!(n instanceof Uint8Array)||n.length!==32||!(r instanceof Uint8Array)||r.length!==32)throw new A("COSE key has malformed coordinates");try{return Ci({key:{kty:"EC",crv:"P-256",x:Buffer.from(n).toString("base64url"),y:Buffer.from(r).toString("base64url")},format:"jwk"})}catch{throw new A("COSE key is not a valid P-256 point")}}function ar(e,t){return e.length===t.length&&Ti(e,t)}function cr(e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.clientDataJSON))}catch{throw new A("clientDataJSON is not valid JSON")}if(typeof t!=="object"||t===null)throw new A("clientDataJSON is not an object");let n="type"in t?t.type:void 0,r="challenge"in t?t.challenge:void 0,s="origin"in t?t.origin:void 0,i="crossOrigin"in t?t.crossOrigin:void 0;if(n!=="webauthn.get")throw new A("clientDataJSON.type is not webauthn.get");if(typeof r!=="string")throw new A("clientDataJSON.challenge is missing");let o;try{o=Q(r)}catch{throw new A("clientDataJSON.challenge is not base64url")}if(!ar(o,e.expectedChallenge))throw new A("The signed challenge does not match this proposal and decision");if(s!==e.origin)throw new A("clientDataJSON.origin is not the enrolled origin");if(i===!0)throw new A("Cross-origin assertions are not accepted");let a=e.authenticatorData;if(a.length<37)throw new A("authenticatorData is too short");let c=or("sha256").update(e.rpId).digest();if(!ar(a.subarray(0,32),c))throw new A("authenticatorData is for another relying party");let u=a[32];if(!(u&Li))throw new A("The authenticator did not report user presence");if(!(u&ki))throw new A("The authenticator did not verify the user");let l=_t(e.publicKey),d=or("sha256").update(e.clientDataJSON).digest(),f=Buffer.concat([a,d]),h=!1;try{h=Ai("sha256",f,{key:l,dsaEncoding:"der"},e.signature)}catch{h=!1}if(!h)throw new A("The signature does not verify with the enrolled key")}var A,vi=1,Ri=3,Ni=-1,Di=-2,_i=-3,Oi=2,Ii=-7,xi=1,Li=1,ki=4;var lr=C(()=>{He();A=class A extends Error{}});function k(e){return new b("APPROVAL_REFUSED",e)}function O(e){return new b("PAIRING_REFUSED",e)}function Ot(e,t){try{return Q(e)}catch{throw k(`${t} is not base64url`)}}function Bi(e,t){if(typeof e!=="string"||e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function mr(e){let{publicKey:t,...n}=e;return n}function Qi(e){if(e==="localhost"||e.endsWith(".localhost"))return!1;if(/^[0-9.]+$/.test(e))return!1;return e.includes(".")}function Ki(e,t){let n;try{n=new URL(e)}catch{return!1}if(n.origin!==e||n.protocol!=="https:")return!1;return n.hostname===t||n.hostname.endsWith(`.${t}`)}class It{storage;proposals;connectionBlock;execute;onChange;now;challenges=new Map;pairing=null;pairingTimer=null;armed=null;constructor(e){this.storage=e.storage,this.proposals=e.proposals,this.connectionBlock=e.connectionBlock,this.execute=e.execute,this.onChange=e.onChange,this.now=e.now??(()=>Date.now())}listApprovers(){return this.storage.listRemoteApprovers().map(mr)}state(){let e=this.armedCode();return{request:this.pendingRequest(),approvers:this.listApprovers(),armed:e?{code:e.code,expiresAt:e.expiresAt}:null}}armPairing(){let e,t=10**ur,n=Math.floor(4294967296/t)*t;do e=crypto.getRandomValues(new Uint32Array(1))[0];while(e>=n);let r=String(e%t).padStart(ur,"0");return this.armed={code:r,expiresAt:this.now()+$i,wrongAttempts:0},this.emit(),{code:r,expiresAt:this.armed.expiresAt}}disarmPairing(){if(!this.armed)return;this.armed=null,this.emit()}async requestApprover(e){let t=this.now();if(this.sweepPairing(),this.pairing)throw O("A pairing request is already waiting for the user.");if(!this.armedCode())throw O("Pairing is not open. In Dotaz, choose Settings > CLI > Pair a device and send the code it shows.");let n=e.label.trim();if(!Fe(n,pr))throw O(`label must be 1 to ${pr} printable characters on one line`);if(!Hi.test(e.rpId)||!Qi(e.rpId))throw O("rpId must be a lowercase domain name, not localhost or an IP address");if(!Ki(e.origin,e.rpId))throw O("origin must be an https origin on rpId or a subdomain of it");let r;try{r=Q(e.credentialId),_t(Q(e.publicKey))}catch(o){throw O(`Invalid key: ${o instanceof Error?o.message:String(o)}`)}if(r.length<16||r.length>1023)throw O("credentialId must be 16 to 1023 bytes");let s=this.storage.listRemoteApprovers();if(s.some((o)=>o.credentialId===e.credentialId))throw O("This key is already paired");if(s.length>=dr)throw O(`At most ${dr} keys can be paired. Remove one in the app first.`);let i=await rr(e.credentialId,e.publicKey);if(this.pairing)throw O("A pairing request is already waiting for the user.");return this.consumeCode(e.pairingCode),this.pairing={requestId:crypto.randomUUID(),label:n,rpId:e.rpId,origin:e.origin,credentialId:e.credentialId,publicKey:e.publicKey,fingerprint:i,requestedAt:t,expiresAt:t+qi},this.schedulePairingExpiry(),this.emit(),{requestId:this.pairing.requestId,fingerprint:i,expiresAt:this.pairing.expiresAt}}pendingRequest(){if(this.sweepPairing(),!this.pairing)return null;let{publicKey:e,...t}=this.pairing;return t}confirmRequest(e,t){this.sweepPairing();let n=this.pairing;if(!n||n.requestId!==e||n.fingerprint!==t)throw O("This pairing request is no longer waiting");if(this.clearPairing(),this.storage.listRemoteApprovers().some((i)=>i.credentialId===n.credentialId))throw this.emit(),O("This key is already paired");let s={id:crypto.randomUUID(),label:n.label,rpId:n.rpId,origin:n.origin,credentialId:n.credentialId,publicKey:n.publicKey,fingerprint:n.fingerprint,addedAt:this.now()};return this.storage.addRemoteApprover(s),this.emit(),mr(s)}declineRequest(e){if(this.sweepPairing(),!this.pairing||this.pairing.requestId!==e)return;this.clearPairing(),this.emit()}removeApprover(e){if(!this.storage.removeRemoteApprover(e))throw Error(`Approver not found: ${e}`);this.emit()}async challenge(e){let t=this.storage.listRemoteApprovers();if(t.length===0)throw new b("APPROVAL_UNAVAILABLE","No approver keys are paired with this app. Approve the proposal in the Dotaz window.");let n=this.requirePending(e.proposalId);if(e.decision==="approve")this.assertRunnable(n);let r=this.now();if(this.sweepChallenges(r),[...this.challenges.values()].filter((a)=>a.proposalId===n.id).length>=Ui)throw k("Too many approval challenges are outstanding for this proposal. Try again in a few minutes.");let i=tr(crypto.getRandomValues(new Uint8Array(32))),o=r+Mi;return this.challenges.set(i,{proposalId:n.id,decision:e.decision,expiresAt:o}),{nonce:i,expiresAt:o,proposal:{id:n.id,connectionId:n.connectionId,connectionName:n.connectionName,database:n.database??null,sql:n.sql,sqlSha256:await Dt(n.sql),reason:n.reason??null,requestedBy:n.requestedBy??null,createdAt:n.createdAt,statements:x(n.sql).length},allowCredentials:t.map((a)=>a.credentialId)}}async redeem(e){let t=this.challenges.get(e.nonce);if(this.challenges.delete(e.nonce),!t)throw k("Unknown or already used challenge. Request a new one.");if(t.expiresAt<=this.now())throw k("The challenge expired. Request a new one.");if(t.proposalId!==e.proposalId||t.decision!==e.decision)throw k("The challenge was issued for another proposal or decision");let n=this.storage.listRemoteApprovers().find((i)=>i.credentialId===e.credentialId);if(!n)throw k("The key that signed is not paired with this app");let r=this.requirePending(e.proposalId),s=await nr(e.nonce,e.decision,r);try{cr({publicKey:Q(n.publicKey),rpId:n.rpId,origin:n.origin,expectedChallenge:s,authenticatorData:Ot(e.authenticatorData,"authenticatorData"),clientDataJSON:Ot(e.clientDataJSON,"clientDataJSON"),signature:Ot(e.signature,"signature")})}catch(i){if(i instanceof A)throw k(`The approval does not verify: ${i.message}`);throw i}if(e.decision==="reject")return this.claim(()=>this.proposals.rejectRemote(r.id,n.label));this.assertRunnable(r),this.claim(()=>this.proposals.claimRemote(r.id,n.label));try{let i=await this.execute(r);return this.proposals.settleRemote(r.id,"executed",i)}catch(i){return this.proposals.settleRemote(r.id,"failed",void 0,i instanceof Error?i.message:String(i))}}dispose(){this.clearPairing(),this.challenges.clear()}requirePending(e){let t=this.proposals.get(e);if(!t)throw k(`Proposal not found: ${e}`);if(t.status!=="pending")throw k(`Proposal ${e} is already ${t.status}`);return t}assertRunnable(e){let t=ir(e)??this.connectionBlock(e);if(t)throw k(t)}claim(e){try{return e()}catch(t){throw k(t instanceof Error?t.message:String(t))}}sweepChallenges(e){for(let[t,n]of this.challenges)if(n.expiresAt<=e)this.challenges.delete(t)}armedCode(){if(this.armed&&this.armed.expiresAt<=this.now())this.armed=null;return this.armed}consumeCode(e){let t=this.armedCode();if(!t)throw O("Pairing is not open. In Dotaz, choose Settings > CLI > Pair a device.");if(!Bi(e,t.code)){if(t.wrongAttempts++,t.wrongAttempts>=Fi)throw this.armed=null,this.emit(),O("Wrong pairing code too many times. Show a new code in Dotaz.");throw O("Wrong pairing code.")}this.armed=null}sweepPairing(){if(this.pairing&&this.pairing.expiresAt<=this.now())this.clearPairing(),this.emit()}schedulePairingExpiry(){if(!this.pairing)return;let e=Math.max(0,this.pairing.expiresAt-this.now())+50;this.pairingTimer=setTimeout(()=>{this.pairingTimer=null,this.sweepPairing()},e),this.pairingTimer.unref()}clearPairing(){if(this.pairing=null,this.pairingTimer!==null)clearTimeout(this.pairingTimer);this.pairingTimer=null}emit(){this.onChange?.(this.state())}}var Mi=120000,Ui=4,qi=300000,$i=300000,Fi=5,ur=6,dr=20,pr=64,Hi;var fr=C(()=>{He();H();q();lr();Hi=/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/});function Yi(e){return e.dataType!=="binary"}async function hr(e,t,n,r){let s=performance.now(),i=await e.loadSchema(t.sessionId),o=[];for(let[f,h]of Object.entries(i.tables)){if(t.scope==="schema"&&t.schemaName&&f!==t.schemaName)continue;for(let p of h){if(p.type!=="table")continue;if(t.scope==="tables"&&t.tableNames){if(!t.tableNames.includes(p.name))continue}o.push(p)}}let a=[],c=0,u=0,l=e.getDriverType()==="postgresql",d=l?"ILIKE":"LIKE";for(let f of o){if(r())return{matches:a,searchedTables:u,totalMatches:c,cancelled:!0,elapsedMs:Math.round(performance.now()-s)};n(f.name,u,o.length);let h=`${f.schema}.${f.name}`,g=(i.columns[h]??[]).filter(Yi);if(g.length===0){u++;continue}let y=[],S=[],m=0;for(let D of g){m++;let R=e.quoteIdentifier(D.name);y.push(`${Te(R,e)} ${d} ${e.placeholder(m)}`),S.push(`%${t.searchTerm}%`)}let w=e.qualifyTable(f.schema,f.name);m++;let E=e.placeholder(m),T=`SELECT * FROM ${w} WHERE ${y.join(" OR ")} LIMIT ${E}`;S.push(t.resultsPerTable);try{let D=await e.execute(T,S,t.sessionId);for(let R of D.rows){let U=R;for(let j of g){let Gt=U[j.name];if(Gt==null)continue;let Jt=String(Gt);if(l?Jt.toLowerCase().includes(t.searchTerm.toLowerCase()):Jt.toLowerCase().includes(t.searchTerm.toLowerCase())){a.push({schema:f.schema,table:f.name,column:j.name,row:U}),c++;break}}}}catch(D){console.debug(`Search: skipped ${f.schema}.${f.name}:`,D instanceof Error?D.message:D)}u++}return{matches:a,searchedTables:u,totalMatches:c,cancelled:!1,elapsedMs:Math.round(performance.now()-s)}}var gr=C(()=>{K()});function zi(e){let t=[],n=0;while(n<e.length){let r=e[n];if(r==="'"||r==='"'){let s=r,i=r;n++;while(n<e.length)if(e[n]===s)if(i+=e[n],n++,n<e.length&&e[n]===s)i+=e[n],n++;else break;else i+=e[n],n++;t.push({type:"string",value:i,upper:i});continue}if(/\s/.test(r)){let s="";while(n<e.length&&/\s/.test(e[n]))s+=e[n],n++;t.push({type:"whitespace",value:s,upper:s});continue}if(/[a-zA-Z_]/.test(r)){let s="";while(n<e.length&&/[a-zA-Z0-9_]/.test(e[n]))s+=e[n],n++;t.push({type:"word",value:s,upper:s.toUpperCase()});continue}t.push({type:"symbol",value:r,upper:r}),n++}return t}function Vi(e,t,n){let r=n.split(" "),s=t,i=0;while(i<r.length&&s<e.length){if(e[s].type==="whitespace"){s++;continue}if(e[s].upper!==r[i])return 0;i++,s++}return i===r.length?s-t:0}function Sr(e){let t=e.trim();if(!t)return"";let n=zi(t);for(let c of n)if(c.type==="word"){if(Wi.includes(c.upper))c.value=c.upper}let r=[],s="",i=0,o=0;while(i<n.length){let c=n[i];if(c.type==="symbol"&&c.value==="("){o++,s+=c.value,i++;continue}if(c.type==="symbol"&&c.value===")"){if(o>0)o--;s+=c.value,i++;continue}if(o>0){s+=c.value,i++;continue}if(c.type==="word"){let u=!1,l=[...yr,...wr].sort((d,f)=>f.split(" ").length-d.split(" ").length);for(let d of l){let f=Vi(n,i,d);if(f>0){let h=[];for(let S=i;S<i+f;S++)h.push(n[S].value);let p=h.filter((S)=>S.trim()).join(" "),g=wr.includes(d);if(yr.includes(d)||g){let S=s.trimEnd();if(S)r.push(S);s=p}else s+=p;i+=f,u=!0;break}}if(u)continue;if(ji.includes(c.upper)){let d=s.trimEnd();if(d)r.push(d);s=" "+c.value,i++;continue}}if(c.type==="whitespace"){if(s.trimEnd())s+=" "}else s+=c.value;i++}let a=s.trimEnd();if(a)r.push(a);return r.join(`
159
+ `)}var yr,wr,ji,Wi;var Er=C(()=>{yr=["SELECT","FROM","WHERE","ORDER BY","GROUP BY","HAVING","LIMIT","OFFSET","UNION","UNION ALL","INTERSECT","EXCEPT","INSERT INTO","UPDATE","SET","DELETE FROM","VALUES"],wr=["LEFT OUTER JOIN","RIGHT OUTER JOIN","FULL OUTER JOIN","CROSS JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","NATURAL JOIN","JOIN"],ji=["ON","AND","OR"],Wi=["SELECT","DISTINCT","FROM","WHERE","AND","OR","NOT","IN","EXISTS","BETWEEN","LIKE","ILIKE","IS","NULL","TRUE","FALSE","AS","ON","USING","JOIN","INNER","LEFT","RIGHT","FULL","OUTER","CROSS","NATURAL","ORDER","BY","GROUP","HAVING","LIMIT","OFFSET","UNION","ALL","INTERSECT","EXCEPT","INSERT","INTO","VALUES","UPDATE","SET","DELETE","CREATE","ALTER","DROP","TABLE","INDEX","VIEW","PRIMARY","KEY","FOREIGN","REFERENCES","UNIQUE","CHECK","DEFAULT","CONSTRAINT","CASCADE","RESTRICT","BEGIN","COMMIT","ROLLBACK","TRANSACTION","CASE","WHEN","THEN","ELSE","END","ASC","DESC","NULLS","FIRST","LAST","COUNT","SUM","AVG","MIN","MAX","CAST","COALESCE","NULLIF","WITH","RECURSIVE","RETURNING"]});class xt{cm;constructor(e){this.cm=e}async begin(e,t,n){let r=this.cm.getDriver(e,t);if(r.inTransaction(n))throw Error("Transaction already active on this connection");await r.beginTransaction(n)}async commit(e,t,n){let r=this.cm.getDriver(e,t);if(!r.inTransaction(n))throw Error("No active transaction to commit");await r.commit(n)}async rollback(e,t,n){let r=this.cm.getDriver(e,t);if(!r.inTransaction(n))throw Error("No active transaction to rollback");await r.rollback(n)}isActive(e,t,n){try{return this.cm.getDriver(e,t).inTransaction(n)}catch{return!1}}async rollbackIfActive(e,t,n){if(this.isActive(e,t,n))await this.rollback(e,t,n)}}class Pt{cm;queryExecutor;appDb;txManager;encryption;Utils;emitMessage;sessionManager;demoDbSourcePath;demoDbTargetPath;allowServerFileAccess;appVersion;mode;proposals=new At;unsubscribeProposals;remoteApprovals;uiSnapshot=null;constructor(e,t,n,r){this.cm=e;this.queryExecutor=t;this.appDb=n;this.txManager=new xt(e),this.encryption=r?.encryption,this.Utils=r?.Utils,this.emitMessage=r?.emitMessage,this.sessionManager=r?.sessionManager,this.demoDbSourcePath=r?.demoDbSourcePath,this.demoDbTargetPath=r?.demoDbTargetPath,this.allowServerFileAccess=r?.allowServerFileAccess??!0,this.appVersion=r?.appVersion??"0.0.0",this.mode=r?.mode??"web",this.unsubscribeProposals=this.proposals.onChange((s)=>{this.emitMessage?.("cli.proposal",s)}),this.remoteApprovals=new It({storage:n,proposals:this.proposals,connectionBlock:(s)=>this.remoteRunBlock(s),execute:(s)=>this.runApprovedProposal(s),onChange:(s)=>this.emitMessage?.("approvers.changed",s)})}listConnections(){return this.cm.listConnections()}createConnection(e){return this.rejectServerSqliteConfig(e.config),this.cm.createConnection(e)}updateConnection(e){return this.rejectServerSqliteConfig(e.config),this.cm.updateConnection(e)}setConnectionReadOnly(e,t){return this.cm.setConnectionReadOnly(e,t)}setConnectionGroup(e,t){return this.appDb.setConnectionGroup(e,t)}listConnectionGroups(){return this.appDb.listConnectionGroups()}renameConnectionGroup(e,t){this.appDb.renameConnectionGroup(e,t)}deleteConnectionGroup(e){this.appDb.deleteConnectionGroup(e)}async deleteConnection(e){await this.cm.deleteConnection(e)}async testConnection(e){return this.rejectServerSqliteConfig(e),this.cm.testConnection(e)}async connect(e,t,n){if(this.encryption){let r;if(n?.config){let s=n.encryptedSecrets?JSON.parse(await this.encryption.decrypt(n.encryptedSecrets)):{};r=Un(n.config,s)}else if(n?.encryptedConfig)r=JSON.parse(await this.encryption.decrypt(n.encryptedConfig));if(r){this.rejectServerSqliteConfig(r);let s=this.appDb.getConnectionById(e),i=n?.name??s?.name??e;if(!s)this.appDb.createConnectionWithId(e,{name:i,config:r});else this.appDb.updateConnection({id:e,name:i,config:r})}}await this.cm.connect(e,t?{password:t}:void 0)}async disconnect(e){await this.cm.disconnect(e)}listConnectionHandles(){let e=this.cm.listConnectionHandles();if(!this.sessionManager)return e;let t=new Map;for(let n of this.cm.listConnections())for(let r of this.sessionManager.listSessions(n.id))t.set(r.sessionId,r);return e.map((n)=>{if(!n.sessionId)return n;let r=t.get(n.sessionId);if(!r)return n;return{...n,label:r.label}})}async terminateConnectionHandle(e,t,n){let r=this.listConnectionHandles().find((s)=>s.connectionId===e&&(t===void 0||s.database===t)&&s.handleId===n);if(r?.sessionId&&this.sessionManager){await this.sessionManager.destroySession(r.sessionId),this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)});return}await this.cm.terminateConnectionHandle(e,t,n)}async createSession(e,t,n){if(!this.sessionManager)throw Error("SessionManager not available");let r=await this.sessionManager.createSession(e,t,n);return this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)}),r}async destroySession(e){if(!this.sessionManager)throw Error("SessionManager not available");let t=this.sessionManager.getSession(e);if(await this.sessionManager.destroySession(e),t)this.emitMessage?.("session.changed",{connectionId:t.connectionId,sessions:this.sessionManager.listSessions(t.connectionId)})}listSessions(e){if(!this.sessionManager)return[];return this.sessionManager.listSessions(e)}getDriver(e,t){return this.cm.getDriver(e,t)}async listDatabases(e){return this.cm.listDatabases(e)}async listDatabasesForConfig(e){return this.rejectServerSqliteConfig(e),this.cm.listDatabasesForConfig(e)}async activateDatabase(e,t){await this.cm.activateDatabase(e,t)}async deactivateDatabase(e,t){if(this.sessionManager)await this.sessionManager.destroySessionsForDatabase(e,t),this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)});await this.cm.deactivateDatabase(e,t)}async executeQuery(e,t,n,r,s,i,o){return this.queryExecutor.executeQuery(e,t,n,void 0,r,s,i,o)}async executeStatements(e,t,n,r){let s=this.cm.getDriver(e,n);for(let o of t)ke(s,o.sql,r);let i=async(o)=>{let a=s.inTransaction(o);try{if(!a)await s.beginTransaction(o);let c=[];for(let u of t){let l=performance.now();try{let d=await s.execute(u.sql,u.params,o),f=Math.round(performance.now()-l);c.push({...d,durationMs:f}),this.queryExecutor.sessionLog.add(e,u.sql,d.error?"error":"success",f,Oe(d),d.error,n,o)}catch(d){let f=Math.round(performance.now()-l);throw this.queryExecutor.sessionLog.add(e,u.sql,"error",f,0,d instanceof Error?d.message:String(d),n,o),d}}if(!a)await s.commit(o);return c}catch(c){if(!a)try{await s.rollback(o)}catch(u){console.debug("Rollback after error failed:",u instanceof Error?u.message:u)}throw c}};if(r)return i(r);return de(s,i)}submitQuery(e,t,n,r,s,i,o){let a=performance.now();this.queryExecutor.executeQuery(e,t,n,0,r,s,i,o).then((c)=>{this.emitMessage?.("query.completed",{queryId:r,results:c,durationMs:Math.round(performance.now()-a)})}).catch((c)=>{let u=c?.code;this.emitMessage?.("query.completed",{queryId:r,error:c instanceof Error?c.message:String(c),errorCode:u,durationMs:Math.round(performance.now()-a)})})}submitExplain(e,t,n,r,s,i,o){let a=performance.now();this.queryExecutor.explainQuery(e,t,n,s,i,o).then((c)=>{this.emitMessage?.("query.completed",{queryId:r,explainResult:c,durationMs:Math.round(performance.now()-a)})}).catch((c)=>{this.emitMessage?.("query.completed",{queryId:r,error:c instanceof Error?c.message:String(c),durationMs:Math.round(performance.now()-a)})})}cancelQuery(e){return this.queryExecutor.cancelQuery(e)}async beginTransaction(e,t,n){await this.txManager.begin(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}async commitTransaction(e,t,n){await this.txManager.commit(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}async rollbackTransaction(e,t,n){await this.txManager.rollback(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}getTransactionLog(e){let t=this.queryExecutor.sessionLog.getEntries(e.connectionId,e.database);if(e.statusFilter)t=t.filter((s)=>s.status===e.statusFilter);if(e.search){let s=e.search.toLowerCase();t=t.filter((i)=>i.sql.toLowerCase().includes(s))}let n=this.txManager.isActive(e.connectionId,e.database,e.sessionId),r=n?this.queryExecutor.sessionLog.getPendingCount(e.connectionId,e.database,e.sessionId):0;return{entries:t,pendingStatementCount:r,inTransaction:n}}clearTransactionLog(e,t,n){this.queryExecutor.sessionLog.clear(e,t)}listHistory(e){return this.appDb.listHistory(e)}clearHistory(e){this.appDb.clearHistory(e)}listSavedViews(e,t,n){return this.appDb.listSavedViews(e,t,n)}createSavedView(e){return this.appDb.createSavedView(e)}updateSavedView(e){return this.appDb.updateSavedView(e)}deleteSavedView(e){this.appDb.deleteSavedView(e)}listSavedViewsByConnection(e){return this.appDb.listSavedViewsByConnection(e)}getSavedViewById(e){return this.appDb.getSavedViewById(e)}listBookmarks(e,t){return this.appDb.listBookmarks(e,t)}createBookmark(e){return this.appDb.createBookmark(e)}updateBookmark(e){return this.appDb.updateBookmark(e)}deleteBookmark(e){this.appDb.deleteBookmark(e)}async searchDatabase(e){let t=this.cm.getDriver(e.connectionId,e.database);return hr(t,{searchTerm:e.searchTerm,scope:e.scope,schemaName:e.schemaName,tableNames:e.tableNames,resultsPerTable:e.resultsPerTable??50,sessionId:e.sessionId},()=>{},()=>!1)}async exportData(e){let t=e.filePath;this.rejectServerFileAccess(t);let n=this.cm.getDriver(e.connectionId,e.database);if(!t)throw Error("Export requires a file path");let r=this.emitMessage?(i)=>this.emitMessage("export.progress",{rowCount:i}):void 0;return{...await Sn(n,{schema:e.schema,table:e.table,format:e.format,columns:e.columns,keyColumns:e.keyColumns,includeHeaders:e.includeHeaders,delimiter:e.delimiter,encoding:e.encoding,utf8Bom:e.utf8Bom,batchSize:e.batchSize,filters:e.filters,sort:e.sort,limit:e.limit,autoJoins:e.autoJoins},t,void 0,r),filePath:t}}async exportPreview(e){let t=this.cm.getDriver(e.connectionId,e.database);return En(t,{schema:e.schema,table:e.table,format:e.format,columns:e.columns,keyColumns:e.keyColumns,delimiter:e.delimiter,filters:e.filters,sort:e.sort,limit:e.limit,autoJoins:e.autoJoins})}async exportPreviewRows(e){let t=this.cm.getDriver(e.connectionId,e.database),{sql:n,params:r}=Ne({schema:e.schema,table:e.table,format:"csv",columns:e.columns,filters:e.filters,sort:e.sort,autoJoins:e.autoJoins},t),s=r.length+1,i=`${n} LIMIT ${t.placeholder(s)}`,a=(await t.execute(i,[...r,e.limit])).rows,c=a.length>0?Object.keys(a[0]):e.columns??[];return{rows:a,columns:c}}async importData(e){this.rejectServerFileAccess(e.filePath);let t=this.cm.getDriver(e.connectionId,e.database),n=this.resolveImportStream(e.filePath,e.fileContent),r=this.emitMessage?(s)=>this.emitMessage("import.progress",{rowCount:s}):void 0;return _e(t,n,{schema:e.schema,table:e.table,format:e.format,delimiter:e.delimiter,hasHeader:e.hasHeader,mappings:e.mappings,batchSize:e.batchSize},void 0,r)}async importPreview(e){this.rejectServerFileAccess(e.filePath);let t=this.resolveImportPreviewStream(e.filePath,e.fileContent),n=await An(t,{format:e.format,delimiter:e.delimiter,hasHeader:e.hasHeader,limit:e.limit});if(e.filePath)try{let r=Bun.file(e.filePath);n.fileSizeBytes=r.size}catch{}return n}rejectServerFileAccess(e){if(!this.allowServerFileAccess&&e!==void 0)throw Error("Server file access is not available in this runtime")}rejectServerSqliteConfig(e){if(e?.type==="sqlite")this.rejectServerFileAccess(e.path)}resolveImportStream(e,t){if(e)return Bun.file(e).stream();if(t!==void 0)return new ReadableStream({start(n){n.enqueue(new TextEncoder().encode(t)),n.close()}});throw Error("Import requires either filePath or fileContent")}resolveImportPreviewStream(e,t){if(e){let s=Bun.file(e).stream().getReader(),i=65536,o=0;return new ReadableStream({async pull(a){let{done:c,value:u}=await s.read();if(c){a.close();return}if(o+=u.byteLength,o>=65536){a.enqueue(u),a.close(),s.releaseLock();return}a.enqueue(u)},cancel(){s.releaseLock()}})}if(t!==void 0)return new ReadableStream({start(n){n.enqueue(new TextEncoder().encode(t)),n.close()}});throw Error("Import preview requires either filePath or fileContent")}getAllSettings(){return this.appDb.getAllSettings()}setSetting(e,t){this.appDb.setSetting(e,t)}async encryptSecrets(e){if(!this.encryption)throw Error("Encryption not available");return this.encryption.encrypt(e)}async decryptConfig(e){if(!this.encryption)throw Error("Encryption not available");return this.encryption.decrypt(e)}async showOpenDialog({filters:e,multiple:t}){if(!this.Utils)throw Error("Utils not available");let n=e&&e.length>0?e.flatMap((i)=>i.extensions.map((o)=>`*.${o}`)).join(","):"*",s=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:n,canChooseFiles:!0,canChooseDirectory:!1,allowsMultipleSelection:t??!1})).filter((i)=>i!=="");return{paths:s,cancelled:s.length===0}}async showSaveDialog({defaultName:e}){if(!this.Utils)throw Error("Utils not available");let n=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:"*",canChooseFiles:!1,canChooseDirectory:!0,allowsMultipleSelection:!1}))[0];if(!n||n==="")return{path:null,cancelled:!0};return{path:e?`${n}/${e}`:n,cancelled:!1}}formatSql(e){return Sr(e)}async generateSql(e){let t=this.cm.getDriver(e.connectionId,e.database),n=await t.loadSchema(),r=zn(n),s=jn(this.appDb.getAllSettings());return{sql:await Jn(s,{prompt:e.prompt,schemaContext:r,dialect:t.getDriverType()})}}saveWorkspace(e){this.appDb.saveWorkspace(e)}loadWorkspace(){return this.appDb.loadWorkspace()}async initializeDemo(){if(!this.demoDbSourcePath||!this.demoDbTargetPath)throw Error("Demo database paths not configured");let e=Bun.file(this.demoDbSourcePath);if(!await e.exists())throw Error('Demo database source not found. Run "bun run seed:sqlite" first.');await Bun.write(this.demoDbTargetPath,e);let t={type:"sqlite",path:this.demoDbTargetPath},n=this.appDb.createConnection({name:"Bookstore (Demo)",config:t});return await this.cm.connect(n.id),n}agentHello(){return{version:this.appVersion,mode:this.mode,pid:process.pid,protocol:Gi}}proposeWrite(e){let t=this.cm.listConnections().find((n)=>n.id===e.connectionId);if(!t)throw Error(`Unknown connection: ${e.connectionId}`);return this.proposals.create({...e,connectionName:t.name})}listProposals(e){return this.proposals.list(e)}getProposal(e){return this.proposals.get(e)}async waitForProposal(e,t){return this.proposals.wait(e,t)}cancelProposal(e){return this.proposals.cancel(e)}resolveProposal(e){return this.proposals.resolve(e)}requestApprover(e){return this.remoteApprovals.requestApprover(e)}listApprovers(){return this.remoteApprovals.listApprovers()}getApproverRequest(){return this.remoteApprovals.pendingRequest()}getApproversState(){return this.remoteApprovals.state()}armPairing(){return this.remoteApprovals.armPairing()}disarmPairing(){this.remoteApprovals.disarmPairing()}confirmApproverRequest(e,t){return this.remoteApprovals.confirmRequest(e,t)}declineApproverRequest(e){this.remoteApprovals.declineRequest(e)}removeApprover(e){this.remoteApprovals.removeApprover(e)}approvalChallenge(e){return this.remoteApprovals.challenge(e)}redeemApproval(e){return this.remoteApprovals.redeem(e)}remoteRunBlock(e){let t=this.cm.listConnections().find((n)=>n.id===e.connectionId);if(!t)return"The connection this proposal targets no longer exists.";if(t.state!=="connected")return`Connection "${t.name}" is not connected in Dotaz.`;if(t.readOnly)return`Connection "${t.name}" is marked read-only in Dotaz.`;return null}async runApprovedProposal(e){let{connectionId:t,database:n,sql:r}=e,s=x(r),i;try{i=await this.createSession(t,n,{label:"remote approval"})}catch(d){throw Error(`Could not open a session: ${d instanceof Error?d.message:String(d)}. Nothing was run.`)}let o=i.sessionId,a=this.cm.getDriver(t,n),c=performance.now(),u=0,l;try{await a.beginTransaction(o);try{for(let d of s){let f=await a.execute(d,void 0,o);if(f.error)throw Error(f.error);u+=f.affectedRows??0}await a.commit(o)}catch(d){if(a.inTransaction(o))try{await a.rollback(o)}catch(f){console.debug("Rollback after a failed remote approval run failed:",f)}throw d}return{affectedRows:u,statements:s.length}}catch(d){throw l=d instanceof Error?d.message:String(d),d}finally{try{this.appDb.addHistory({connectionId:t,database:n,sql:r,status:l===void 0?"success":"error",durationMs:Math.round(performance.now()-c),rowCount:u,errorMessage:l})}catch(d){console.debug("Could not record a remote approval run in history:",d)}await this.destroySession(o).catch((d)=>{console.warn(`Failed to destroy remote approval session ${o}`,d)})}}getUiSnapshot(){return this.uiSnapshot??{tabs:[],activeTabId:null,activeConnectionId:null,updatedAt:0}}setUiSnapshot(e){this.uiSnapshot=e}sendUiCommand(e){this.emitMessage?.("cli.command",e)}getSessionManager(){return this.sessionManager}dispose(){this.remoteApprovals.dispose(),this.unsubscribeProposals(),this.proposals.dispose()}}var Gi=1;var br=C(()=>{H();me();Wn();at();lt();Xn();Me();fr();gr();Er()});function eo(e,t){if(e===void 0)return;let n=e.trim();if(n==="")return;if(!pt(n,t))throw Error("where must be a single boolean expression: no statement separators, comments, unbalanced parentheses or backslashes in quoted text")}function to(e,t){return e.listConnections().find((n)=>n.id===t)?.config.type}function Be(e,t){if(!t)throw Error("connectionId is required");if(!e.listConnections().some((n)=>n.id===t))throw Error(`Unknown connection: ${t}`)}async function Cr(e,t){try{await e.destroySession(t)}catch(n){console.warn(`Failed to destroy agent session ${t}`,n)}}async function Lt(e,t,n,r){Be(e,t);let s=await e.createSession(t,n,{readOnly:!0,label:Zi});if(s.readOnly!==!0)throw await Cr(e,s.sessionId),new b("READ_ONLY_SESSION","The database did not confirm a read-only agent session");try{return await r(s.sessionId)}finally{await Cr(e,s.sessionId)}}function no(e){if(e===void 0)return Xi;if(!Number.isFinite(e)||e<0)throw Error("timeoutMs must be a non-negative number");return Math.min(e,Ji)}function Tr(e){return{"connections.list":()=>e.listConnections(),"connections.create":({name:t,config:n,readOnly:r,color:s,groupName:i})=>e.createConnection({name:t,config:n,readOnly:r,color:s,groupName:i}),"connections.update":({id:t,name:n,config:r,readOnly:s,color:i,groupName:o})=>e.updateConnection({id:t,name:n,config:r,readOnly:s,color:i,groupName:o}),"connections.setReadOnly":({id:t,readOnly:n})=>e.setConnectionReadOnly(t,n),"connections.setGroup":({id:t,groupName:n})=>e.setConnectionGroup(t,n),"connections.listGroups":()=>e.listConnectionGroups(),"connections.renameGroup":({oldName:t,newName:n})=>{e.renameConnectionGroup(t,n)},"connections.deleteGroup":({groupName:t})=>{e.deleteConnectionGroup(t)},"connections.delete":async({id:t})=>{await e.deleteConnection(t)},"connections.test":async({config:t})=>e.testConnection(t),"connections.connect":async({connectionId:t,password:n,config:r,encryptedSecrets:s,name:i,encryptedConfig:o})=>{await e.connect(t,n,{config:r,encryptedSecrets:s,name:i,encryptedConfig:o})},"connections.disconnect":async({connectionId:t})=>{await e.disconnect(t)},"connections.listOpenHandles":()=>e.listConnectionHandles(),"connections.terminateHandle":async({connectionId:t,database:n,handleId:r})=>{await e.terminateConnectionHandle(t,n,r)},"session.create":async({connectionId:t,database:n,readOnly:r,label:s})=>e.createSession(t,n,{readOnly:r,label:s}),"session.destroy":async({sessionId:t})=>{await e.destroySession(t)},"session.list":({connectionId:t})=>e.listSessions(t),"databases.list":async({connectionId:t})=>e.listDatabases(t),"databases.listForConfig":async({config:t})=>e.listDatabasesForConfig(t),"databases.activate":async({connectionId:t,database:n})=>{await e.activateDatabase(t,n)},"databases.deactivate":async({connectionId:t,database:n})=>{await e.deactivateDatabase(t,n)},"schema.load":async({connectionId:t,database:n,sessionId:r})=>e.getDriver(t,n).loadSchema(r),"query.execute":async({connectionId:t,sql:n,queryId:r,params:s,database:i,statements:o,sessionId:a,searchPath:c})=>{if(o&&o.length>0)return e.executeStatements(t,o,i,a);return e.executeQuery(t,n,s,r,i,a,c)},"query.submit":({connectionId:t,sql:n,queryId:r,params:s,database:i,sessionId:o,searchPath:a})=>(e.submitQuery(t,n,s,r,i,o,a),{queryId:r}),"query.submitExplain":({connectionId:t,sql:n,analyze:r,queryId:s,database:i,sessionId:o,searchPath:a})=>(e.submitExplain(t,n,r??!1,s,i,o,a),{queryId:s}),"query.cancel":async({queryId:t})=>({cancelled:await e.cancelQuery(t)}),"query.format":({sql:t})=>({sql:e.formatSql(t)}),"tx.begin":async({connectionId:t,database:n,sessionId:r})=>{await e.beginTransaction(t,n,r)},"tx.commit":async({connectionId:t,database:n,sessionId:r})=>{await e.commitTransaction(t,n,r)},"tx.rollback":async({connectionId:t,database:n,sessionId:r})=>{await e.rollbackTransaction(t,n,r)},"transaction.getLog":(t)=>e.getTransactionLog(t),"transaction.clearLog":({connectionId:t,database:n,sessionId:r})=>{e.clearTransactionLog(t,n,r)},"search.searchDatabase":async(t)=>e.searchDatabase(t),"export.exportData":async(t)=>e.exportData(t),"export.preview":async(t)=>({content:await e.exportPreview(t)}),"export.previewRows":async(t)=>e.exportPreviewRows(t),"import.importData":async(t)=>e.importData(t),"import.preview":async(t)=>e.importPreview(t),"history.list":(t)=>e.listHistory(t),"history.clear":({connectionId:t})=>{e.clearHistory(t)},"views.save":({connectionId:t,schemaName:n,tableName:r,name:s,config:i})=>{if(!s?.trim())throw Error("View name is required");if(!t)throw Error("connectionId is required");if(!r)throw Error("tableName is required");if(e.listSavedViews(t,n,r).some((a)=>a.name===s.trim()))throw Error(`A view named "${s.trim()}" already exists for this table`);return e.createSavedView({connectionId:t,schemaName:n,tableName:r,name:s.trim(),config:i})},"views.update":({id:t,name:n,config:r})=>{if(!t)throw Error("View id is required");if(!n?.trim())throw Error("View name is required");let s=e.getSavedViewById(t);if(!s)throw Error(`Saved view not found: ${t}`);if(e.listSavedViews(s.connectionId,s.schemaName,s.tableName).some((o)=>o.id!==t&&o.name===n.trim()))throw Error(`A view named "${n.trim()}" already exists for this table`);return e.updateSavedView({id:t,name:n.trim(),config:r})},"views.delete":({id:t})=>{e.deleteSavedView(t)},"views.listByConnection":({connectionId:t})=>e.listSavedViewsByConnection(t),"bookmarks.list":({connectionId:t,search:n})=>e.listBookmarks(t,n),"bookmarks.create":({connectionId:t,database:n,name:r,description:s,sql:i})=>{if(!r?.trim())throw Error("Bookmark name is required");return e.createBookmark({connectionId:t,database:n,name:r.trim(),description:s,sql:i})},"bookmarks.update":({id:t,name:n,description:r,sql:s})=>{if(!t)throw Error("Bookmark id is required");if(!n?.trim())throw Error("Bookmark name is required");return e.updateBookmark({id:t,name:n.trim(),description:r,sql:s})},"bookmarks.delete":({id:t})=>{e.deleteBookmark(t)},"settings.getAll":()=>e.getAllSettings(),"settings.set":({key:t,value:n})=>{e.setSetting(t,n)},"storage.encryptSecrets":async({secrets:t})=>{if(!e.encryptSecrets)throw Error("Encryption not available");return{encryptedSecrets:await e.encryptSecrets(t)}},"storage.decryptConfig":async({encryptedConfig:t})=>{if(!e.decryptConfig)throw Error("Encryption not available");return{config:await e.decryptConfig(t)}},"ai.generateSql":async(t)=>e.generateSql(t),"workspace.save":({data:t})=>{e.saveWorkspace(t)},"workspace.load":()=>e.loadWorkspace(),"system.showOpenDialog":async(t)=>{if(!e.showOpenDialog)return{paths:[],cancelled:!0};return e.showOpenDialog(t)},"system.showSaveDialog":async(t)=>{if(!e.showSaveDialog)return{path:null,cancelled:!0};return e.showSaveDialog(t)},"agent.hello":()=>e.agentHello(),"agent.schema":async({connectionId:t,database:n})=>Lt(e,t,n,(r)=>e.getDriver(t,n).loadSchema(r)),"agent.query":async({connectionId:t,database:n,sql:r,queryId:s,params:i,searchPath:o})=>{if(!r?.trim())throw Error("sql is required");if(!s)throw Error("queryId is required");return Lt(e,t,n,(a)=>e.executeQuery(t,r,i,s,n,a,o))},"agent.search":async(t)=>Lt(e,t.connectionId,t.database,(n)=>e.searchDatabase({...t,sessionId:n})),"agent.proposeWrite":({connectionId:t,database:n,sql:r,reason:s,requestedBy:i})=>{if(Be(e,t),!r?.trim())throw Error("sql is required");let o=i?.trim()||void 0;if(o!==void 0&&!Fe(o,Rt))throw Error(`requestedBy must be at most ${Rt} printable characters on one line`);return{proposalId:e.proposeWrite({connectionId:t,database:n,sql:r.trim(),reason:s?.trim()||void 0,requestedBy:o}).id}},"agent.proposals.list":(t)=>e.listProposals(t),"agent.proposals.get":({proposalId:t})=>{if(!t)throw Error("proposalId is required");let n=e.getProposal(t);if(!n)throw Error(`Proposal not found: ${t}`);return n},"agent.proposals.wait":async({proposalId:t,timeoutMs:n})=>{if(!t)throw Error("proposalId is required");return e.waitForProposal(t,no(n))},"agent.proposals.cancel":({proposalId:t})=>{if(!t)throw Error("proposalId is required");e.cancelProposal(t)},"agent.proposals.resolve":({proposalId:t,status:n,result:r,error:s})=>{if(!t)throw Error("proposalId is required");if(!n)throw Error("status is required");return e.resolveProposal({proposalId:t,status:n,result:r,error:s})},"approvers.request":(t)=>e.requestApprover(t),"approvers.list":()=>e.listApprovers(),"agent.approvals.challenge":({proposalId:t,decision:n})=>{if(!t)throw Error("proposalId is required");if(n!=="approve"&&n!=="reject")throw Error("decision must be approve or reject");return e.approvalChallenge({proposalId:t,decision:n})},"agent.approvals.redeem":(t)=>{if(!t.proposalId)throw Error("proposalId is required");if(t.decision!=="approve"&&t.decision!=="reject")throw Error("decision must be approve or reject");return e.redeemApproval(t)},"approvers.pending":()=>e.getApproverRequest(),"approvers.state":()=>e.getApproversState(),"approvers.arm":()=>e.armPairing(),"approvers.disarm":()=>{e.disarmPairing()},"approvers.confirm":({requestId:t,fingerprint:n})=>{if(!t||!n)throw Error("requestId and fingerprint are required");return e.confirmApproverRequest(t,n)},"approvers.decline":({requestId:t})=>{if(!t)throw Error("requestId is required");e.declineApproverRequest(t)},"approvers.remove":({id:t})=>{if(!t)throw Error("id is required");e.removeApprover(t)},"ui.state":()=>e.getUiSnapshot(),"ui.openTable":({connectionId:t,database:n,schema:r,table:s,where:i,limit:o})=>{if(Be(e,t),!s?.trim())throw Error("table is required");if(o!==void 0&&(!Number.isInteger(o)||o<=0))throw Error("limit must be a positive integer");return eo(i,to(e,t)),e.sendUiCommand({kind:"open-table",connectionId:t,database:n,schema:r??"",table:s.trim(),where:i,limit:o}),{ok:!0}},"ui.openConsole":({connectionId:t,database:n,sql:r})=>(Be(e,t),e.sendUiCommand({kind:"open-console",connectionId:t,database:n,sql:r}),{ok:!0}),"ui.snapshot.set":({snapshot:t})=>{if(!t||!Array.isArray(t.tabs))throw Error("snapshot is required");e.setUiSnapshot(t)},"demo.initialize":async()=>{if(!e.initializeDemo)throw Error("Demo initialization is not available");return e.initializeDemo()}}}var Ji=600000,Xi=30000,Zi="cli";var Ar=C(()=>{He();mt();q()});function ro(e){if(!e)throw Error("AppDatabase is required");return e}function vr(e,t,n,r,s){let i=ro(n),o=t??new pe(e,void 0,i),a=new Ct(e,i,(u,l,d)=>{o.sessionLog.resetPendingCount(u,l,d)}),c=new Pt(e,o,i,{encryption:s?.encryption,Utils:r,emitMessage:s?.emitMessage,sessionManager:a,demoDbSourcePath:s?.demoDbSourcePath,demoDbTargetPath:s?.demoDbTargetPath,allowServerFileAccess:s?.allowServerFileAccess,appVersion:s?.appVersion,mode:s?.mode});return{handlers:Tr(c),sessionManager:a,adapter:c}}var Rr=C(()=>{Me();Yn();br();Ar()});class kt{inner;constructor(e){this.inner=e}log(e,t,n,r){let s=e.replace(/\s+/g," ").trim(),i=t&&t.length>0;if(r)console.debug(`[SQL ERROR] ${s}${i?` -- params: ${JSON.stringify(t)}`:""} (${n}ms)`,r);else if(n!==void 0)console.debug(`[SQL] ${s}${i?` -- params: ${JSON.stringify(t)}`:""} (${n}ms)`);else console.debug(`[SQL] ${s}${i?` -- params: ${JSON.stringify(t)}`:""}`)}async execute(e,t,n,r){let s=performance.now();try{let i=await this.inner.execute(e,t,n,r);return this.log(e,t,Math.round(performance.now()-s)),i}catch(i){throw this.log(e,t,Math.round(performance.now()-s),i),i}}async*iterate(e,t,n,r,s){this.log(e,t),yield*this.inner.iterate(e,t,n,r,s)}async importBatch(e,t,n,r){let s=`INSERT INTO ${e} (${t.join(", ")}) VALUES ... [${n.length} rows]`,i=performance.now();try{let o=await this.inner.importBatch(e,t,n,r);return this.log(s,void 0,Math.round(performance.now()-i)),o}catch(o){throw this.log(s,void 0,Math.round(performance.now()-i),o),o}}connect(e){return this.inner.connect(e)}disconnect(){return this.inner.disconnect()}isConnected(){return this.inner.isConnected()}reserveSession(e,t){return this.inner.reserveSession(e,t)}releaseSession(e){return this.inner.releaseSession(e)}getSessionIds(){return this.inner.getSessionIds()}isSessionReadOnly(e){return this.inner.isSessionReadOnly(e)}cancel(e,t){return this.inner.cancel(e,t)}ping(){return this.inner.ping()}async loadSchema(e){console.debug("[SQL] loadSchema started"+(e?` (session: ${e})`:""));let t=performance.now();try{let n=await this.inner.loadSchema(e),r=Object.values(n.tables).reduce((s,i)=>s+i.length,0);return console.debug(`[SQL] loadSchema completed \u2014 ${n.schemas.length} schemas, ${r} tables (${Math.round(performance.now()-t)}ms)`),n}catch(n){throw console.debug(`[SQL ERROR] loadSchema failed (${Math.round(performance.now()-t)}ms)`,n),n}}beginTransaction(e){return this.inner.beginTransaction(e)}commit(e){return this.inner.commit(e)}rollback(e){return this.inner.rollback(e)}inTransaction(e){return this.inner.inTransaction(e)}isTxAborted(e){return this.inner.isTxAborted(e)}isIterating(e){return this.inner.isIterating(e)}getDriverType(){return this.inner.getDriverType()}listConnectionHandles(){return this.inner.listConnectionHandles()}terminateConnectionHandle(e){return this.inner.terminateConnectionHandle(e)}quoteIdentifier(e){return this.inner.quoteIdentifier(e)}qualifyTable(e,t){return this.inner.qualifyTable(e,t)}emptyInsertSql(e){return this.inner.emptyInsertSql(e)}placeholder(e){return this.inner.placeholder(e)}}var{SQL:so}=globalThis.Bun;class ye{url;resetFn;initFn;systemConn=null;idleConn=null;idleTimer=null;connections=new Set;metadata=new Map;nextHandleNumber=1;constructor(e,t,n){this.url=e;this.resetFn=t;this.initFn=n}async connect(){if(this.systemConn=this.createSql("system"),this.connections.add(this.systemConn),await this.systemConn.unsafe("SELECT 1"),this.initFn)await this.initFn(this.systemConn)}getSystemConnection(){if(!this.systemConn)throw Error("ConnectionPool is not connected");return this.markUsed(this.systemConn),this.systemConn}async createConnection(){let e=this.createSql("leased");if(this.connections.add(e),this.initFn)try{await this.initFn(e)}catch(t){throw await this.destroyConnection(e),t}return e}async acquireConnection(){if(this.idleConn){let e=this.idleConn;return this.idleConn=null,this.clearIdleTimer(),this.setRole(e,"leased"),this.markUsed(e),e}return this.createConnection()}async releaseConnection(e){if(!this.connections.has(e)){try{await e.close()}catch{}return}if(!this.idleConn){if(this.resetFn||this.initFn)try{if(this.resetFn)await this.resetFn(e);if(this.initFn)await this.initFn(e)}catch{await this.destroyConnection(e);return}this.setRole(e,"idle"),this.markUsed(e),this.idleConn=e,this.scheduleIdleTimeout()}else await this.destroyConnection(e)}async destroyConnection(e){if(this.idleConn===e)this.idleConn=null,this.clearIdleTimer();if(this.systemConn===e)this.systemConn=null;this.connections.delete(e),this.metadata.delete(e);try{await e.close()}catch{}}async reconnectSystemConnection(){if(this.systemConn)await this.destroyConnection(this.systemConn);let e=this.createSql("system");this.connections.add(e);try{if(await e.unsafe("SELECT 1"),this.initFn)await this.initFn(e)}catch(t){throw await this.destroyConnection(e),t}this.systemConn=e}async disconnectAll(){this.clearIdleTimer(),this.idleConn=null;let e=[...this.connections];this.connections.clear(),this.metadata.clear(),this.systemConn=null,await Promise.allSettled(e.map((t)=>t.close()))}getConnectionId(e){return this.metadata.get(e)?.handleId}snapshot(){return[...this.connections].map((e)=>this.metadata.get(e)).filter((e)=>e!==void 0).map((e)=>({...e}))}async terminateConnection(e){let t=this.findConnectionByHandleId(e);if(!t)return!1;if(t===this.systemConn)return await this.reconnectSystemConnection(),!0;return await this.destroyConnection(t),!0}createSql(e){let t=new so({url:this.url,max:1}),n=Date.now();return this.metadata.set(t,{handleId:`pool-${this.nextHandleNumber}`,role:e,createdAt:n,lastUsedAt:n}),this.nextHandleNumber+=1,t}findConnectionByHandleId(e){for(let t of this.connections)if(this.metadata.get(t)?.handleId===e)return t;return}markUsed(e){let t=this.metadata.get(e);if(!t)return;t.lastUsedAt=Date.now()}setRole(e,t){let n=this.metadata.get(e);if(!n)return;n.role=t}scheduleIdleTimeout(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{if(this.idleConn)this.destroyConnection(this.idleConn)},io)}clearIdleTimer(){if(this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null}}var io=30000;var Mt=()=>{};function we(e){let t=e instanceof Error?e.message:String(e),n=e?.errno??e?.code;if(n==="57014")return new N("QUERY_CANCELED",t,{cause:e});if(/ECONNREFUSED|connection refused/i.test(t))return new _("CONNECTION_REFUSED",t,{cause:e});if(/timeout|timed out/i.test(t))return new _("CONNECTION_TIMEOUT",t,{cause:e});if(/ENOTFOUND|getaddrinfo/i.test(t))return new _("HOST_NOT_FOUND",t,{cause:e});if(/too many connections|connection limit/i.test(t))return new _("CONNECTION_LIMIT",t,{cause:e});if(/SSL|TLS|certificate/i.test(t))return new _("SSL_ERROR",t,{cause:e});if(n?.startsWith("28")||/authentication failed|password authentication/i.test(t))return new Ce(t,{cause:e});if(n==="3D000"||/database .* does not exist/i.test(t))return new _("DATABASE_NOT_FOUND",t,{cause:e});if(n==="23505"||/violates unique constraint|duplicate key/i.test(t))return new I("CONSTRAINT_UNIQUE",t,{cause:e});if(n==="23503"||/violates foreign key constraint/i.test(t))return new I("CONSTRAINT_FK",t,{cause:e});if(n==="23514"||/violates check constraint/i.test(t))return new I("CONSTRAINT_CHECK",t,{cause:e});if(n==="23502"||/violates not-null constraint/i.test(t))return new I("CONSTRAINT_NOT_NULL",t,{cause:e});if(n==="42601"||/syntax error/i.test(t))return new N("QUERY_SYNTAX",t,{cause:e});if(n==="42P01"||/relation .* does not exist/i.test(t))return new N("TABLE_NOT_FOUND",t,{cause:e});if(n==="42703"||/column .* does not exist/i.test(t))return new N("COLUMN_NOT_FOUND",t,{cause:e});if(n==="42501"||/permission denied/i.test(t))return new b("PERMISSION_DENIED",t,{cause:e});if(n==="40001")return new N("SERIALIZATION_FAILURE",t,{cause:e});if(n==="40P01")return new N("DEADLOCK_DETECTED",t,{cause:e});if(n==="25P02")return new N("TRANSACTION_ABORTED",t,{cause:e});if(n?.startsWith("42")||n?.startsWith("22"))return new N("QUERY_EXECUTION",t,{cause:e});return new b("UNKNOWN",t,{cause:e})}function se(e){let t=e instanceof Error?e.message:String(e);if(/unable to open database|cannot open/i.test(t))return new _("CONNECTION_REFUSED",t,{cause:e});if(/UNIQUE constraint failed/i.test(t))return new I("CONSTRAINT_UNIQUE",t,{cause:e});if(/FOREIGN KEY constraint failed/i.test(t))return new I("CONSTRAINT_FK",t,{cause:e});if(/CHECK constraint failed/i.test(t))return new I("CONSTRAINT_CHECK",t,{cause:e});if(/NOT NULL constraint failed/i.test(t))return new I("CONSTRAINT_NOT_NULL",t,{cause:e});if(/no such table/i.test(t))return new N("TABLE_NOT_FOUND",t,{cause:e});if(/no such column/i.test(t))return new N("COLUMN_NOT_FOUND",t,{cause:e});if(/syntax error|near /i.test(t))return new N("QUERY_SYNTAX",t,{cause:e});if(/authorization denied|not authorized/i.test(t))return new b("PERMISSION_DENIED",t,{cause:e});return new b("UNKNOWN",t,{cause:e})}function Qe(e){let t=e instanceof Error?e.message:String(e),n=e?.errno;if(n===3024||n===1969)return new N("QUERY_CANCELED",t,{cause:e});if(/ECONNREFUSED|connection refused/i.test(t)||n===2003)return new _("CONNECTION_REFUSED",t,{cause:e});if(/timeout|timed out/i.test(t))return new _("CONNECTION_TIMEOUT",t,{cause:e});if(/ENOTFOUND|getaddrinfo/i.test(t))return new _("HOST_NOT_FOUND",t,{cause:e});if(/too many connections/i.test(t)||n===1040)return new _("CONNECTION_LIMIT",t,{cause:e});if(/SSL|TLS|certificate/i.test(t))return new _("SSL_ERROR",t,{cause:e});if(n===1045||/access denied/i.test(t))return new Ce(t,{cause:e});if(n===1049||/unknown database/i.test(t))return new _("DATABASE_NOT_FOUND",t,{cause:e});if(n===1062||/duplicate entry/i.test(t))return new I("CONSTRAINT_UNIQUE",t,{cause:e});if(n===1451||n===1452||/foreign key constraint/i.test(t)||/cannot delete or update a parent row/i.test(t)||/cannot add or update a child row/i.test(t))return new I("CONSTRAINT_FK",t,{cause:e});if(n===3819||/check constraint/i.test(t))return new I("CONSTRAINT_CHECK",t,{cause:e});if(n===1048||/cannot be null/i.test(t))return new I("CONSTRAINT_NOT_NULL",t,{cause:e});if(n===1213||/deadlock found/i.test(t))return new N("DEADLOCK_DETECTED",t,{cause:e});if(n===1205||/lock wait timeout exceeded/i.test(t))return new N("SERIALIZATION_FAILURE",t,{cause:e});if(n===1064||/syntax error|you have an error in your sql syntax/i.test(t))return new N("QUERY_SYNTAX",t,{cause:e});if(n===1146||/table .* doesn't exist/i.test(t))return new N("TABLE_NOT_FOUND",t,{cause:e});if(n===1054||/unknown column/i.test(t))return new N("COLUMN_NOT_FOUND",t,{cause:e});if(n===1142||n===1143||/command denied|access denied/i.test(t))return new b("PERMISSION_DENIED",t,{cause:e});return new b("UNKNOWN",t,{cause:e})}var Ke=C(()=>{q()});function ie(e){let t=e;if(typeof t.affectedRows==="number")return t.affectedRows;if(typeof t.count==="number")return t.count;return 0}var Rc,Nc,Dc,_c,Oc,Ic;var Nr=C(()=>{K();Rc=new Set(["integer","serial","float","numeric"]),Nc=new Set(["boolean"]),Dc=new Set(["timestamp","date"]),_c=new Set(["text","varchar","char"]),Oc=new Set(["json"]),Ic=new Set(["array"])});var Dr=C(()=>{Nr();K()});var _r=C(()=>{Re();H();Dr()});function oe(e,t){let n=F(t).trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(n)){if(e.txActive=!0,"txAborted"in e)e.txAborted=!1}else if(/^(COMMIT|END)\b/.test(n)){if(e.txActive=!1,"txAborted"in e)e.txAborted=!1}else if(/^ROLLBACK\b/.test(n)&&!/^ROLLBACK\s+TO\b/.test(n)){if(e.txActive=!1,"txAborted"in e)e.txAborted=!1}}function z(e){let t=e?.code;if(typeof t==="string"&&/^(ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|ENOTCONN)$/.test(t))return!0;let n=e instanceof Error?e.message:String(e);return/ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|connection (terminated|ended|closed|lost|reset)|socket.*(closed|hang up|end)|write after end|broken pipe|network/i.test(n)}async function M(e,t){if(t?.rollback)try{await e.unsafe("ROLLBACK")}catch{}try{await e.close()}catch{}}var Ye=C(()=>{_r()});function oo(e){switch(e.toLowerCase()){case"int":case"integer":case"bigint":case"smallint":case"tinyint":case"mediumint":return"integer";case"float":case"double":return"float";case"decimal":case"numeric":return"numeric";case"bit":case"boolean":case"bool":return"boolean";case"text":case"tinytext":case"mediumtext":case"longtext":return"text";case"varchar":return"varchar";case"char":return"char";case"date":return"date";case"time":return"time";case"datetime":case"timestamp":return"timestamp";case"json":return"json";case"binary":case"varbinary":case"blob":case"tinyblob":case"mediumblob":case"longblob":return"binary";case"enum":case"set":return"enum";default:return"unknown"}}class Ut{pool=null;connected=!1;sessions=new Map;readOnlySessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;async connect(e){if(e.type!=="mysql")throw Error("MysqlDriver requires a mysql connection config");let t=`mysql://${encodeURIComponent(e.user)}:${encodeURIComponent(e.password)}@${e.host}:${e.port}/${encodeURIComponent(e.database)}`,n=e.initSql?.trim(),r=n?async(s)=>{await s.unsafe(n)}:void 0;this.pool=new ye(t,(s)=>s.unsafe("RESET CONNECTION"),r);try{await this.pool.connect()}catch(s){let i=this.pool;throw this.pool=null,await i.disconnectAll().catch(()=>{}),s instanceof b?s:Qe(s)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,e]of this.sessions)await M(e.conn,{rollback:e.txActive});if(this.sessions.clear(),this.readOnlySessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession(e,t){if(this.ensureConnected(),this.sessions.has(e))throw Error(`Session "${e}" already exists`);let n=await this.pool.createConnection();if(t?.readOnly){let r=["SET SESSION TRANSACTION READ ONLY"];r.push("SET NAMES utf8mb4");try{for(let i of r)await n.unsafe(i);let s=Math.floor(t.statementTimeoutMs??0);if(Number.isFinite(s)&&s>0)r.push(await this.setStatementTimeout(n,s))}catch(s){throw await M(n),await this.pool.destroyConnection(n),s instanceof b?s:Qe(s)}this.readOnlySessions.set(e,r)}this.sessions.set(e,{conn:n,txActive:!1,iterating:!1,activeQueries:new Set})}async releaseSession(e){this.readOnlySessions.delete(e);let t=this.sessions.get(e);if(!t)return;if(this.sessions.delete(e),await M(t.conn,{rollback:!0}),this.pool)await this.pool.destroyConnection(t.conn)}getSessionIds(){return[...this.sessions.keys()].filter((e)=>e!==L)}isSessionReadOnly(e){return this.readOnlySessions.has(e)}async reassertReadOnly(e,t){let n=e===void 0?void 0:this.readOnlySessions.get(e);if(!n)return;for(let r of n)await t.unsafe(r)}async execute(e,t,n,r){this.ensureConnected();let s=this.resolveSession(n),i=s?s.conn:await this.pool.acquireConnection(),o=!s;if(s)await this.reassertReadOnly(n,i);let a=performance.now(),c=i.unsafe(e,t??[]),u=s?void 0:r??Symbol();if(s)s.activeQueries.add(c);else this.poolActiveQueries.set(u,c);try{let l=await c,d=Math.round(performance.now()-a),f=[...l];if(s)oe(s,e);return{columns:f.length>0?Object.keys(f[0]).map((p)=>({name:p,dataType:"unknown"})):[],rows:f,rowCount:f.length,affectedRows:ie(l),durationMs:d}}catch(l){throw l instanceof b?l:Qe(l)}finally{if(s)s.activeQueries.delete(c);else if(this.poolActiveQueries.delete(u),o)await this.pool.releaseConnection(i)}}async cancel(e,t){if(e){let n=this.sessions.get(e);if(n){for(let r of n.activeQueries)r.cancel();n.activeQueries.clear()}}else if(t){let n=this.poolActiveQueries.get(t);if(n)n.cancel(),this.poolActiveQueries.delete(t)}else{for(let n of this.poolActiveQueries.values())n.cancel();this.poolActiveQueries.clear()}}async loadSchema(e){this.ensureConnected();let t=this.resolveSession(e),n=t?t.conn:this.pool.getSystemConnection(),r=await this.getSchemas(n),s=r.map((p)=>p.name),i={};for(let p of r)i[p.name]=await this.getTables(n,p.name);let[o,a,c,u]=await Promise.all([n.unsafe(`SELECT
148
160
  c.TABLE_SCHEMA AS table_schema,
149
161
  c.TABLE_NAME AS table_name,
150
162
  c.COLUMN_NAME AS column_name,
@@ -198,10 +210,10 @@ Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.st
198
210
  AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
199
211
  GROUP BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME,
200
212
  kcu.CONSTRAINT_NAME, kcu.TABLE_SCHEMA, kcu.TABLE_NAME
201
- ORDER BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.CONSTRAINT_NAME`,s)]),l={};for(let d of o){let h=`${d.table_schema}.${d.table_name}`;if(!l[h])l[h]=[];l[h].push({name:d.column_name,dataType:Ws(d.data_type),nullable:d.is_nullable==="YES",defaultValue:d.column_default,isPrimaryKey:d.column_key==="PRI",isAutoIncrement:(d.extra??"").includes("auto_increment"),maxLength:d.character_maximum_length??void 0})}let m={};for(let d of a){let h=`${d.table_schema}.${d.table_name}`;if(!m[h])m[h]=[];m[h].push({name:d.index_name,columns:typeof d.columns==="string"?d.columns.split(","):[d.columns],isUnique:d.non_unique===0||d.non_unique==="0",isPrimary:d.index_name==="PRIMARY"})}let f={};for(let d of c){let h=`${d.table_schema}.${d.table_name}`;if(!f[h])f[h]=[];f[h].push({name:d.constraint_name,columns:typeof d.columns==="string"?d.columns.split(","):[d.columns],referencedSchema:d.referenced_schema,referencedTable:d.referenced_table,referencedColumns:typeof d.referenced_columns==="string"?d.referenced_columns.split(","):[d.referenced_columns],onUpdate:d.on_update,onDelete:d.on_delete})}let g={};for(let d of u){let h=`${d.referenced_schema}.${d.referenced_table}`;if(!g[h])g[h]=[];g[h].push({constraintName:d.constraint_name,referencingSchema:d.referencing_schema,referencingTable:d.referencing_table,referencingColumns:typeof d.referencing_columns==="string"?d.referencing_columns.split(","):[d.referencing_columns],referencedColumns:typeof d.referenced_columns==="string"?d.referenced_columns.split(","):[d.referenced_columns]})}for(let d of r)for(let h of i[d.name]){let y=`${d.name}.${h.name}`;if(!l[y])l[y]=[];if(!m[y])m[y]=[];if(!f[y])f[y]=[];if(!g[y])g[y]=[]}return{schemas:r,tables:i,columns:l,indexes:m,foreignKeys:f,referencingForeignKeys:g}}async getSchemas(e){return this.ensureConnected(),[...await e.unsafe("SELECT DATABASE() AS name")]}async getTables(e,t){return this.ensureConnected(),[...await e.unsafe(`SELECT table_name AS name, table_type
213
+ ORDER BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.CONSTRAINT_NAME`,s)]),l={};for(let p of o){let g=`${p.table_schema}.${p.table_name}`;if(!l[g])l[g]=[];l[g].push({name:p.column_name,dataType:oo(p.data_type),nullable:p.is_nullable==="YES",defaultValue:p.column_default,isPrimaryKey:p.column_key==="PRI",isAutoIncrement:(p.extra??"").includes("auto_increment"),maxLength:p.character_maximum_length??void 0})}let d={};for(let p of a){let g=`${p.table_schema}.${p.table_name}`;if(!d[g])d[g]=[];d[g].push({name:p.index_name,columns:typeof p.columns==="string"?p.columns.split(","):[p.columns],isUnique:p.non_unique===0||p.non_unique==="0",isPrimary:p.index_name==="PRIMARY"})}let f={};for(let p of c){let g=`${p.table_schema}.${p.table_name}`;if(!f[g])f[g]=[];f[g].push({name:p.constraint_name,columns:typeof p.columns==="string"?p.columns.split(","):[p.columns],referencedSchema:p.referenced_schema,referencedTable:p.referenced_table,referencedColumns:typeof p.referenced_columns==="string"?p.referenced_columns.split(","):[p.referenced_columns],onUpdate:p.on_update,onDelete:p.on_delete})}let h={};for(let p of u){let g=`${p.referenced_schema}.${p.referenced_table}`;if(!h[g])h[g]=[];h[g].push({constraintName:p.constraint_name,referencingSchema:p.referencing_schema,referencingTable:p.referencing_table,referencingColumns:typeof p.referencing_columns==="string"?p.referencing_columns.split(","):[p.referencing_columns],referencedColumns:typeof p.referenced_columns==="string"?p.referenced_columns.split(","):[p.referenced_columns]})}for(let p of r)for(let g of i[p.name]){let y=`${p.name}.${g.name}`;if(!l[y])l[y]=[];if(!d[y])d[y]=[];if(!f[y])f[y]=[];if(!h[y])h[y]=[]}return{schemas:r,tables:i,columns:l,indexes:d,foreignKeys:f,referencingForeignKeys:h}}async getSchemas(e){return this.ensureConnected(),[...await e.unsafe("SELECT DATABASE() AS name")]}async getTables(e,t){return this.ensureConnected(),[...await e.unsafe(`SELECT table_name AS name, table_type
202
214
  FROM information_schema.tables
203
215
  WHERE table_schema = ?
204
- ORDER BY table_name`,[t])].map((r)=>({schema:t,name:r.name,type:r.table_type==="VIEW"?"view":"table"}))}async ping(){this.ensureConnected();try{await this.pool.getSystemConnection().unsafe("SELECT 1")}catch{await this.pool.reconnectSystemConnection()}}async*iterate(e,t,n=1000,r,s){this.ensureConnected();let i=this.resolveSession(s);if(i?.txActive)throw Error("Cannot iterate on a session with an active transaction");let o=i?i.conn:await this.pool.acquireConnection(),a=!i;if(i)i.txActive=!0,i.iterating=!0;try{if(i)await this.reassertReadOnly(s,o);await o.unsafe("START TRANSACTION WITH CONSISTENT SNAPSHOT");let c=0;while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");if(i&&c>0)await this.reassertReadOnly(s,o);let u=`${e} LIMIT ? OFFSET ?`,m=[...await o.unsafe(u,[...t??[],n,c])];if(m.length===0)break;if(yield m,m.length<n)break;c+=n}await o.unsafe("COMMIT")}catch(c){try{await o.unsafe("ROLLBACK")}catch{}throw c}finally{if(i)i.txActive=!1,i.iterating=!1;if(a)await this.pool.releaseConnection(o)}}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let m=0;m<t.length;m++)i.push(n[u][t[m]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}async beginTransaction(e){if(this.ensureConnected(),e){let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);await t.conn.unsafe("START TRANSACTION"),t.txActive=!0}else{if(this.sessions.has(I)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let t=await this.pool.acquireConnection();try{await t.unsafe("START TRANSACTION")}catch(n){throw await this.pool.releaseConnection(t),n}this.sessions.set(I,{conn:t,txActive:!0,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit(e){this.ensureConnected();let t=e??I,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot commit during active iteration");try{await n.conn.unsafe("COMMIT"),n.txActive=!1}catch(r){if(B(r))throw n.txActive=!1,new b("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:r});try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1}catch{}throw r}finally{if(t===I)this.sessions.delete(I),await this.pool.releaseConnection(n.conn)}}async rollback(e){this.ensureConnected();let t=e??I,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot rollback during active iteration");try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1}catch(r){if(B(r))n.txActive=!1;throw r}finally{if(t===I)this.sessions.delete(I),await this.pool.releaseConnection(n.conn)}}inTransaction(e){let t=e??I;return this.sessions.get(t)?.txActive??!1}isTxAborted(e){return!1}isIterating(e){let t=e??I;return this.sessions.get(t)?.iterating??!1}getDriverType(){return"mysql"}listConnectionHandles(){if(!this.pool)return[];return this.pool.snapshot().map((e)=>this.describePoolConnection(e))}async terminateConnectionHandle(e){this.ensureConnected();let t=this.findSessionByHandleId(e);if(t){await this.cancel(t.sessionId),await this.releaseSession(t.sessionId);return}if(!await this.pool.terminateConnection(e))throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`\`${e.replace(/`/g,"``")}\``}qualifyTable(e,t){return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} () VALUES ()`}placeholder(e){return"?"}async setStatementTimeout(e,t){let n=`SET SESSION MAX_EXECUTION_TIME = ${t}`;try{return await e.unsafe(n),n}catch{let r=`SET SESSION max_statement_time = ${t/1000}`;return await e.unsafe(r),r}}ensureConnected(){if(!this.pool||!this.connected)throw Error("Not connected. Call connect() first.")}describePoolConnection(e){let t=this.findSessionByHandleId(e.handleId);if(t){let i=t.session,o=t.sessionId===I,a=i.txActive?"transaction":i.iterating||i.activeQueries.size>0?"active":"idle";return{handleId:e.handleId,role:o?"default-transaction":"session",state:a,label:o?"Default transaction":void 0,sessionId:o?void 0:t.sessionId,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:i.activeQueries.size,inTransaction:i.txActive,txAborted:!1,iterating:i.iterating,canTerminate:!0}}let n=e.role==="system"?"system":e.role==="idle"?"idle":"temporary",r=e.role==="system"?this.poolActiveQueries.size:0,s=r>0||e.role==="leased"?"active":"idle";return{handleId:e.handleId,role:n,state:s,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:r,inTransaction:!1,txAborted:!1,iterating:e.role==="leased",canTerminate:!0}}findSessionByHandleId(e){if(!this.pool)return;for(let[t,n]of this.sessions)if(this.pool.getConnectionId(n.conn)===e)return{sessionId:t,session:n};return}resolveSession(e){if(!e)return;let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);return t}}var I="__default__";var tr=T(()=>{M();P();Tt();$e();qe()});async function js(e){await e.unsafe("RESET ALL"),await e.unsafe("RESET ROLE"),await e.unsafe("RESET SESSION AUTHORIZATION"),await e.unsafe("UNLISTEN *"),await e.unsafe("SELECT pg_advisory_unlock_all()"),await e.unsafe("DISCARD SEQUENCES"),await e.unsafe("DISCARD TEMP")}function zs(e){switch(e.toLowerCase()){case"integer":case"bigint":case"smallint":return"integer";case"serial":case"bigserial":case"smallserial":return"serial";case"real":case"double precision":return"float";case"numeric":case"decimal":case"money":return"numeric";case"boolean":return"boolean";case"text":return"text";case"character varying":return"varchar";case"character":return"char";case"date":return"date";case"time without time zone":case"time with time zone":return"time";case"timestamp without time zone":case"timestamp with time zone":return"timestamp";case"json":case"jsonb":return"json";case"uuid":return"uuid";case"bytea":case"bit":case"bit varying":return"binary";default:return"unknown"}}class vt{pool=null;connected=!1;sessions=new Map;readOnlySessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;async connect(e){if(e.type!=="postgresql")throw Error("PostgresDriver requires a postgresql connection config");let t=new URLSearchParams;if(e.ssl)t.set("sslmode",e.ssl);t.set("application_name","dotaz");let n=`postgres://${encodeURIComponent(e.user)}:${encodeURIComponent(e.password)}@${e.host}:${e.port}/${encodeURIComponent(e.database)}?${t}`,r=e.initSql?.trim(),s=r?async(i)=>{await i.unsafe(r)}:void 0;this.pool=new pe(n,js,s);try{await this.pool.connect()}catch(i){let o=this.pool;throw this.pool=null,await o.disconnectAll().catch(()=>{}),i instanceof b?i:fe(i)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,e]of this.sessions)await x(e.conn,{rollback:!0});if(this.sessions.clear(),this.readOnlySessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession(e,t){if(this.ensureConnected(),this.sessions.has(e))throw Error(`Session "${e}" already exists`);let n=await this.pool.createConnection();if(t?.readOnly){let r=["SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY"],s=Math.floor(t.statementTimeoutMs??0);if(Number.isFinite(s)&&s>0)r.push(`SET SESSION statement_timeout = ${s}`);let i=r.join("; ");try{await n.unsafe(i)}catch(o){throw await x(n),await this.pool.destroyConnection(n),o instanceof b?o:fe(o)}this.readOnlySessions.set(e,i)}this.sessions.set(e,{conn:n,txActive:!1,txAborted:!1,iterating:!1,activeQueries:new Set})}async releaseSession(e){this.readOnlySessions.delete(e);let t=this.sessions.get(e);if(!t)return;if(this.sessions.delete(e),await x(t.conn,{rollback:!0}),this.pool)await this.pool.destroyConnection(t.conn)}getSessionIds(){return[...this.sessions.keys()].filter((e)=>e!==O)}isSessionReadOnly(e){return this.readOnlySessions.has(e)}async reassertReadOnly(e,t,n){let r=this.readOnlySessions.get(e);if(!r)return;try{await n.unsafe(r)}catch(s){let i=s instanceof b?s:fe(s);if(t.txAborted&&i.code==="TRANSACTION_ABORTED")return;throw i}}async execute(e,t,n,r){this.ensureConnected();let s=this.resolveSession(n),i=s?s.conn:await this.pool.acquireConnection(),o=!s;if(s&&n!==void 0)await this.reassertReadOnly(n,s,i);let a=performance.now(),c=i.unsafe(e,t??[]),u=s?void 0:r??Symbol();if(s)s.activeQueries.add(c);else this.poolActiveQueries.set(u,c);try{let l=await c,m=Math.round(performance.now()-a),f=[...l];if(s)ne(s,e);return{columns:f.length>0?Object.keys(f[0]).map((d)=>({name:d,dataType:"unknown"})):[],rows:f,rowCount:f.length,affectedRows:te(l),durationMs:m}}catch(l){if(s?.txActive&&!B(l))s.txAborted=!0;throw l instanceof b?l:fe(l)}finally{if(s)s.activeQueries.delete(c);else if(this.poolActiveQueries.delete(u),o)await this.pool.releaseConnection(i)}}async cancel(e,t){if(e){let n=this.sessions.get(e);if(n){for(let r of n.activeQueries)r.cancel();n.activeQueries.clear()}}else if(t){let n=this.poolActiveQueries.get(t);if(n)n.cancel(),this.poolActiveQueries.delete(t)}else{for(let n of this.poolActiveQueries.values())n.cancel();this.poolActiveQueries.clear()}}async loadSchema(e){this.ensureConnected();let t=this.resolveSession(e),n=t?t.conn:this.pool.getSystemConnection(),r=!!process.env.DEBUG_SQL,s=async(p,S)=>{if(!r)return S();let E=performance.now();console.debug(`[SQL] loadSchema: ${p} \u2014 started`);try{let C=await S();return console.debug(`[SQL] loadSchema: ${p} \u2014 completed (${Math.round(performance.now()-E)}ms)`),C}catch(C){throw console.debug(`[SQL ERROR] loadSchema: ${p} \u2014 failed (${Math.round(performance.now()-E)}ms)`,C),C}},i=await s("getSchemas",()=>this.getSchemas(n)),a=`{${i.map((p)=>p.name).join(",")}}`,c={};for(let p of i){let S=await s(`getTables(${p.name})`,()=>this.getTables(n,p.name)),E=await s(`getMaterializedViews(${p.name})`,()=>this.getMaterializedViews(n,p.name));c[p.name]=[...S,...E]}let u=new Map;for(let p of i){let S=c[p.name].filter((E)=>E.type==="materialized-view");if(S.length>0)u.set(p.name,S.map((E)=>E.name))}let[l,m,f,g]=await Promise.all([s("columns",()=>n.unsafe(`SELECT
216
+ ORDER BY table_name`,[t])].map((r)=>({schema:t,name:r.name,type:r.table_type==="VIEW"?"view":"table"}))}async ping(){this.ensureConnected();try{await this.pool.getSystemConnection().unsafe("SELECT 1")}catch{await this.pool.reconnectSystemConnection()}}async*iterate(e,t,n=1000,r,s){this.ensureConnected();let i=this.resolveSession(s);if(i?.txActive)throw Error("Cannot iterate on a session with an active transaction");let o=i?i.conn:await this.pool.acquireConnection(),a=!i;if(i)i.txActive=!0,i.iterating=!0;try{if(i)await this.reassertReadOnly(s,o);await o.unsafe("START TRANSACTION WITH CONSISTENT SNAPSHOT");let c=0;while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");if(i&&c>0)await this.reassertReadOnly(s,o);let u=`${e} LIMIT ? OFFSET ?`,d=[...await o.unsafe(u,[...t??[],n,c])];if(d.length===0)break;if(yield d,d.length<n)break;c+=n}await o.unsafe("COMMIT")}catch(c){try{await o.unsafe("ROLLBACK")}catch{}throw c}finally{if(i)i.txActive=!1,i.iterating=!1;if(a)await this.pool.releaseConnection(o)}}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let d=0;d<t.length;d++)i.push(n[u][t[d]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}async beginTransaction(e){if(this.ensureConnected(),e){let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);await t.conn.unsafe("START TRANSACTION"),t.txActive=!0}else{if(this.sessions.has(L)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let t=await this.pool.acquireConnection();try{await t.unsafe("START TRANSACTION")}catch(n){throw await this.pool.releaseConnection(t),n}this.sessions.set(L,{conn:t,txActive:!0,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit(e){this.ensureConnected();let t=e??L,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot commit during active iteration");try{await n.conn.unsafe("COMMIT"),n.txActive=!1}catch(r){if(z(r))throw n.txActive=!1,new b("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:r});try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1}catch{}throw r}finally{if(t===L)this.sessions.delete(L),await this.pool.releaseConnection(n.conn)}}async rollback(e){this.ensureConnected();let t=e??L,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot rollback during active iteration");try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1}catch(r){if(z(r))n.txActive=!1;throw r}finally{if(t===L)this.sessions.delete(L),await this.pool.releaseConnection(n.conn)}}inTransaction(e){let t=e??L;return this.sessions.get(t)?.txActive??!1}isTxAborted(e){return!1}isIterating(e){let t=e??L;return this.sessions.get(t)?.iterating??!1}getDriverType(){return"mysql"}listConnectionHandles(){if(!this.pool)return[];return this.pool.snapshot().map((e)=>this.describePoolConnection(e))}async terminateConnectionHandle(e){this.ensureConnected();let t=this.findSessionByHandleId(e);if(t){await this.cancel(t.sessionId),await this.releaseSession(t.sessionId);return}if(!await this.pool.terminateConnection(e))throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`\`${e.replace(/`/g,"``")}\``}qualifyTable(e,t){return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} () VALUES ()`}placeholder(e){return"?"}async setStatementTimeout(e,t){let n=`SET SESSION MAX_EXECUTION_TIME = ${t}`;try{return await e.unsafe(n),n}catch{let r=`SET SESSION max_statement_time = ${t/1000}`;return await e.unsafe(r),r}}ensureConnected(){if(!this.pool||!this.connected)throw Error("Not connected. Call connect() first.")}describePoolConnection(e){let t=this.findSessionByHandleId(e.handleId);if(t){let i=t.session,o=t.sessionId===L,a=i.txActive?"transaction":i.iterating||i.activeQueries.size>0?"active":"idle";return{handleId:e.handleId,role:o?"default-transaction":"session",state:a,label:o?"Default transaction":void 0,sessionId:o?void 0:t.sessionId,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:i.activeQueries.size,inTransaction:i.txActive,txAborted:!1,iterating:i.iterating,canTerminate:!0}}let n=e.role==="system"?"system":e.role==="idle"?"idle":"temporary",r=e.role==="system"?this.poolActiveQueries.size:0,s=r>0||e.role==="leased"?"active":"idle";return{handleId:e.handleId,role:n,state:s,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:r,inTransaction:!1,txAborted:!1,iterating:e.role==="leased",canTerminate:!0}}findSessionByHandleId(e){if(!this.pool)return;for(let[t,n]of this.sessions)if(this.pool.getConnectionId(n.conn)===e)return{sessionId:t,session:n};return}resolveSession(e){if(!e)return;let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);return t}}var L="__default__";var Or=C(()=>{K();q();Mt();Ke();Ye()});async function ao(e){await e.unsafe("RESET ALL"),await e.unsafe("RESET ROLE"),await e.unsafe("RESET SESSION AUTHORIZATION"),await e.unsafe("UNLISTEN *"),await e.unsafe("SELECT pg_advisory_unlock_all()"),await e.unsafe("DISCARD SEQUENCES"),await e.unsafe("DISCARD TEMP")}function co(e){switch(e.toLowerCase()){case"integer":case"bigint":case"smallint":return"integer";case"serial":case"bigserial":case"smallserial":return"serial";case"real":case"double precision":return"float";case"numeric":case"decimal":case"money":return"numeric";case"boolean":return"boolean";case"text":return"text";case"character varying":return"varchar";case"character":return"char";case"date":return"date";case"time without time zone":case"time with time zone":return"time";case"timestamp without time zone":case"timestamp with time zone":return"timestamp";case"json":case"jsonb":return"json";case"uuid":return"uuid";case"bytea":case"bit":case"bit varying":return"binary";default:return"unknown"}}class qt{pool=null;connected=!1;sessions=new Map;readOnlySessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;async connect(e){if(e.type!=="postgresql")throw Error("PostgresDriver requires a postgresql connection config");let t=new URLSearchParams;if(e.ssl)t.set("sslmode",e.ssl);t.set("application_name","dotaz");let n=`postgres://${encodeURIComponent(e.user)}:${encodeURIComponent(e.password)}@${e.host}:${e.port}/${encodeURIComponent(e.database)}?${t}`,r=e.initSql?.trim(),s=r?async(i)=>{await i.unsafe(r)}:void 0;this.pool=new ye(n,ao,s);try{await this.pool.connect()}catch(i){let o=this.pool;throw this.pool=null,await o.disconnectAll().catch(()=>{}),i instanceof b?i:we(i)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,e]of this.sessions)await M(e.conn,{rollback:!0});if(this.sessions.clear(),this.readOnlySessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession(e,t){if(this.ensureConnected(),this.sessions.has(e))throw Error(`Session "${e}" already exists`);let n=await this.pool.createConnection();if(t?.readOnly){let r=["SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY"],s=Math.floor(t.statementTimeoutMs??0);if(Number.isFinite(s)&&s>0)r.push(`SET SESSION statement_timeout = ${s}`);let i=r.join("; ");try{await n.unsafe(i)}catch(o){throw await M(n),await this.pool.destroyConnection(n),o instanceof b?o:we(o)}this.readOnlySessions.set(e,i)}this.sessions.set(e,{conn:n,txActive:!1,txAborted:!1,iterating:!1,activeQueries:new Set})}async releaseSession(e){this.readOnlySessions.delete(e);let t=this.sessions.get(e);if(!t)return;if(this.sessions.delete(e),await M(t.conn,{rollback:!0}),this.pool)await this.pool.destroyConnection(t.conn)}getSessionIds(){return[...this.sessions.keys()].filter((e)=>e!==P)}isSessionReadOnly(e){return this.readOnlySessions.has(e)}async reassertReadOnly(e,t,n){let r=this.readOnlySessions.get(e);if(!r)return;try{await n.unsafe(r)}catch(s){let i=s instanceof b?s:we(s);if(t.txAborted&&i.code==="TRANSACTION_ABORTED")return;throw i}}async execute(e,t,n,r){this.ensureConnected();let s=this.resolveSession(n),i=s?s.conn:await this.pool.acquireConnection(),o=!s;if(s&&n!==void 0)await this.reassertReadOnly(n,s,i);let a=performance.now(),c=i.unsafe(e,t??[]),u=s?void 0:r??Symbol();if(s)s.activeQueries.add(c);else this.poolActiveQueries.set(u,c);try{let l=await c,d=Math.round(performance.now()-a),f=[...l];if(s)oe(s,e);return{columns:f.length>0?Object.keys(f[0]).map((p)=>({name:p,dataType:"unknown"})):[],rows:f,rowCount:f.length,affectedRows:ie(l),durationMs:d}}catch(l){if(s?.txActive&&!z(l))s.txAborted=!0;throw l instanceof b?l:we(l)}finally{if(s)s.activeQueries.delete(c);else if(this.poolActiveQueries.delete(u),o)await this.pool.releaseConnection(i)}}async cancel(e,t){if(e){let n=this.sessions.get(e);if(n){for(let r of n.activeQueries)r.cancel();n.activeQueries.clear()}}else if(t){let n=this.poolActiveQueries.get(t);if(n)n.cancel(),this.poolActiveQueries.delete(t)}else{for(let n of this.poolActiveQueries.values())n.cancel();this.poolActiveQueries.clear()}}async loadSchema(e){this.ensureConnected();let t=this.resolveSession(e),n=t?t.conn:this.pool.getSystemConnection(),r=!!process.env.DEBUG_SQL,s=async(m,w)=>{if(!r)return w();let E=performance.now();console.debug(`[SQL] loadSchema: ${m} \u2014 started`);try{let T=await w();return console.debug(`[SQL] loadSchema: ${m} \u2014 completed (${Math.round(performance.now()-E)}ms)`),T}catch(T){throw console.debug(`[SQL ERROR] loadSchema: ${m} \u2014 failed (${Math.round(performance.now()-E)}ms)`,T),T}},i=await s("getSchemas",()=>this.getSchemas(n)),a=`{${i.map((m)=>m.name).join(",")}}`,c={};for(let m of i){let w=await s(`getTables(${m.name})`,()=>this.getTables(n,m.name)),E=await s(`getMaterializedViews(${m.name})`,()=>this.getMaterializedViews(n,m.name));c[m.name]=[...w,...E]}let u=new Map;for(let m of i){let w=c[m.name].filter((E)=>E.type==="materialized-view");if(w.length>0)u.set(m.name,w.map((E)=>E.name))}let[l,d,f,h]=await Promise.all([s("columns",()=>n.unsafe(`SELECT
205
217
  c.table_schema,
206
218
  c.table_name,
207
219
  c.column_name,
@@ -301,7 +313,7 @@ Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.st
301
313
  AND nsp_ref.nspname = ANY($1)
302
314
  GROUP BY nsp_ref.nspname, cl_ref.relname, con.conname,
303
315
  nsp_src.nspname, cl_src.relname
304
- ORDER BY nsp_ref.nspname, cl_ref.relname, con.conname`,[a]))]);for(let[p,S]of u){let E=await s(`matviewColumns(${p})`,()=>n.unsafe(`SELECT
316
+ ORDER BY nsp_ref.nspname, cl_ref.relname, con.conname`,[a]))]);for(let[m,w]of u){let E=await s(`matviewColumns(${m})`,()=>n.unsafe(`SELECT
305
317
  n.nspname AS schema_name,
306
318
  c.relname AS table_name,
307
319
  a.attname AS column_name,
@@ -319,7 +331,7 @@ Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.st
319
331
  AND c.relname = ANY($2)
320
332
  AND a.attnum > 0
321
333
  AND NOT a.attisdropped
322
- ORDER BY n.nspname, c.relname, a.attnum`,[p,`{${S.join(",")}}`]));for(let C of E)l.push({table_schema:C.schema_name,table_name:C.table_name,column_name:C.column_name,data_type:C.data_type,udt_name:C.udt_name,is_nullable:C.is_nullable,column_default:C.column_default,character_maximum_length:null,is_primary_key:!1})}let d={};for(let p of l){let S=`${p.table_schema}.${p.table_name}`;if(!d[S])d[S]=[];d[S].push({name:p.column_name,dataType:this.mapDataType(p.data_type,p.udt_name),nullable:p.is_nullable==="YES",defaultValue:p.column_default,isPrimaryKey:p.is_primary_key,isAutoIncrement:p.is_primary_key&&typeof p.column_default==="string"&&p.column_default.startsWith("nextval("),maxLength:p.character_maximum_length??void 0})}let h={};for(let p of m){let S=`${p.table_schema}.${p.table_name}`;if(!h[S])h[S]=[];h[S].push({name:p.index_name,columns:typeof p.columns==="string"?p.columns.replace(/^\{|\}$/g,"").split(","):p.columns,isUnique:p.is_unique,isPrimary:p.is_primary})}let y={};for(let p of f){let S=`${p.table_schema}.${p.table_name}`;if(!y[S])y[S]=[];y[S].push({name:p.constraint_name,columns:typeof p.columns==="string"?p.columns.replace(/^\{|\}$/g,"").split(","):p.columns,referencedSchema:p.referenced_schema,referencedTable:p.referenced_table,referencedColumns:typeof p.referenced_columns==="string"?p.referenced_columns.replace(/^\{|\}$/g,"").split(","):p.referenced_columns,onUpdate:p.on_update,onDelete:p.on_delete})}let w={};for(let p of g){let S=`${p.referenced_schema}.${p.referenced_table}`;if(!w[S])w[S]=[];w[S].push({constraintName:p.constraint_name,referencingSchema:p.referencing_schema,referencingTable:p.referencing_table,referencingColumns:typeof p.referencing_columns==="string"?p.referencing_columns.replace(/^\{|\}$/g,"").split(","):p.referencing_columns,referencedColumns:typeof p.referenced_columns==="string"?p.referenced_columns.replace(/^\{|\}$/g,"").split(","):p.referenced_columns})}for(let p of i)for(let S of c[p.name]){let E=`${p.name}.${S.name}`;if(!d[E])d[E]=[];if(!h[E])h[E]=[];if(!y[E])y[E]=[];if(!w[E])w[E]=[]}return{schemas:i,tables:c,columns:d,indexes:h,foreignKeys:y,referencingForeignKeys:w}}async getSchemas(e){return this.ensureConnected(),[...await e.unsafe(`SELECT schema_name AS name
334
+ ORDER BY n.nspname, c.relname, a.attnum`,[m,`{${w.join(",")}}`]));for(let T of E)l.push({table_schema:T.schema_name,table_name:T.table_name,column_name:T.column_name,data_type:T.data_type,udt_name:T.udt_name,is_nullable:T.is_nullable,column_default:T.column_default,character_maximum_length:null,is_primary_key:!1})}let p={};for(let m of l){let w=`${m.table_schema}.${m.table_name}`;if(!p[w])p[w]=[];p[w].push({name:m.column_name,dataType:this.mapDataType(m.data_type,m.udt_name),nullable:m.is_nullable==="YES",defaultValue:m.column_default,isPrimaryKey:m.is_primary_key,isAutoIncrement:m.is_primary_key&&typeof m.column_default==="string"&&m.column_default.startsWith("nextval("),maxLength:m.character_maximum_length??void 0})}let g={};for(let m of d){let w=`${m.table_schema}.${m.table_name}`;if(!g[w])g[w]=[];g[w].push({name:m.index_name,columns:typeof m.columns==="string"?m.columns.replace(/^\{|\}$/g,"").split(","):m.columns,isUnique:m.is_unique,isPrimary:m.is_primary})}let y={};for(let m of f){let w=`${m.table_schema}.${m.table_name}`;if(!y[w])y[w]=[];y[w].push({name:m.constraint_name,columns:typeof m.columns==="string"?m.columns.replace(/^\{|\}$/g,"").split(","):m.columns,referencedSchema:m.referenced_schema,referencedTable:m.referenced_table,referencedColumns:typeof m.referenced_columns==="string"?m.referenced_columns.replace(/^\{|\}$/g,"").split(","):m.referenced_columns,onUpdate:m.on_update,onDelete:m.on_delete})}let S={};for(let m of h){let w=`${m.referenced_schema}.${m.referenced_table}`;if(!S[w])S[w]=[];S[w].push({constraintName:m.constraint_name,referencingSchema:m.referencing_schema,referencingTable:m.referencing_table,referencingColumns:typeof m.referencing_columns==="string"?m.referencing_columns.replace(/^\{|\}$/g,"").split(","):m.referencing_columns,referencedColumns:typeof m.referenced_columns==="string"?m.referenced_columns.replace(/^\{|\}$/g,"").split(","):m.referenced_columns})}for(let m of i)for(let w of c[m.name]){let E=`${m.name}.${w.name}`;if(!p[E])p[E]=[];if(!g[E])g[E]=[];if(!y[E])y[E]=[];if(!S[E])S[E]=[]}return{schemas:i,tables:c,columns:p,indexes:g,foreignKeys:y,referencingForeignKeys:S}}async getSchemas(e){return this.ensureConnected(),[...await e.unsafe(`SELECT schema_name AS name
323
335
  FROM information_schema.schemata
324
336
  WHERE schema_name NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
325
337
  AND schema_name NOT LIKE 'pg_temp_%'
@@ -330,13 +342,13 @@ Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.st
330
342
  ORDER BY table_name`,[t])].map((r)=>({schema:t,name:r.name,type:r.table_type==="VIEW"?"view":"table"}))}async getMaterializedViews(e,t){return this.ensureConnected(),[...await e.unsafe(`SELECT matviewname
331
343
  FROM pg_matviews
332
344
  WHERE schemaname = $1
333
- ORDER BY matviewname`,[t])].map((r)=>({schema:t,name:r.matviewname,type:"materialized-view"}))}async ping(){this.ensureConnected();try{await this.pool.getSystemConnection().unsafe("SELECT 1")}catch{await this.pool.reconnectSystemConnection()}}async beginTransaction(e){if(this.ensureConnected(),e){let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);await t.conn.unsafe("BEGIN"),t.txActive=!0,t.txAborted=!1}else{if(this.sessions.has(O)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let t=await this.pool.acquireConnection();try{await t.unsafe("BEGIN")}catch(n){throw await this.pool.releaseConnection(t),n}this.sessions.set(O,{conn:t,txActive:!0,txAborted:!1,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit(e){this.ensureConnected();let t=e??O,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot commit during active iteration");try{await n.conn.unsafe("COMMIT"),n.txActive=!1,n.txAborted=!1}catch(r){if(B(r))throw n.txActive=!1,n.txAborted=!1,new b("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:r});try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1,n.txAborted=!1}catch{}throw r}finally{if(t===O)this.sessions.delete(O),await this.pool.releaseConnection(n.conn)}}async rollback(e){this.ensureConnected();let t=e??O,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot rollback during active iteration");try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1,n.txAborted=!1}catch(r){if(B(r))n.txActive=!1,n.txAborted=!1;throw r}finally{if(t===O)this.sessions.delete(O),await this.pool.releaseConnection(n.conn)}}inTransaction(e){let t=e??O;return this.sessions.get(t)?.txActive??!1}isTxAborted(e){let t=e??O;return this.sessions.get(t)?.txAborted??!1}isIterating(e){let t=e??O;return this.sessions.get(t)?.iterating??!1}getDriverType(){return"postgresql"}listConnectionHandles(){if(!this.pool)return[];return this.pool.snapshot().map((e)=>this.describePoolConnection(e))}async terminateConnectionHandle(e){this.ensureConnected();let t=this.findSessionByHandleId(e);if(t){await this.cancel(t.sessionId),await this.releaseSession(t.sessionId);return}if(!await this.pool.terminateConnection(e))throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`"${e.replace(/"/g,'""')}"`}qualifyTable(e,t){return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} DEFAULT VALUES`}placeholder(e){return`$${e}`}async*iterate(e,t,n=1000,r,s){this.ensureConnected();let i=`dotaz_iter_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=s?this.sessions.get(s):void 0;if(s&&!o)throw Error(`Session "${s}" not found`);if(o?.txActive)throw Error("Cannot iterate on a session with an active transaction");let a=o?o.conn:await this.pool.acquireConnection(),c=!o;if(o)o.txActive=!0,o.iterating=!0;let u=!1;try{await a.unsafe("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"),await a.unsafe(`DECLARE ${i} NO SCROLL CURSOR FOR ${e}`,t??[]);try{while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");let m=[...await a.unsafe(`FETCH FORWARD ${n} FROM ${i}`)];if(m.length===0)break;if(yield m,m.length<n)break}}finally{try{await a.unsafe(`CLOSE ${i}`)}catch{}}await a.unsafe("COMMIT")}catch(l){u=!0;try{await a.unsafe("ROLLBACK")}catch{}throw l}finally{if(o)o.txActive=!1,o.iterating=!1;if(c)await this.pool.releaseConnection(a);else if(o&&!u)try{await a.unsafe("ROLLBACK")}catch{}}}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let m=0;m<t.length;m++)i.push(n[u][t[m]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}ensureConnected(){if(!this.pool||!this.connected)throw Error("Not connected. Call connect() first.")}describePoolConnection(e){let t=this.findSessionByHandleId(e.handleId);if(t){let i=t.session,o=t.sessionId===O,a=i.txActive?"transaction":i.iterating||i.activeQueries.size>0?"active":"idle";return{handleId:e.handleId,role:o?"default-transaction":"session",state:a,label:o?"Default transaction":void 0,sessionId:o?void 0:t.sessionId,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:i.activeQueries.size,inTransaction:i.txActive,txAborted:i.txAborted,iterating:i.iterating,canTerminate:!0}}let n=e.role==="system"?"system":e.role==="idle"?"idle":"temporary",r=e.role==="system"?this.poolActiveQueries.size:0,s=r>0||e.role==="leased"?"active":"idle";return{handleId:e.handleId,role:n,state:s,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:r,inTransaction:!1,txAborted:!1,iterating:e.role==="leased",canTerminate:!0}}findSessionByHandleId(e){if(!this.pool)return;for(let[t,n]of this.sessions)if(this.pool.getConnectionId(n.conn)===e)return{sessionId:t,session:n};return}resolveSession(e){if(!e)return;let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);return t}mapDataType(e,t){if(e==="ARRAY")return"array";if(e==="USER-DEFINED"){let n=t.toLowerCase();if(n==="json"||n==="jsonb")return"json";return"enum"}return zs(e)}}var O="__default__";var nr=T(()=>{M();P();Tt();$e();qe()});var{SQL:Fe}=globalThis.Bun;function Gs(e){let t=e.toUpperCase();if(t==="INTEGER"||t==="INT"||t==="BIGINT"||t==="SMALLINT"||t==="TINYINT"||t==="MEDIUMINT")return"integer";if(t==="REAL"||t==="FLOAT"||t==="DOUBLE")return"float";if(t==="NUMERIC"||t==="DECIMAL")return"numeric";if(t==="BOOLEAN"||t==="BOOL")return"boolean";if(t==="TEXT")return"text";if(t.includes("VARCHAR")||t.includes("VARYING"))return"varchar";if(t.includes("CHAR")&&!t.includes("VARCHAR"))return"char";if(t==="DATE")return"date";if(t==="TIME")return"time";if(t==="DATETIME"||t.includes("TIMESTAMP"))return"timestamp";if(t==="JSON"||t==="JSONB")return"json";if(t==="BLOB"||t==="BINARY"||t.includes("VARBINARY"))return"binary";return"unknown"}class Rt{db=null;dbPath=null;connected=!1;txActive=!1;txOwnerSession=null;sessionIds=new Set;readOnlySessions=new Map;iterating=!1;iterateDb=null;iterateActive=!1;initSql=null;mainHandleId=null;mainCreatedAt=0;mainLastUsedAt=0;iterateHandleId=null;iterateCreatedAt=0;iterateLastUsedAt=0;nextHandleNumber=1;async connect(e){if(e.type!=="sqlite")throw Error("SqliteDriver requires a sqlite connection config");let t=e.initSql?.trim()||null;try{this.db=new Fe(`sqlite:${e.path}`),this.dbPath=e.path,this.resetMainHandle(),await this.db.unsafe("PRAGMA journal_mode = WAL"),await this.db.unsafe("PRAGMA foreign_keys = ON"),this.initSql=t,await this.applyInitSql(this.db)}catch(n){if(this.db)try{await this.db.close()}catch{}throw this.db=null,this.dbPath=null,this.initSql=null,this.mainHandleId=null,this.mainCreatedAt=0,this.mainLastUsedAt=0,n instanceof b?n:ee(n)}this.connected=!0}async disconnect(){this.connected=!1;for(let e of this.readOnlySessions.values())await x(e.conn,{rollback:e.txActive});if(this.readOnlySessions.clear(),this.iterateDb){try{await this.iterateDb.close()}catch{}this.iterateDb=null,this.iterateHandleId=null,this.iterateCreatedAt=0,this.iterateLastUsedAt=0,this.iterateActive=!1}if(this.db)await this.db.close(),this.db=null,this.dbPath=null,this.initSql=null,this.mainHandleId=null,this.mainCreatedAt=0,this.mainLastUsedAt=0,this.txActive=!1,this.txOwnerSession=null,this.sessionIds.clear()}isConnected(){return this.connected}async reserveSession(e,t){if(t?.readOnly)await this.openReadOnlyHandle(e);this.sessionIds.add(e)}async releaseSession(e){let t=this.readOnlySessions.get(e);if(t){this.readOnlySessions.delete(e),await x(t.conn,{rollback:t.txActive}),this.sessionIds.delete(e);return}if(this.txActive&&this.txOwnerSession===e){try{await this.db.unsafe("ROLLBACK")}catch{}this.txActive=!1,this.txOwnerSession=null}this.sessionIds.delete(e)}getSessionIds(){return[...this.sessionIds]}isSessionReadOnly(e){return this.readOnlySessions.has(e)}async execute(e,t,n){this.ensureConnected(),this.ensureKnownSession(n);let r=n===void 0?void 0:this.readOnlySessions.get(n);if(r){r.lastUsedAt=Date.now();let o=await this.runStatement(r.conn,e,t);return ne(r,e),o}this.ensureSessionCanExecute(n),this.markMainUsed();let s=await this.runStatement(this.db,e,t),i=e.trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(i))this.txActive=!0,this.txOwnerSession=n??null;else if(/^(COMMIT|END)\b/.test(i))this.txActive=!1,this.txOwnerSession=null;else if(/^ROLLBACK\b/.test(i)&&!/^ROLLBACK\s+TO\b/.test(i))this.txActive=!1,this.txOwnerSession=null;return s}async runStatement(e,t,n){let r=performance.now();try{let s=await e.unsafe(t,n??[]),i=Math.round(performance.now()-r),o=[...s];return{columns:o.length>0?Object.keys(o[0]).map((c)=>({name:c,dataType:"unknown"})):[],rows:o,rowCount:o.length,affectedRows:te(s),durationMs:i}}catch(s){throw s instanceof b?s:ee(s)}}async openReadOnlyHandle(e){if(this.ensureConnected(),this.readOnlySessions.has(e))return;if(!this.dbPath||this.dbPath===":memory:")throw Error("Read-only sessions require a file-backed SQLite database");let t=new Fe({adapter:"sqlite",filename:this.dbPath,readonly:!0});try{await t.unsafe("PRAGMA foreign_keys = ON"),await this.applyInitSql(t),await t.unsafe("PRAGMA query_only = ON")}catch(r){try{await t.close()}catch{}throw r instanceof b?r:ee(r)}let n=Date.now();this.readOnlySessions.set(e,{conn:t,txActive:!1,iterating:!1,handleId:this.createHandleId(),createdAt:n,lastUsedAt:n})}async cancel(e,t){}async loadSchema(e){this.ensureConnected(),this.markMainUsed();let t=await this.getSchemas(),n=t[0].name,r=await this.getTables(n),s={[n]:r},i={},o={},a={},c={},u=new Map;for(let l of r){let m=`${n}.${l.name}`;i[m]=await this.getColumns(n,l.name),o[m]=await this.getIndexes(n,l.name);let f=await this.getForeignKeys(n,l.name);a[m]=f;for(let g of f){let d=`${g.referencedSchema}.${g.referencedTable}`;if(!u.has(d))u.set(d,[]);u.get(d).push({constraintName:g.name,referencingSchema:n,referencingTable:l.name,referencingColumns:g.columns,referencedColumns:g.referencedColumns})}}for(let l of r){let m=`${n}.${l.name}`;c[m]=u.get(m)??[]}return{schemas:t,tables:s,columns:i,indexes:o,foreignKeys:a,referencingForeignKeys:c}}async getSchemas(){return[{name:"main"}]}async getTables(e){return this.ensureConnected(),[...await this.db.unsafe("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name")].map((n)=>({schema:e,name:n.name,type:n.type}))}async getColumns(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA table_info(${this.quoteIdentifier(t)})`)],r=n.filter((s)=>s.pk>0).length;return n.map((s)=>({name:s.name,dataType:Gs(s.type||"BLOB"),nullable:s.notnull===0&&s.pk===0,defaultValue:s.dflt_value,isPrimaryKey:s.pk>0,isAutoIncrement:s.pk>0&&r===1&&s.type?.toUpperCase()==="INTEGER"}))}async getIndexes(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA index_list(${this.quoteIdentifier(t)})`)],r=[];for(let s of n){let i=[...await this.db.unsafe(`PRAGMA index_info(${this.quoteIdentifier(s.name)})`)];r.push({name:s.name,columns:i.map((o)=>o.name),isUnique:s.unique===1,isPrimary:s.origin==="pk"})}return r}async getForeignKeys(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA foreign_key_list(${this.quoteIdentifier(t)})`)],r=new Map;for(let s of n){let i=r.get(s.id);if(i)i.columns.push(s.from),i.referencedColumns.push(s.to);else r.set(s.id,{name:`fk_${t}_${s.id}`,columns:[s.from],referencedSchema:"main",referencedTable:s.table,referencedColumns:[s.to],onUpdate:s.on_update,onDelete:s.on_delete})}return Array.from(r.values())}async ping(){this.ensureConnected(),this.markMainUsed(),await this.db.unsafe("SELECT 1")}async*iterate(e,t,n=1000,r,s){this.ensureConnected(),this.ensureKnownSession(s);let i=s===void 0?void 0:this.readOnlySessions.get(s),o=!i&&this.dbPath===":memory:",a;if(i){if(i.txActive)throw Error("Cannot iterate with an active transaction");a=i.conn,i.iterating=!0,i.lastUsedAt=Date.now()}else if(o){if(a=this.db,this.markMainUsed(),this.ensureSessionCanExecute(s),this.txActive)throw Error("Cannot iterate with an active transaction");this.txActive=!0,this.txOwnerSession=s??null,this.iterating=!0}else a=await this.getIterateDb(),this.iterateActive=!0,this.markIterateUsed();await a.unsafe("BEGIN");let c=!1;try{let u=0;while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");let l=`${e} LIMIT ? OFFSET ?`,f=[...await a.unsafe(l,[...t??[],n,u])];if(f.length===0)break;if(yield f,f.length<n)break;u+=n}await a.unsafe("COMMIT"),c=!0}catch(u){try{await a.unsafe("ROLLBACK")}catch{}throw u}finally{if(!c)try{await a.unsafe("ROLLBACK")}catch{}if(i)i.iterating=!1,i.lastUsedAt=Date.now();else if(o)this.iterating=!1,this.txActive=!1,this.txOwnerSession=null;else this.iterateActive=!1,this.markIterateUsed()}}async getIterateDb(){if(!this.iterateDb){let e=new Fe(`sqlite:${this.dbPath}`);try{await this.applyInitSql(e)}catch(t){try{await e.close()}catch{}throw t instanceof b?t:ee(t)}this.iterateDb=e,this.resetIterateHandle()}return this.iterateDb}async applyInitSql(e){if(!this.initSql)return;for(let t of H(this.initSql))await e.unsafe(t)}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let m=0;m<t.length;m++)i.push(n[u][t[m]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}async beginTransaction(e){this.ensureConnected(),this.ensureKnownSession(e);let t=e===void 0?void 0:this.readOnlySessions.get(e);if(t){if(t.txActive)throw Error("A transaction is already active");await t.conn.unsafe("BEGIN"),t.txActive=!0,t.lastUsedAt=Date.now();return}if(this.markMainUsed(),this.txActive)throw Error(e&&this.txOwnerSession!==e?`Another session ("${this.txOwnerSession}") already has an active transaction`:"A transaction is already active");await this.db.unsafe("BEGIN"),this.txActive=!0,this.txOwnerSession=e??null}async commit(e){this.ensureConnected(),this.ensureKnownSession(e);let t=e===void 0?void 0:this.readOnlySessions.get(e);if(t){if(!t.txActive)throw Error("No active transaction");if(t.iterating)throw Error("Cannot commit during active iteration");await t.conn.unsafe("COMMIT"),t.txActive=!1,t.lastUsedAt=Date.now();return}if(this.ensureSessionOwnsTx(e),this.iterating)throw Error("Cannot commit during active iteration");this.markMainUsed(),await this.db.unsafe("COMMIT"),this.txActive=!1,this.txOwnerSession=null}async rollback(e){this.ensureConnected(),this.ensureKnownSession(e);let t=e===void 0?void 0:this.readOnlySessions.get(e);if(t){if(!t.txActive)throw Error("No active transaction");if(t.iterating)throw Error("Cannot rollback during active iteration");try{await t.conn.unsafe("ROLLBACK")}finally{t.txActive=!1,t.lastUsedAt=Date.now()}return}if(this.ensureSessionOwnsTx(e),this.iterating)throw Error("Cannot rollback during active iteration");this.markMainUsed();try{await this.db.unsafe("ROLLBACK")}finally{this.txActive=!1,this.txOwnerSession=null}}inTransaction(e){if(e!==void 0){let t=this.readOnlySessions.get(e);if(t)return t.txActive;return this.txActive&&this.txOwnerSession===e}return this.txActive&&this.txOwnerSession===null}isTxAborted(e){return!1}isIterating(e){if(e!==void 0){let t=this.readOnlySessions.get(e);if(t)return t.iterating}return this.iterating}getDriverType(){return"sqlite"}listConnectionHandles(){if(!this.connected||!this.db||!this.mainHandleId)return[];let e=this.txActive?"transaction":this.iterating?"active":"idle",t=[{handleId:this.mainHandleId,role:"sqlite-main",state:e,createdAt:this.mainCreatedAt,lastUsedAt:this.mainLastUsedAt,activeQueryCount:0,inTransaction:this.txActive,txAborted:!1,iterating:this.iterating,canTerminate:!0}];if(this.iterateDb&&this.iterateHandleId)t.push({handleId:this.iterateHandleId,role:"sqlite-iterate",state:this.iterateActive?"active":"idle",createdAt:this.iterateCreatedAt,lastUsedAt:this.iterateLastUsedAt,activeQueryCount:this.iterateActive?1:0,inTransaction:this.iterateActive,txAborted:!1,iterating:this.iterateActive,canTerminate:!0});for(let[n,r]of this.readOnlySessions)t.push({handleId:r.handleId,role:"session",state:r.txActive?"transaction":r.iterating?"active":"idle",label:"Read-only session",sessionId:n,createdAt:r.createdAt,lastUsedAt:r.lastUsedAt,activeQueryCount:r.iterating?1:0,inTransaction:r.txActive,txAborted:!1,iterating:r.iterating,canTerminate:!0});return t}async terminateConnectionHandle(e){if(this.ensureConnected(),this.mainHandleId===e){await this.reopenMainConnection();return}for(let[t,n]of this.readOnlySessions)if(n.handleId===e){await this.releaseSession(t);return}if(this.iterateHandleId===e&&this.iterateDb){try{await this.iterateDb.close()}catch{}this.iterateDb=null,this.iterateHandleId=null,this.iterateCreatedAt=0,this.iterateLastUsedAt=0,this.iterateActive=!1;return}throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`"${e.replace(/"/g,'""')}"`}qualifyTable(e,t){if(e==="main")return this.quoteIdentifier(t);return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} DEFAULT VALUES`}placeholder(e){return`$${e}`}ensureKnownSession(e){if(e===void 0)return;if(!this.sessionIds.has(e))throw Error(`Session "${e}" not found`)}ensureSessionCanExecute(e){if(!this.txActive)return;if(this.iterating)throw Error("Cannot execute: iteration is in progress on the shared connection");if(this.txOwnerSession===null){if(e!==void 0)throw Error("Cannot execute: a sessionless transaction is active. SQLite uses a single connection shared by all sessions.");return}if(e===void 0||e!==this.txOwnerSession)throw Error(`Cannot execute: session "${this.txOwnerSession}" has an active transaction. SQLite uses a single connection shared by all sessions.`)}ensureSessionOwnsTx(e){if(!this.txActive)throw Error("No active transaction");if(!(e===void 0?this.txOwnerSession===null:this.txOwnerSession===e))throw Error(`Cannot modify transaction owned by ${this.txOwnerSession===null?"sessionless caller":`session "${this.txOwnerSession}"`}`)}ensureConnected(){if(!this.db||!this.connected)throw Error("Not connected. Call connect() first.")}async reopenMainConnection(){let e=this.dbPath;if(!e)throw Error("SQLite path is not available");if(this.db)try{await this.db.close()}catch{}let t=new Fe(`sqlite:${e}`);try{await t.unsafe("PRAGMA journal_mode = WAL"),await t.unsafe("PRAGMA foreign_keys = ON"),await this.applyInitSql(t)}catch(n){try{await t.close()}catch{}throw n instanceof b?n:ee(n)}this.db=t,this.txActive=!1,this.txOwnerSession=null,this.iterating=!1,this.resetMainHandle()}resetMainHandle(){let e=Date.now();this.mainHandleId=this.createHandleId(),this.mainCreatedAt=e,this.mainLastUsedAt=e}resetIterateHandle(){let e=Date.now();this.iterateHandleId=this.createHandleId(),this.iterateCreatedAt=e,this.iterateLastUsedAt=e}createHandleId(){let e=`sqlite-${this.nextHandleNumber}`;return this.nextHandleNumber+=1,e}markMainUsed(){this.mainLastUsedAt=Date.now()}markIterateUsed(){this.iterateLastUsedAt=Date.now()}}var rr=T(()=>{G();M();P();$e();qe()});import{chmodSync as Vs,unlinkSync as Js,writeFileSync as Xs}from"fs";import{tmpdir as Zs}from"os";import{join as ei}from"path";async function ri(){return new Promise((e,t)=>{let n=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){},open(){},close(){},error(){}}}),r=n.port;if(n.stop(!0),r>0)e(r);else t(Error("Could not find a free port"))})}async function si(e,t,n){let r=Date.now()+t;while(Date.now()<r){if(n&&n.exitCode!==null)return;try{(await Bun.connect({hostname:"127.0.0.1",port:e,socket:{data(){},open(i){i.end()},close(){},error(){}}})).end();return}catch{await Bun.sleep(ni)}}throw Error(`SSH tunnel port ${e} did not become available within ${t/1000}s`)}async function He(e,t,n){let r=e.localPort||await ri(),s=null,i=null;try{let o=["ssh","-N","-L",`${r}:${t}:${n}`,"-p",String(e.port||22),"-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30","-o","ExitOnForwardFailure=yes"],a={...process.env};if(e.authMethod==="key"&&e.keyPath)o.push("-i",e.keyPath),o.push("-o","BatchMode=yes");else if(e.password)s=ei(Zs(),`dotaz-askpass-${process.pid}-${Date.now()}`),Xs(s,`#!/bin/sh
334
- echo '${e.password.replace(/'/g,"'\\''")}'`),Vs(s,448),a.SSH_ASKPASS=s,a.SSH_ASKPASS_REQUIRE="force",a.DISPLAY=a.DISPLAY||":0";if(o.push(`${e.username}@${e.host}`),i=Bun.spawn(o,{stdin:"pipe",stdout:"ignore",stderr:"pipe",env:a}),i.stdin&&typeof i.stdin!=="number")i.stdin.end();let c=i.stderr&&typeof i.stderr!=="number"?i.stderr:null,u=si(r,ti,i),l=i.exited.then(async(f)=>{if(f!==0){let g=await ii(c),d=oi(g)||`SSH process exited with code ${f}`;throw Error(d)}});return await Promise.race([u,l]),{localPort:r,close:async()=>{if(i)i.kill(),i=null;sr(s)}}}catch(o){if(i)i.kill();if(sr(s),o instanceof Error)throw ai(o);throw Error(`SSH tunnel error: ${String(o)}`)}}function sr(e){if(e)try{Js(e)}catch{}}async function ii(e){if(!e)return"";try{let t=e.getReader(),n=[];while(!0){let{done:r,value:s}=await t.read();if(r)break;n.push(s)}return Buffer.concat(n).toString("utf-8")}catch{return""}}function oi(e){if(!e.trim())return null;let t=e.trim().split(`
335
- `);for(let n of t){let r=n.toLowerCase();if(r.includes("permission denied")||r.includes("authentication"))return`SSH authentication failed: ${n.trim()}`;if(r.includes("connection refused"))return`SSH host unreachable: ${n.trim()}`;if(r.includes("timed out")||r.includes("timeout"))return`SSH connection timed out: ${n.trim()}`;if(r.includes("no such file")||r.includes("no such identity"))return`SSH key file not found: ${n.trim()}`;if(r.includes("could not resolve"))return`SSH host unreachable: ${n.trim()}`}return t[t.length-1]?.trim()||null}function ai(e){let t=e.message.toLowerCase();if(t.includes("authentication")||t.includes("permission denied"))return Error(`SSH authentication failed: ${e.message}`);if(t.includes("econnrefused")||t.includes("connection refused")||t.includes("unreachable"))return Error(`SSH host unreachable: ${e.message}`);if(t.includes("timeout")||t.includes("timed out"))return Error(`SSH connection timed out: ${e.message}`);return Error(`SSH tunnel error: ${e.message}`)}var ti=15000,ni=100;var ir=()=>{};class Nt{drivers=new Map;passwords=new Map;states=new Map;listeners=[];sessionDeadListeners=[];appDb;opts;tunnels=new Map;healthTimers=new Map;reconnectStates=new Map;healthCheckRunning=new Set;connectAttempt=new Map;constructor(e,t){this.appDb=e,this.opts={...li,...t}}async connect(e,t){let n=this.appDb.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);this.cancelAutoReconnect(e);let r=(this.connectAttempt.get(e)??0)+1;if(this.connectAttempt.set(e,r),this.drivers.has(e))await this.disconnectAllDrivers(e);await this.closeTunnel(e),await this.setConnectionState(e,"connecting");try{let s=t?{...n.config,...t}:n.config;if(ge(s),k(s))this.passwords.set(e,s.password);s=await this.setupSshTunnel(e,s);let i=V(s),o=he(s);if(await o.connect(s),this.connectAttempt.get(e)!==r){await o.disconnect().catch(()=>{});return}let a=new Map;if(a.set(i,o),this.drivers.set(e,a),U[s.type].supportsMultiDatabase&&"activeDatabases"in s&&s.activeDatabases){let c=s,u=(c.activeDatabases??[]).filter((l)=>l!==c.database).map((l)=>this.connectDatabase(e,c,l));await Promise.allSettled(u)}await this.setConnectionState(e,"connected"),this.startHealthCheck(e)}catch(s){if(this.connectAttempt.get(e)!==r)return;await this.closeTunnel(e);let i=s instanceof Error?s.message:"Unknown connection error",o=s instanceof b?s.code:void 0;throw await this.setConnectionState(e,"error",i,o),s}}async disconnect(e){this.connectAttempt.set(e,(this.connectAttempt.get(e)??0)+1),this.cancelAutoReconnect(e),this.stopHealthCheck(e),await this.gracefulDisconnect(e),await this.closeTunnel(e),this.passwords.delete(e),await this.setConnectionState(e,"disconnected")}async reconnect(e){if(this.cancelAutoReconnect(e),this.stopHealthCheck(e),this.drivers.has(e))await this.gracefulDisconnect(e);await this.connect(e)}getDriver(e,t){let n=this.drivers.get(e);if(!n)throw Error(`No active connection for id: ${e}`);let r=t??this.getDefaultDatabaseName(e),s=n.get(r);if(!s)throw Error(`No active driver for database "${r}" on connection ${e}`);return s}getConnectionState(e){return this.states.get(e)?.state??"disconnected"}listConnectionHandles(){let e=[];for(let[t,n]of this.drivers){let s=this.appDb.getConnectionById(t)?.name??t;for(let[i,o]of n)for(let a of o.listConnectionHandles())e.push({...a,connectionId:t,connectionName:s,database:i,driverType:o.getDriverType()})}return e}async terminateConnectionHandle(e,t,n){await this.getDriver(e,t).terminateConnectionHandle(n)}async listDatabases(e){let t=this.appDb.getConnectionById(e);if(!t||!U[t.config.type].supportsMultiDatabase)throw Error("listDatabases is only supported for connections with multi-database support");let n=V(t.config),r=this.getDriver(e,n),s=t.config.type==="postgresql"?ar:or,i=await r.execute(s),o=this.drivers.get(e),a=o?[...o.keys()]:[n];return i.rows.map((c)=>({name:c.name,isDefault:c.name===n,isActive:a.includes(c.name)}))}async activateDatabase(e,t){let n=this.appDb.getConnectionById(e);if(!n||!U[n.config.type].supportsMultiDatabase)throw Error("activateDatabase is only supported for connections with multi-database support");let r=n.config,s=this.drivers.get(e);if(!s)throw Error(`No active connection for id: ${e}`);if(s.has(t))return;let i=this.passwords.get(e)??r.password,o={...r,database:t,password:i};await this.connectDatabase(e,o,t);let a=[...new Set([...r.activeDatabases??[],t])];this.appDb.updateConnection({id:e,name:n.name,config:{...r,activeDatabases:a}})}async deactivateDatabase(e,t){let n=this.appDb.getConnectionById(e);if(!n||!U[n.config.type].supportsMultiDatabase)throw Error("deactivateDatabase is only supported for connections with multi-database support");let r=n.config;if(t===V(r))throw Error("Cannot deactivate the default database");let s=this.drivers.get(e);if(s){let o=s.get(t);if(o)try{await o.disconnect()}finally{s.delete(t)}}let i=(r.activeDatabases??[]).filter((o)=>o!==t);this.appDb.updateConnection({id:e,name:n.name,config:{...r,activeDatabases:i.length>0?i:void 0}})}listConnections(){return this.appDb.listConnections().map((t)=>({...t,state:this.getConnectionState(t.id),error:this.states.get(t.id)?.error}))}createConnection(e,t=!1){return ge(e.config,t),this.appDb.createConnection(e)}updateConnection(e){return ge(e.config),{...this.appDb.updateConnection(e),state:this.getConnectionState(e.id),error:this.states.get(e.id)?.error}}setConnectionReadOnly(e,t){return{...this.appDb.setConnectionReadOnly(e,t),state:this.getConnectionState(e),error:this.states.get(e)?.error}}async deleteConnection(e){if(this.cancelAutoReconnect(e),this.stopHealthCheck(e),this.drivers.has(e))await this.disconnectAllDrivers(e);await this.closeTunnel(e),this.passwords.delete(e),this.states.delete(e),this.appDb.deleteConnection(e)}async testConnection(e){ge(e);let t=null,n=e;try{if(e.type==="postgresql"&&e.sshTunnel?.enabled)t=await He(e.sshTunnel,e.host,e.port),n={...e,host:"127.0.0.1",port:t.localPort};let r=he(n);return await r.connect(n),await r.disconnect(),{success:!0}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown connection error"}}finally{if(t)await t.close()}}async listDatabasesForConfig(e){if(e.type!=="postgresql"&&e.type!=="mysql")throw Error(`Listing databases is not supported for connection type: ${e.type}`);let t=e.type==="postgresql"?"postgres":"information_schema",n=e.database?e:{...e,database:t};ge(n);let r=null;try{if(n.type==="postgresql"&&n.sshTunnel?.enabled)r=await He(n.sshTunnel,n.host,n.port),n={...n,host:"127.0.0.1",port:r.localPort};let s=he(n);try{await s.connect(n);let i=n.type==="postgresql"?ar:or;return(await s.execute(i)).rows.map((a)=>a.name)}finally{await s.disconnect().catch(()=>{})}}finally{if(r)await r.close().catch(()=>{})}}onStatusChanged(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);if(t>=0)this.listeners.splice(t,1)}}onSessionDead(e){return this.sessionDeadListeners.push(e),()=>{let t=this.sessionDeadListeners.indexOf(e);if(t>=0)this.sessionDeadListeners.splice(t,1)}}async disconnectAll(){for(let t of[...this.reconnectStates.keys()])this.cancelAutoReconnect(t);for(let t of[...this.healthTimers.keys()])this.stopHealthCheck(t);let e=[...new Set([...this.drivers.keys(),...this.tunnels.keys()])];for(let t of e)await this.disconnect(t)}startHealthCheck(e){this.stopHealthCheck(e);let t=setInterval(()=>{this.performHealthCheck(e)},this.opts.healthCheckIntervalMs);this.healthTimers.set(e,t)}stopHealthCheck(e){let t=this.healthTimers.get(e);if(t)clearInterval(t),this.healthTimers.delete(e)}async performHealthCheck(e){if(this.healthCheckRunning.has(e))return;this.healthCheckRunning.add(e);try{let t=this.drivers.get(e);if(!t)return;for(let n of t.values()){try{await Promise.race([n.ping(),new Promise((r,s)=>setTimeout(()=>s(Error("Health check timed out")),this.opts.healthCheckTimeoutMs))])}catch{let r=!1;for(let s of t.values()){if(s.inTransaction()){r=!0;break}for(let i of s.getSessionIds())if(s.inTransaction(i)){r=!0;break}if(r)break}this.stopHealthCheck(e);try{await this.disconnectAllDrivers(e)}catch{}await this.setConnectionState(e,"disconnected","Connection lost"),this.startAutoReconnect(e,r);return}for(let r of n.getSessionIds())try{await n.execute("SELECT 1",void 0,r)}catch{try{await n.releaseSession(r)}catch{}for(let s of this.sessionDeadListeners)try{await s({connectionId:e,sessionId:r})}catch{}}}}finally{this.healthCheckRunning.delete(e)}}startAutoReconnect(e,t=!1){this.cancelAutoReconnect(e);let n={attempt:0,timer:null,cancelled:!1,hadTransaction:t};this.reconnectStates.set(e,n),this.scheduleReconnectAttempt(e,n)}cancelAutoReconnect(e){let t=this.reconnectStates.get(e);if(t){if(t.cancelled=!0,t.timer)clearTimeout(t.timer);this.reconnectStates.delete(e)}}async scheduleReconnectAttempt(e,t){if(t.cancelled)return;if(t.attempt>=this.opts.reconnectMaxAttempts){this.reconnectStates.delete(e),await this.setConnectionState(e,"error",`Reconnect failed after ${this.opts.reconnectMaxAttempts} attempts`);return}let n=Math.min(this.opts.reconnectBaseDelayMs*Math.pow(2,t.attempt),this.opts.reconnectMaxDelayMs);t.timer=setTimeout(()=>{if(t.cancelled)return;this.attemptReconnect(e,t).catch(()=>{})},n)}async attemptReconnect(e,t){if(t.cancelled)return;let n=this.appDb.getConnectionById(e);if(!n){this.cancelAutoReconnect(e);return}t.attempt++,await this.setConnectionState(e,"reconnecting");try{await this.closeTunnel(e);let r=this.passwords.get(e),s=r?{...n.config,password:r}:n.config;s=await this.setupSshTunnel(e,s);let i=V(s),o=he(s);if(await o.connect(s),t.cancelled){await o.disconnect(),await this.closeTunnel(e);return}let a=new Map;if(a.set(i,o),this.drivers.set(e,a),U[s.type].supportsMultiDatabase&&"activeDatabases"in s&&s.activeDatabases){let u=s,l=(u.activeDatabases??[]).filter((m)=>m!==u.database).map((m)=>this.connectDatabase(e,u,m));await Promise.allSettled(l)}let c=t.hadTransaction;this.reconnectStates.delete(e),await this.setConnectionState(e,"connected",void 0,void 0,c),this.startHealthCheck(e)}catch{if(t.cancelled)return;await this.closeTunnel(e),this.scheduleReconnectAttempt(e,t)}}async gracefulDisconnect(e){let t=this.drivers.get(e);if(!t)return;for(let[n,r]of t)try{for(let s of r.getSessionIds()){try{await r.cancel(s)}catch{}if(r.inTransaction(s))try{await r.rollback(s)}catch{}}if(r.inTransaction())try{await r.rollback()}catch{}try{await r.cancel()}catch{}}finally{try{await r.disconnect()}finally{t.delete(n)}}this.drivers.delete(e)}async disconnectAllDrivers(e){let t=this.drivers.get(e);if(!t)return;for(let[n,r]of t)try{await r.disconnect()}finally{t.delete(n)}this.drivers.delete(e)}async connectDatabase(e,t,n){let r=this.drivers.get(e);if(!r)throw Error(`No active connection for id: ${e}`);let s=this.tunnels.get(e),i=s?{host:"127.0.0.1",port:s.localPort}:{},o={...t,...i,database:n},a=he(o);await a.connect(o),r.set(n,a)}async setupSshTunnel(e,t){if(t.type!=="postgresql"||!t.sshTunnel?.enabled)return t;let n=await He(t.sshTunnel,t.host,t.port);return this.tunnels.set(e,n),{...t,host:"127.0.0.1",port:n.localPort}}async closeTunnel(e){let t=this.tunnels.get(e);if(t)await t.close(),this.tunnels.delete(e)}getActiveDatabases(e){let t=this.drivers.get(e);if(!t)return[];return[...t.keys()]}getDefaultDatabaseName(e){let t=this.appDb.getConnectionById(e);if(!t)throw Error(`Connection not found: ${e}`);return V(t.config)}async setConnectionState(e,t,n,r,s){this.states.set(e,{state:t,error:n});let i=this.listeners.map((o)=>o({connectionId:e,state:t,error:n,errorCode:r,transactionLost:s||void 0}));await Promise.allSettled(i)}}function he(e){let t;switch(e.type){case"postgresql":t=new vt;break;case"sqlite":t=new Rt;break;case"mysql":t=new At;break;default:throw Error(`Unsupported connection type: ${e.type}`)}if(process.env.DEBUG_SQL)t=new Ct(t);return t}function ge(e,t=!1){if(!e?.type)throw Error("Connection config must have a type");let n=U[e.type];if(!n)throw Error(`Unsupported connection type: ${e.type}`);if(n.hasHost&&k(e)){let r=n.label;if(!e.host)throw Error(`${r} host is required`);if(!e.port)throw Error(`${r} port is required`);if(!e.database)throw Error(`${r} database is required`);if(!e.user)throw Error(`${r} user is required`);if(!t&&(e.password===void 0||e.password===null))throw Error(`${r} password is required`)}else if(e.type==="sqlite"){if(!e.path)throw Error("SQLite path is required")}}var ci,or,ar="SELECT datname AS name FROM pg_database WHERE datistemplate = false AND datallowconn = true ORDER BY datname",li;var cr=T(()=>{le();P();tr();nr();rr();ir();ci=["mysql","information_schema","performance_schema","sys"],or=`SELECT schema_name AS name FROM information_schema.schemata WHERE schema_name NOT IN (${ci.map((e)=>`'${e}'`).join(", ")}) ORDER BY schema_name`,li={healthCheckIntervalMs:30000,healthCheckTimeoutMs:1e4,reconnectBaseDelayMs:1000,reconnectMaxDelayMs:30000,reconnectMaxAttempts:5}});function ui(e){let t=[],n=/-c\s+([^\s=]+)=([^\s]+)/g,r;while((r=n.exec(e))!==null){let s=r[1],i=r[2].replace(/'/g,"''");t.push(`SET ${s} = '${i}';`)}return t.join(`
336
- `)}function lr(){let e=process.env.DATABASE_URL;if(!e)return null;let t;try{t=new URL(e)}catch{return console.warn("DATABASE_URL: invalid URL, ignoring"),null}let n=t.protocol.replace(/:$/,"");if(n==="postgresql"||n==="postgres"){let r=t.hostname||"localhost",s=t.port?Number(t.port):5432,i=t.pathname.replace(/^\//,"")||"postgres",o=decodeURIComponent(t.username||"postgres"),a=decodeURIComponent(t.password||""),c=t.searchParams.get("options"),u=process.env.DOTAZ_INIT_SQL?.trim()||(c?ui(c):"")||void 0;return{name:`${r}/${i}`,config:{type:"postgresql",host:r,port:s,database:i,user:o,password:a,initSql:u}}}if(n==="mysql"){let r=t.hostname||"localhost",s=t.port?Number(t.port):3306,i=t.pathname.replace(/^\//,"")||"mysql",o=decodeURIComponent(t.username||"root"),a=decodeURIComponent(t.password||""),c=process.env.DOTAZ_INIT_SQL?.trim()||void 0;return{name:`${r}/${i}`,config:{type:"mysql",host:r,port:s,database:i,user:o,password:a,initSql:c}}}return console.warn(`DATABASE_URL: unsupported scheme "${n}", ignoring`),null}var re="env-default";function Dt(e,t){if(!t.has(e.id))return e;return{...e,config:Tn(e.config),serverManaged:!0}}function Qe(e,t){return(...n)=>{let r=e(...n);return r instanceof Promise?r.then((s)=>Dt(s,t)):Dt(r,t)}}function Ot(){return Ye}function dr(e,t){let n=crypto.randomUUID(),r=me.create(":memory:"),s=new Nt(r),i=new ce(s,void 0,r),o=new dt(t),a=(h,y)=>{if(d.ws)d.ws.send(JSON.stringify({type:"message",channel:h,payload:y}))},{handlers:c,sessionManager:u}=Vn(s,i,r,void 0,{encryption:o,emitMessage:a,allowServerFileAccess:!1}),l=new Set,m=lr();if(m){let h=Be.size>0?{...m.config,activeDatabases:[...Be]}:m.config;r.createConnectionWithId(re,{name:m.name,config:h}),l.add(re);let y=c["connections.list"];c["connections.list"]=()=>y().map((L)=>Dt(L,l));let w=c["connections.create"];c["connections.create"]=Qe(w,l);let p=c["connections.setReadOnly"];c["connections.setReadOnly"]=Qe(p,l);let S=c["connections.setGroup"];c["connections.setGroup"]=Qe(S,l);let E=c["connections.update"];c["connections.update"]=Qe((v)=>{if(l.has(v.id))throw Error("Server-managed connections cannot be reconfigured");return E(v)},l);let C=c["databases.activate"];c["databases.activate"]=async(v)=>{let L=await C(v);if(v.connectionId===re)Be.add(v.database);return L};let N=c["databases.deactivate"];c["databases.deactivate"]=async(v)=>{let L=await N(v);if(v.connectionId===re)Be.delete(v.database);return L}}let f=s.onSessionDead((h)=>{if(u.handleSessionDead(h.sessionId),d.ws)d.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:h.connectionId,sessions:u.listSessions(h.connectionId)}}))}),g=s.onStatusChanged(async(h)=>{if(d.ws)d.ws.send(JSON.stringify({type:"message",channel:"connections.statusChanged",payload:{connectionId:h.connectionId,state:h.state,error:h.error,errorCode:h.errorCode,transactionLost:h.transactionLost}}));if(h.state==="disconnected"||h.state==="error"){if(u.handleConnectionLost(h.connectionId),d.ws)d.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:h.connectionId,sessions:[]}}))}if(h.state==="connected")try{let y=await u.handleConnectionRestored(h.connectionId);if(y.length>0&&d.ws)d.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:h.connectionId,sessions:y}}))}catch(y){console.warn("Session restoration failed:",y instanceof Error?y.message:y)}}),d={id:n,appDb:r,connectionManager:s,queryExecutor:i,handlers:c,sessionManager:u,serverManagedIds:l,unsubscribe:()=>{f(),g()},ws:e,activeStreams:0,disconnectedAt:null,ttlTimer:null};if(Ye.set(n,d),m)s.connect(re).catch((h)=>{console.warn("DATABASE_URL auto-connect failed:",h?.message??h)});return d}async function ye(e){if(Ye.delete(e.id),e.ttlTimer)clearTimeout(e.ttlTimer),e.ttlTimer=null;e.unsubscribe(),e.sessionManager.dispose();for(let t of e.queryExecutor.getRunningQueryIds())await e.queryExecutor.cancelQuery(t);await e.connectionManager.disconnectAll(),e.appDb.close()}async function mr(e){if(e.ws=null,e.disconnectedAt=Date.now(),e.activeStreams===0)await ye(e);else e.ttlTimer=setTimeout(async()=>{if(Ye.has(e.id))await ye(e)},_t)}async function It(e){if(e.activeStreams--,e.ws===null&&e.activeStreams===0)await ye(e)}function xt(e,t,n,r,s){let i=crypto.randomUUID();return se.set(i,{session:e,connectionId:n,database:r,params:s,type:t,createdAt:Date.now()}),i}function Lt(e,t){let n=se.get(e);if(!n)return null;if(n.type!==t)return null;if(Date.now()-n.createdAt>ur)return se.delete(e),null;return se.delete(e),n}function pr(){let e=Date.now();for(let[t,n]of se)if(e-n.createdAt>ur)se.delete(t)}var _t=300000,ur=300000,Ye,Be,se;var fr=T(()=>{Jn();cr();mt();xe();ht();le();Ye=new Map,Be=new Set;se=new Map});import{resolve as Pt}from"path";async function hi(e,t){let n=Lt(t,"export");if(!n)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:r,connectionId:s,database:i,params:o}=n,a=o,c;try{c=r.connectionManager.getDriver(s,i)}catch(d){return new Response(JSON.stringify({error:d?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}r.activeStreams++;let u=pi[a.format]??"application/octet-stream",l=fi[a.format]??"dat",m=`${a.table}.${l}`,f=new AbortController;e.signal.addEventListener("abort",()=>f.abort());let g=new ReadableStream({async start(d){let h={write(y){if(typeof y==="string")d.enqueue(new TextEncoder().encode(y));else d.enqueue(y)},async end(){}};try{let y=await et(c,a,h,f.signal,(w)=>{if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"export.progress",payload:{rowCount:w}}))});if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"export.complete",payload:{rowCount:y.rowCount}}));d.close()}catch(y){if(f.signal.aborted)try{d.close()}catch{}else d.error(y)}finally{await It(r)}}});return new Response(g,{headers:{"Content-Type":u,"Content-Disposition":`attachment; filename="${m}"`}})}async function gi(e,t){let n=Lt(t,"import");if(!n)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:r,connectionId:s,database:i,params:o}=n,a=o,c;try{c=r.connectionManager.getDriver(s,i)}catch(l){return new Response(JSON.stringify({error:l?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}if(!e.body)return new Response(JSON.stringify({error:"Request body is required"}),{status:400,headers:{"Content-Type":"application/json"}});r.activeStreams++;let u=new AbortController;e.signal.addEventListener("abort",()=>u.abort());try{let l=await ve(c,e.body,a,u.signal,(m)=>{if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"import.progress",payload:{rowCount:m}}))});return new Response(JSON.stringify({rowCount:l.rowCount}),{headers:{"Content-Type":"application/json"}})}catch(l){return new Response(JSON.stringify({error:l?.message??"Import failed"}),{status:500,headers:{"Content-Type":"application/json"}})}finally{await It(r)}}var di,kt,hr,Q,gr,mi=60000,pi,fi,yi;var yr=T(()=>{Kt();tt();rt();fr();di=Number(process.env.DOTAZ_PORT)||6401,kt=process.env.DOTAZ_HOST||"localhost",hr=process.env.DOTAZ_DIST_DIR||Pt(import.meta.dir,"../../dist");try{Q=qt(kt)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}gr=process.env.DOTAZ_ENCRYPTION_KEY;if(!gr)console.error("DOTAZ_ENCRYPTION_KEY is required for web mode"),process.exit(1);setInterval(()=>{pr()},60000);setInterval(async()=>{let e=Date.now();for(let[,t]of Ot())if(t.disconnectedAt!==null&&e-t.disconnectedAt>_t)await ye(t)},mi);pi={csv:"text/csv",json:"application/json",sql:"application/sql",markdown:"text/markdown",sql_update:"application/sql",html:"text/html",xml:"application/xml"},fi={csv:"csv",json:"json",sql:"sql",markdown:"md",sql_update:"sql",html:"html",xml:"xml"};yi=Bun.serve({port:di,hostname:kt,async fetch(e,t){let n=new URL(e.url);if(!Ke(e,Q))return new Response("Host not allowed",{status:403});if(n.pathname==="/api/bootstrap"&&e.method==="GET"){let a=K(e,Q);if(!a.ok)return W(a,"json");return Response.json({ok:!0})}if(n.pathname==="/rpc"){let a=K(e,Q);if(!a.ok)return W(a,"text");if(t.upgrade(e,{data:{}}))return;return new Response("WebSocket upgrade failed",{status:400})}let r=n.pathname.match(/^\/api\/stream\/export\/([a-f0-9-]+)$/);if(r&&e.method==="GET"){let a=K(e,Q);if(!a.ok)return W(a,"json");return hi(e,r[1])}let s=n.pathname.match(/^\/api\/stream\/import\/([a-f0-9-]+)$/);if(s&&e.method==="POST"){let a=K(e,Q);if(!a.ok)return W(a,"json");return gi(e,s[1])}if(n.pathname==="/api/menu-action"&&e.method==="POST"){let a=K(e,Q);if(!a.ok)return W(a,"json");try{let u=(await e.json())?.action;if(!u)return new Response(JSON.stringify({error:"Missing action"}),{status:400,headers:{"Content-Type":"application/json"}});for(let[,l]of Ot())if(l.ws)l.ws.send(JSON.stringify({type:"message",channel:"menu.action",payload:{action:u}}));return new Response(JSON.stringify({ok:!0}),{headers:{"Content-Type":"application/json"}})}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}}let i=Pt(hr,n.pathname.slice(1)),o=Bun.file(i);if(await o.exists())return new Response(o);if(i=Pt(hr,"index.html"),o=Bun.file(i),await o.exists())return new Response(o,{headers:{"Content-Type":"text/html"}});return new Response("Not found",{status:404})},websocket:{open(e){let t=dr(e,gr);Object.assign(e.data,t)},async close(e){await mr(e.data)},async message(e,t){let n=Yt(typeof t==="string"?t:new Uint8Array(t));if(!n){e.send(JSON.stringify(Bt()));return}let s=await Qt(n,(i)=>{if(i==="stream.createExportToken")return({connectionId:o,database:a,...c})=>({token:xt(e.data,"export",o,a,c)});if(i==="stream.createImportToken")return({connectionId:o,database:a,...c})=>({token:xt(e.data,"import",o,a,c)});return e.data.handlers[i]});e.send(JSON.stringify(s))}}});console.log(`Dotaz web server running at http://${kt}:${yi.port}`)});var{secrets:Sr}=globalThis.Bun;import{randomBytes as Si}from"crypto";import{resolve as wi}from"path";function je(e){return typeof e==="string"&&e.trim().length>0}function Ht(e,t){if(je(t))return null;if(Y(e))return null;return"DOTAZ_ENCRYPTION_KEY is required when binding Dotaz to a non-loopback host. Set it to a stable random value so saved credentials remain decryptable across restarts."}var wr="dev.dotaz.server",Er="encryption-key",ie=process.argv.slice(2),Cr=Number(process.env.DOTAZ_PORT)||6401,Mt=process.env.DOTAZ_HOST||"localhost";for(let e=0;e<ie.length;e++){let t=ie[e];if((t==="--port"||t==="-p")&&ie[e+1])Cr=Number(ie[e+1]),e++;else if((t==="--host"||t==="-H")&&ie[e+1])Mt=ie[e+1],e++;else if(t==="--help")console.log(`Usage: dotaz [options]
345
+ ORDER BY matviewname`,[t])].map((r)=>({schema:t,name:r.matviewname,type:"materialized-view"}))}async ping(){this.ensureConnected();try{await this.pool.getSystemConnection().unsafe("SELECT 1")}catch{await this.pool.reconnectSystemConnection()}}async beginTransaction(e){if(this.ensureConnected(),e){let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);await t.conn.unsafe("BEGIN"),t.txActive=!0,t.txAborted=!1}else{if(this.sessions.has(P)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let t=await this.pool.acquireConnection();try{await t.unsafe("BEGIN")}catch(n){throw await this.pool.releaseConnection(t),n}this.sessions.set(P,{conn:t,txActive:!0,txAborted:!1,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit(e){this.ensureConnected();let t=e??P,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot commit during active iteration");try{await n.conn.unsafe("COMMIT"),n.txActive=!1,n.txAborted=!1}catch(r){if(z(r))throw n.txActive=!1,n.txAborted=!1,new b("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:r});try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1,n.txAborted=!1}catch{}throw r}finally{if(t===P)this.sessions.delete(P),await this.pool.releaseConnection(n.conn)}}async rollback(e){this.ensureConnected();let t=e??P,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot rollback during active iteration");try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1,n.txAborted=!1}catch(r){if(z(r))n.txActive=!1,n.txAborted=!1;throw r}finally{if(t===P)this.sessions.delete(P),await this.pool.releaseConnection(n.conn)}}inTransaction(e){let t=e??P;return this.sessions.get(t)?.txActive??!1}isTxAborted(e){let t=e??P;return this.sessions.get(t)?.txAborted??!1}isIterating(e){let t=e??P;return this.sessions.get(t)?.iterating??!1}getDriverType(){return"postgresql"}listConnectionHandles(){if(!this.pool)return[];return this.pool.snapshot().map((e)=>this.describePoolConnection(e))}async terminateConnectionHandle(e){this.ensureConnected();let t=this.findSessionByHandleId(e);if(t){await this.cancel(t.sessionId),await this.releaseSession(t.sessionId);return}if(!await this.pool.terminateConnection(e))throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`"${e.replace(/"/g,'""')}"`}qualifyTable(e,t){return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} DEFAULT VALUES`}placeholder(e){return`$${e}`}async*iterate(e,t,n=1000,r,s){this.ensureConnected();let i=`dotaz_iter_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=s?this.sessions.get(s):void 0;if(s&&!o)throw Error(`Session "${s}" not found`);if(o?.txActive)throw Error("Cannot iterate on a session with an active transaction");let a=o?o.conn:await this.pool.acquireConnection(),c=!o;if(o)o.txActive=!0,o.iterating=!0;let u=!1;try{await a.unsafe("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"),await a.unsafe(`DECLARE ${i} NO SCROLL CURSOR FOR ${e}`,t??[]);try{while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");let d=[...await a.unsafe(`FETCH FORWARD ${n} FROM ${i}`)];if(d.length===0)break;if(yield d,d.length<n)break}}finally{try{await a.unsafe(`CLOSE ${i}`)}catch{}}await a.unsafe("COMMIT")}catch(l){u=!0;try{await a.unsafe("ROLLBACK")}catch{}throw l}finally{if(o)o.txActive=!1,o.iterating=!1;if(c)await this.pool.releaseConnection(a);else if(o&&!u)try{await a.unsafe("ROLLBACK")}catch{}}}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let d=0;d<t.length;d++)i.push(n[u][t[d]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}ensureConnected(){if(!this.pool||!this.connected)throw Error("Not connected. Call connect() first.")}describePoolConnection(e){let t=this.findSessionByHandleId(e.handleId);if(t){let i=t.session,o=t.sessionId===P,a=i.txActive?"transaction":i.iterating||i.activeQueries.size>0?"active":"idle";return{handleId:e.handleId,role:o?"default-transaction":"session",state:a,label:o?"Default transaction":void 0,sessionId:o?void 0:t.sessionId,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:i.activeQueries.size,inTransaction:i.txActive,txAborted:i.txAborted,iterating:i.iterating,canTerminate:!0}}let n=e.role==="system"?"system":e.role==="idle"?"idle":"temporary",r=e.role==="system"?this.poolActiveQueries.size:0,s=r>0||e.role==="leased"?"active":"idle";return{handleId:e.handleId,role:n,state:s,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:r,inTransaction:!1,txAborted:!1,iterating:e.role==="leased",canTerminate:!0}}findSessionByHandleId(e){if(!this.pool)return;for(let[t,n]of this.sessions)if(this.pool.getConnectionId(n.conn)===e)return{sessionId:t,session:n};return}resolveSession(e){if(!e)return;let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);return t}mapDataType(e,t){if(e==="ARRAY")return"array";if(e==="USER-DEFINED"){let n=t.toLowerCase();if(n==="json"||n==="jsonb")return"json";return"enum"}return co(e)}}var P="__default__";var Ir=C(()=>{K();q();Mt();Ke();Ye()});var{SQL:je}=globalThis.Bun;function lo(e){let t=e.toUpperCase();if(t==="INTEGER"||t==="INT"||t==="BIGINT"||t==="SMALLINT"||t==="TINYINT"||t==="MEDIUMINT")return"integer";if(t==="REAL"||t==="FLOAT"||t==="DOUBLE")return"float";if(t==="NUMERIC"||t==="DECIMAL")return"numeric";if(t==="BOOLEAN"||t==="BOOL")return"boolean";if(t==="TEXT")return"text";if(t.includes("VARCHAR")||t.includes("VARYING"))return"varchar";if(t.includes("CHAR")&&!t.includes("VARCHAR"))return"char";if(t==="DATE")return"date";if(t==="TIME")return"time";if(t==="DATETIME"||t.includes("TIMESTAMP"))return"timestamp";if(t==="JSON"||t==="JSONB")return"json";if(t==="BLOB"||t==="BINARY"||t.includes("VARBINARY"))return"binary";return"unknown"}class $t{db=null;dbPath=null;connected=!1;txActive=!1;txOwnerSession=null;sessionIds=new Set;readOnlySessions=new Map;iterating=!1;iterateDb=null;iterateActive=!1;initSql=null;mainHandleId=null;mainCreatedAt=0;mainLastUsedAt=0;iterateHandleId=null;iterateCreatedAt=0;iterateLastUsedAt=0;nextHandleNumber=1;async connect(e){if(e.type!=="sqlite")throw Error("SqliteDriver requires a sqlite connection config");let t=e.initSql?.trim()||null;try{this.db=new je(`sqlite:${e.path}`),this.dbPath=e.path,this.resetMainHandle(),await this.db.unsafe("PRAGMA journal_mode = WAL"),await this.db.unsafe("PRAGMA foreign_keys = ON"),this.initSql=t,await this.applyInitSql(this.db)}catch(n){if(this.db)try{await this.db.close()}catch{}throw this.db=null,this.dbPath=null,this.initSql=null,this.mainHandleId=null,this.mainCreatedAt=0,this.mainLastUsedAt=0,n instanceof b?n:se(n)}this.connected=!0}async disconnect(){this.connected=!1;for(let e of this.readOnlySessions.values())await M(e.conn,{rollback:e.txActive});if(this.readOnlySessions.clear(),this.iterateDb){try{await this.iterateDb.close()}catch{}this.iterateDb=null,this.iterateHandleId=null,this.iterateCreatedAt=0,this.iterateLastUsedAt=0,this.iterateActive=!1}if(this.db)await this.db.close(),this.db=null,this.dbPath=null,this.initSql=null,this.mainHandleId=null,this.mainCreatedAt=0,this.mainLastUsedAt=0,this.txActive=!1,this.txOwnerSession=null,this.sessionIds.clear()}isConnected(){return this.connected}async reserveSession(e,t){if(t?.readOnly)await this.openReadOnlyHandle(e);this.sessionIds.add(e)}async releaseSession(e){let t=this.readOnlySessions.get(e);if(t){this.readOnlySessions.delete(e),await M(t.conn,{rollback:t.txActive}),this.sessionIds.delete(e);return}if(this.txActive&&this.txOwnerSession===e){try{await this.db.unsafe("ROLLBACK")}catch{}this.txActive=!1,this.txOwnerSession=null}this.sessionIds.delete(e)}getSessionIds(){return[...this.sessionIds]}isSessionReadOnly(e){return this.readOnlySessions.has(e)}async execute(e,t,n){this.ensureConnected(),this.ensureKnownSession(n);let r=n===void 0?void 0:this.readOnlySessions.get(n);if(r){r.lastUsedAt=Date.now();let o=await this.runStatement(r.conn,e,t);return oe(r,e),o}this.ensureSessionCanExecute(n),this.markMainUsed();let s=await this.runStatement(this.db,e,t),i=e.trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(i))this.txActive=!0,this.txOwnerSession=n??null;else if(/^(COMMIT|END)\b/.test(i))this.txActive=!1,this.txOwnerSession=null;else if(/^ROLLBACK\b/.test(i)&&!/^ROLLBACK\s+TO\b/.test(i))this.txActive=!1,this.txOwnerSession=null;return s}async runStatement(e,t,n){let r=performance.now();try{let s=await e.unsafe(t,n??[]),i=Math.round(performance.now()-r),o=[...s];return{columns:o.length>0?Object.keys(o[0]).map((c)=>({name:c,dataType:"unknown"})):[],rows:o,rowCount:o.length,affectedRows:ie(s),durationMs:i}}catch(s){throw s instanceof b?s:se(s)}}async openReadOnlyHandle(e){if(this.ensureConnected(),this.readOnlySessions.has(e))return;if(!this.dbPath||this.dbPath===":memory:")throw Error("Read-only sessions require a file-backed SQLite database");let t=new je({adapter:"sqlite",filename:this.dbPath,readonly:!0});try{await t.unsafe("PRAGMA foreign_keys = ON"),await this.applyInitSql(t),await t.unsafe("PRAGMA query_only = ON")}catch(r){try{await t.close()}catch{}throw r instanceof b?r:se(r)}let n=Date.now();this.readOnlySessions.set(e,{conn:t,txActive:!1,iterating:!1,handleId:this.createHandleId(),createdAt:n,lastUsedAt:n})}async cancel(e,t){}async loadSchema(e){this.ensureConnected(),this.markMainUsed();let t=await this.getSchemas(),n=t[0].name,r=await this.getTables(n),s={[n]:r},i={},o={},a={},c={},u=new Map;for(let l of r){let d=`${n}.${l.name}`;i[d]=await this.getColumns(n,l.name),o[d]=await this.getIndexes(n,l.name);let f=await this.getForeignKeys(n,l.name);a[d]=f;for(let h of f){let p=`${h.referencedSchema}.${h.referencedTable}`;if(!u.has(p))u.set(p,[]);u.get(p).push({constraintName:h.name,referencingSchema:n,referencingTable:l.name,referencingColumns:h.columns,referencedColumns:h.referencedColumns})}}for(let l of r){let d=`${n}.${l.name}`;c[d]=u.get(d)??[]}return{schemas:t,tables:s,columns:i,indexes:o,foreignKeys:a,referencingForeignKeys:c}}async getSchemas(){return[{name:"main"}]}async getTables(e){return this.ensureConnected(),[...await this.db.unsafe("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name")].map((n)=>({schema:e,name:n.name,type:n.type}))}async getColumns(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA table_info(${this.quoteIdentifier(t)})`)],r=n.filter((s)=>s.pk>0).length;return n.map((s)=>({name:s.name,dataType:lo(s.type||"BLOB"),nullable:s.notnull===0&&s.pk===0,defaultValue:s.dflt_value,isPrimaryKey:s.pk>0,isAutoIncrement:s.pk>0&&r===1&&s.type?.toUpperCase()==="INTEGER"}))}async getIndexes(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA index_list(${this.quoteIdentifier(t)})`)],r=[];for(let s of n){let i=[...await this.db.unsafe(`PRAGMA index_info(${this.quoteIdentifier(s.name)})`)];r.push({name:s.name,columns:i.map((o)=>o.name),isUnique:s.unique===1,isPrimary:s.origin==="pk"})}return r}async getForeignKeys(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA foreign_key_list(${this.quoteIdentifier(t)})`)],r=new Map;for(let s of n){let i=r.get(s.id);if(i)i.columns.push(s.from),i.referencedColumns.push(s.to);else r.set(s.id,{name:`fk_${t}_${s.id}`,columns:[s.from],referencedSchema:"main",referencedTable:s.table,referencedColumns:[s.to],onUpdate:s.on_update,onDelete:s.on_delete})}return Array.from(r.values())}async ping(){this.ensureConnected(),this.markMainUsed(),await this.db.unsafe("SELECT 1")}async*iterate(e,t,n=1000,r,s){this.ensureConnected(),this.ensureKnownSession(s);let i=s===void 0?void 0:this.readOnlySessions.get(s),o=!i&&this.dbPath===":memory:",a;if(i){if(i.txActive)throw Error("Cannot iterate with an active transaction");a=i.conn,i.iterating=!0,i.lastUsedAt=Date.now()}else if(o){if(a=this.db,this.markMainUsed(),this.ensureSessionCanExecute(s),this.txActive)throw Error("Cannot iterate with an active transaction");this.txActive=!0,this.txOwnerSession=s??null,this.iterating=!0}else a=await this.getIterateDb(),this.iterateActive=!0,this.markIterateUsed();await a.unsafe("BEGIN");let c=!1;try{let u=0;while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");let l=`${e} LIMIT ? OFFSET ?`,f=[...await a.unsafe(l,[...t??[],n,u])];if(f.length===0)break;if(yield f,f.length<n)break;u+=n}await a.unsafe("COMMIT"),c=!0}catch(u){try{await a.unsafe("ROLLBACK")}catch{}throw u}finally{if(!c)try{await a.unsafe("ROLLBACK")}catch{}if(i)i.iterating=!1,i.lastUsedAt=Date.now();else if(o)this.iterating=!1,this.txActive=!1,this.txOwnerSession=null;else this.iterateActive=!1,this.markIterateUsed()}}async getIterateDb(){if(!this.iterateDb){let e=new je(`sqlite:${this.dbPath}`);try{await this.applyInitSql(e)}catch(t){try{await e.close()}catch{}throw t instanceof b?t:se(t)}this.iterateDb=e,this.resetIterateHandle()}return this.iterateDb}async applyInitSql(e){if(!this.initSql)return;for(let t of x(this.initSql))await e.unsafe(t)}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let d=0;d<t.length;d++)i.push(n[u][t[d]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}async beginTransaction(e){this.ensureConnected(),this.ensureKnownSession(e);let t=e===void 0?void 0:this.readOnlySessions.get(e);if(t){if(t.txActive)throw Error("A transaction is already active");await t.conn.unsafe("BEGIN"),t.txActive=!0,t.lastUsedAt=Date.now();return}if(this.markMainUsed(),this.txActive)throw Error(e&&this.txOwnerSession!==e?`Another session ("${this.txOwnerSession}") already has an active transaction`:"A transaction is already active");await this.db.unsafe("BEGIN"),this.txActive=!0,this.txOwnerSession=e??null}async commit(e){this.ensureConnected(),this.ensureKnownSession(e);let t=e===void 0?void 0:this.readOnlySessions.get(e);if(t){if(!t.txActive)throw Error("No active transaction");if(t.iterating)throw Error("Cannot commit during active iteration");await t.conn.unsafe("COMMIT"),t.txActive=!1,t.lastUsedAt=Date.now();return}if(this.ensureSessionOwnsTx(e),this.iterating)throw Error("Cannot commit during active iteration");this.markMainUsed(),await this.db.unsafe("COMMIT"),this.txActive=!1,this.txOwnerSession=null}async rollback(e){this.ensureConnected(),this.ensureKnownSession(e);let t=e===void 0?void 0:this.readOnlySessions.get(e);if(t){if(!t.txActive)throw Error("No active transaction");if(t.iterating)throw Error("Cannot rollback during active iteration");try{await t.conn.unsafe("ROLLBACK")}finally{t.txActive=!1,t.lastUsedAt=Date.now()}return}if(this.ensureSessionOwnsTx(e),this.iterating)throw Error("Cannot rollback during active iteration");this.markMainUsed();try{await this.db.unsafe("ROLLBACK")}finally{this.txActive=!1,this.txOwnerSession=null}}inTransaction(e){if(e!==void 0){let t=this.readOnlySessions.get(e);if(t)return t.txActive;return this.txActive&&this.txOwnerSession===e}return this.txActive&&this.txOwnerSession===null}isTxAborted(e){return!1}isIterating(e){if(e!==void 0){let t=this.readOnlySessions.get(e);if(t)return t.iterating}return this.iterating}getDriverType(){return"sqlite"}listConnectionHandles(){if(!this.connected||!this.db||!this.mainHandleId)return[];let e=this.txActive?"transaction":this.iterating?"active":"idle",t=[{handleId:this.mainHandleId,role:"sqlite-main",state:e,createdAt:this.mainCreatedAt,lastUsedAt:this.mainLastUsedAt,activeQueryCount:0,inTransaction:this.txActive,txAborted:!1,iterating:this.iterating,canTerminate:!0}];if(this.iterateDb&&this.iterateHandleId)t.push({handleId:this.iterateHandleId,role:"sqlite-iterate",state:this.iterateActive?"active":"idle",createdAt:this.iterateCreatedAt,lastUsedAt:this.iterateLastUsedAt,activeQueryCount:this.iterateActive?1:0,inTransaction:this.iterateActive,txAborted:!1,iterating:this.iterateActive,canTerminate:!0});for(let[n,r]of this.readOnlySessions)t.push({handleId:r.handleId,role:"session",state:r.txActive?"transaction":r.iterating?"active":"idle",label:"Read-only session",sessionId:n,createdAt:r.createdAt,lastUsedAt:r.lastUsedAt,activeQueryCount:r.iterating?1:0,inTransaction:r.txActive,txAborted:!1,iterating:r.iterating,canTerminate:!0});return t}async terminateConnectionHandle(e){if(this.ensureConnected(),this.mainHandleId===e){await this.reopenMainConnection();return}for(let[t,n]of this.readOnlySessions)if(n.handleId===e){await this.releaseSession(t);return}if(this.iterateHandleId===e&&this.iterateDb){try{await this.iterateDb.close()}catch{}this.iterateDb=null,this.iterateHandleId=null,this.iterateCreatedAt=0,this.iterateLastUsedAt=0,this.iterateActive=!1;return}throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`"${e.replace(/"/g,'""')}"`}qualifyTable(e,t){if(e==="main")return this.quoteIdentifier(t);return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} DEFAULT VALUES`}placeholder(e){return`$${e}`}ensureKnownSession(e){if(e===void 0)return;if(!this.sessionIds.has(e))throw Error(`Session "${e}" not found`)}ensureSessionCanExecute(e){if(!this.txActive)return;if(this.iterating)throw Error("Cannot execute: iteration is in progress on the shared connection");if(this.txOwnerSession===null){if(e!==void 0)throw Error("Cannot execute: a sessionless transaction is active. SQLite uses a single connection shared by all sessions.");return}if(e===void 0||e!==this.txOwnerSession)throw Error(`Cannot execute: session "${this.txOwnerSession}" has an active transaction. SQLite uses a single connection shared by all sessions.`)}ensureSessionOwnsTx(e){if(!this.txActive)throw Error("No active transaction");if(!(e===void 0?this.txOwnerSession===null:this.txOwnerSession===e))throw Error(`Cannot modify transaction owned by ${this.txOwnerSession===null?"sessionless caller":`session "${this.txOwnerSession}"`}`)}ensureConnected(){if(!this.db||!this.connected)throw Error("Not connected. Call connect() first.")}async reopenMainConnection(){let e=this.dbPath;if(!e)throw Error("SQLite path is not available");if(this.db)try{await this.db.close()}catch{}let t=new je(`sqlite:${e}`);try{await t.unsafe("PRAGMA journal_mode = WAL"),await t.unsafe("PRAGMA foreign_keys = ON"),await this.applyInitSql(t)}catch(n){try{await t.close()}catch{}throw n instanceof b?n:se(n)}this.db=t,this.txActive=!1,this.txOwnerSession=null,this.iterating=!1,this.resetMainHandle()}resetMainHandle(){let e=Date.now();this.mainHandleId=this.createHandleId(),this.mainCreatedAt=e,this.mainLastUsedAt=e}resetIterateHandle(){let e=Date.now();this.iterateHandleId=this.createHandleId(),this.iterateCreatedAt=e,this.iterateLastUsedAt=e}createHandleId(){let e=`sqlite-${this.nextHandleNumber}`;return this.nextHandleNumber+=1,e}markMainUsed(){this.mainLastUsedAt=Date.now()}markIterateUsed(){this.iterateLastUsedAt=Date.now()}}var xr=C(()=>{H();K();q();Ke();Ye()});import{chmodSync as uo,unlinkSync as po,writeFileSync as mo}from"fs";import{tmpdir as fo}from"os";import{join as ho}from"path";async function wo(){return new Promise((e,t)=>{let n=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){},open(){},close(){},error(){}}}),r=n.port;if(n.stop(!0),r>0)e(r);else t(Error("Could not find a free port"))})}async function So(e,t,n){let r=Date.now()+t;while(Date.now()<r){if(n&&n.exitCode!==null)return;try{(await Bun.connect({hostname:"127.0.0.1",port:e,socket:{data(){},open(i){i.end()},close(){},error(){}}})).end();return}catch{await Bun.sleep(yo)}}throw Error(`SSH tunnel port ${e} did not become available within ${t/1000}s`)}async function We(e,t,n){let r=e.localPort||await wo(),s=null,i=null;try{let o=["ssh","-N","-L",`${r}:${t}:${n}`,"-p",String(e.port||22),"-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30","-o","ExitOnForwardFailure=yes"],a={...process.env};if(e.authMethod==="key"&&e.keyPath)o.push("-i",e.keyPath),o.push("-o","BatchMode=yes");else if(e.password)s=ho(fo(),`dotaz-askpass-${process.pid}-${Date.now()}`),mo(s,`#!/bin/sh
346
+ echo '${e.password.replace(/'/g,"'\\''")}'`),uo(s,448),a.SSH_ASKPASS=s,a.SSH_ASKPASS_REQUIRE="force",a.DISPLAY=a.DISPLAY||":0";if(o.push(`${e.username}@${e.host}`),i=Bun.spawn(o,{stdin:"pipe",stdout:"ignore",stderr:"pipe",env:a}),i.stdin&&typeof i.stdin!=="number")i.stdin.end();let c=i.stderr&&typeof i.stderr!=="number"?i.stderr:null,u=So(r,go,i),l=i.exited.then(async(f)=>{if(f!==0){let h=await Eo(c),p=bo(h)||`SSH process exited with code ${f}`;throw Error(p)}});return await Promise.race([u,l]),{localPort:r,close:async()=>{if(i)i.kill(),i=null;Pr(s)}}}catch(o){if(i)i.kill();if(Pr(s),o instanceof Error)throw Co(o);throw Error(`SSH tunnel error: ${String(o)}`)}}function Pr(e){if(e)try{po(e)}catch{}}async function Eo(e){if(!e)return"";try{let t=e.getReader(),n=[];while(!0){let{done:r,value:s}=await t.read();if(r)break;n.push(s)}return Buffer.concat(n).toString("utf-8")}catch{return""}}function bo(e){if(!e.trim())return null;let t=e.trim().split(`
347
+ `);for(let n of t){let r=n.toLowerCase();if(r.includes("permission denied")||r.includes("authentication"))return`SSH authentication failed: ${n.trim()}`;if(r.includes("connection refused"))return`SSH host unreachable: ${n.trim()}`;if(r.includes("timed out")||r.includes("timeout"))return`SSH connection timed out: ${n.trim()}`;if(r.includes("no such file")||r.includes("no such identity"))return`SSH key file not found: ${n.trim()}`;if(r.includes("could not resolve"))return`SSH host unreachable: ${n.trim()}`}return t[t.length-1]?.trim()||null}function Co(e){let t=e.message.toLowerCase();if(t.includes("authentication")||t.includes("permission denied"))return Error(`SSH authentication failed: ${e.message}`);if(t.includes("econnrefused")||t.includes("connection refused")||t.includes("unreachable"))return Error(`SSH host unreachable: ${e.message}`);if(t.includes("timeout")||t.includes("timed out"))return Error(`SSH connection timed out: ${e.message}`);return Error(`SSH tunnel error: ${e.message}`)}var go=15000,yo=100;var Lr=()=>{};class Ft{drivers=new Map;passwords=new Map;states=new Map;listeners=[];sessionDeadListeners=[];appDb;opts;tunnels=new Map;healthTimers=new Map;reconnectStates=new Map;healthCheckRunning=new Set;connectAttempt=new Map;constructor(e,t){this.appDb=e,this.opts={...Ao,...t}}async connect(e,t){let n=this.appDb.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);this.cancelAutoReconnect(e);let r=(this.connectAttempt.get(e)??0)+1;if(this.connectAttempt.set(e,r),this.drivers.has(e))await this.disconnectAllDrivers(e);await this.closeTunnel(e),await this.setConnectionState(e,"connecting");try{let s=t?{...n.config,...t}:n.config;if(Ee(s),B(s))this.passwords.set(e,s.password);s=await this.setupSshTunnel(e,s);let i=ee(s),o=Se(s);if(await o.connect(s),this.connectAttempt.get(e)!==r){await o.disconnect().catch(()=>{});return}let a=new Map;if(a.set(i,o),this.drivers.set(e,a),Y[s.type].supportsMultiDatabase&&"activeDatabases"in s&&s.activeDatabases){let c=s,u=(c.activeDatabases??[]).filter((l)=>l!==c.database).map((l)=>this.connectDatabase(e,c,l));await Promise.allSettled(u)}await this.setConnectionState(e,"connected"),this.startHealthCheck(e)}catch(s){if(this.connectAttempt.get(e)!==r)return;await this.closeTunnel(e);let i=s instanceof Error?s.message:"Unknown connection error",o=s instanceof b?s.code:void 0;throw await this.setConnectionState(e,"error",i,o),s}}async disconnect(e){this.connectAttempt.set(e,(this.connectAttempt.get(e)??0)+1),this.cancelAutoReconnect(e),this.stopHealthCheck(e),await this.gracefulDisconnect(e),await this.closeTunnel(e),this.passwords.delete(e),await this.setConnectionState(e,"disconnected")}async reconnect(e){if(this.cancelAutoReconnect(e),this.stopHealthCheck(e),this.drivers.has(e))await this.gracefulDisconnect(e);await this.connect(e)}getDriver(e,t){let n=this.drivers.get(e);if(!n)throw Error(`No active connection for id: ${e}`);let r=t??this.getDefaultDatabaseName(e),s=n.get(r);if(!s)throw Error(`No active driver for database "${r}" on connection ${e}`);return s}getConnectionState(e){return this.states.get(e)?.state??"disconnected"}listConnectionHandles(){let e=[];for(let[t,n]of this.drivers){let s=this.appDb.getConnectionById(t)?.name??t;for(let[i,o]of n)for(let a of o.listConnectionHandles())e.push({...a,connectionId:t,connectionName:s,database:i,driverType:o.getDriverType()})}return e}async terminateConnectionHandle(e,t,n){await this.getDriver(e,t).terminateConnectionHandle(n)}async listDatabases(e){let t=this.appDb.getConnectionById(e);if(!t||!Y[t.config.type].supportsMultiDatabase)throw Error("listDatabases is only supported for connections with multi-database support");let n=ee(t.config),r=this.getDriver(e,n),s=t.config.type==="postgresql"?Mr:kr,i=await r.execute(s),o=this.drivers.get(e),a=o?[...o.keys()]:[n];return i.rows.map((c)=>({name:c.name,isDefault:c.name===n,isActive:a.includes(c.name)}))}async activateDatabase(e,t){let n=this.appDb.getConnectionById(e);if(!n||!Y[n.config.type].supportsMultiDatabase)throw Error("activateDatabase is only supported for connections with multi-database support");let r=n.config,s=this.drivers.get(e);if(!s)throw Error(`No active connection for id: ${e}`);if(s.has(t))return;let i=this.passwords.get(e)??r.password,o={...r,database:t,password:i};await this.connectDatabase(e,o,t);let a=[...new Set([...r.activeDatabases??[],t])];this.appDb.updateConnection({id:e,name:n.name,config:{...r,activeDatabases:a}})}async deactivateDatabase(e,t){let n=this.appDb.getConnectionById(e);if(!n||!Y[n.config.type].supportsMultiDatabase)throw Error("deactivateDatabase is only supported for connections with multi-database support");let r=n.config;if(t===ee(r))throw Error("Cannot deactivate the default database");let s=this.drivers.get(e);if(s){let o=s.get(t);if(o)try{await o.disconnect()}finally{s.delete(t)}}let i=(r.activeDatabases??[]).filter((o)=>o!==t);this.appDb.updateConnection({id:e,name:n.name,config:{...r,activeDatabases:i.length>0?i:void 0}})}listConnections(){return this.appDb.listConnections().map((t)=>({...t,state:this.getConnectionState(t.id),error:this.states.get(t.id)?.error}))}createConnection(e,t=!1){return Ee(e.config,t),this.appDb.createConnection(e)}updateConnection(e){return Ee(e.config),{...this.appDb.updateConnection(e),state:this.getConnectionState(e.id),error:this.states.get(e.id)?.error}}setConnectionReadOnly(e,t){return{...this.appDb.setConnectionReadOnly(e,t),state:this.getConnectionState(e),error:this.states.get(e)?.error}}async deleteConnection(e){if(this.cancelAutoReconnect(e),this.stopHealthCheck(e),this.drivers.has(e))await this.disconnectAllDrivers(e);await this.closeTunnel(e),this.passwords.delete(e),this.states.delete(e),this.appDb.deleteConnection(e)}async testConnection(e){Ee(e);let t=null,n=e;try{if(e.type==="postgresql"&&e.sshTunnel?.enabled)t=await We(e.sshTunnel,e.host,e.port),n={...e,host:"127.0.0.1",port:t.localPort};let r=Se(n);return await r.connect(n),await r.disconnect(),{success:!0}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown connection error"}}finally{if(t)await t.close()}}async listDatabasesForConfig(e){if(e.type!=="postgresql"&&e.type!=="mysql")throw Error(`Listing databases is not supported for connection type: ${e.type}`);let t=e.type==="postgresql"?"postgres":"information_schema",n=e.database?e:{...e,database:t};Ee(n);let r=null;try{if(n.type==="postgresql"&&n.sshTunnel?.enabled)r=await We(n.sshTunnel,n.host,n.port),n={...n,host:"127.0.0.1",port:r.localPort};let s=Se(n);try{await s.connect(n);let i=n.type==="postgresql"?Mr:kr;return(await s.execute(i)).rows.map((a)=>a.name)}finally{await s.disconnect().catch(()=>{})}}finally{if(r)await r.close().catch(()=>{})}}onStatusChanged(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);if(t>=0)this.listeners.splice(t,1)}}onSessionDead(e){return this.sessionDeadListeners.push(e),()=>{let t=this.sessionDeadListeners.indexOf(e);if(t>=0)this.sessionDeadListeners.splice(t,1)}}async disconnectAll(){for(let t of[...this.reconnectStates.keys()])this.cancelAutoReconnect(t);for(let t of[...this.healthTimers.keys()])this.stopHealthCheck(t);let e=[...new Set([...this.drivers.keys(),...this.tunnels.keys()])];for(let t of e)await this.disconnect(t)}startHealthCheck(e){this.stopHealthCheck(e);let t=setInterval(()=>{this.performHealthCheck(e)},this.opts.healthCheckIntervalMs);this.healthTimers.set(e,t)}stopHealthCheck(e){let t=this.healthTimers.get(e);if(t)clearInterval(t),this.healthTimers.delete(e)}async performHealthCheck(e){if(this.healthCheckRunning.has(e))return;this.healthCheckRunning.add(e);try{let t=this.drivers.get(e);if(!t)return;for(let n of t.values()){try{await Promise.race([n.ping(),new Promise((r,s)=>setTimeout(()=>s(Error("Health check timed out")),this.opts.healthCheckTimeoutMs))])}catch{let r=!1;for(let s of t.values()){if(s.inTransaction()){r=!0;break}for(let i of s.getSessionIds())if(s.inTransaction(i)){r=!0;break}if(r)break}this.stopHealthCheck(e);try{await this.disconnectAllDrivers(e)}catch{}await this.setConnectionState(e,"disconnected","Connection lost"),this.startAutoReconnect(e,r);return}for(let r of n.getSessionIds())try{await n.execute("SELECT 1",void 0,r)}catch{try{await n.releaseSession(r)}catch{}for(let s of this.sessionDeadListeners)try{await s({connectionId:e,sessionId:r})}catch{}}}}finally{this.healthCheckRunning.delete(e)}}startAutoReconnect(e,t=!1){this.cancelAutoReconnect(e);let n={attempt:0,timer:null,cancelled:!1,hadTransaction:t};this.reconnectStates.set(e,n),this.scheduleReconnectAttempt(e,n)}cancelAutoReconnect(e){let t=this.reconnectStates.get(e);if(t){if(t.cancelled=!0,t.timer)clearTimeout(t.timer);this.reconnectStates.delete(e)}}async scheduleReconnectAttempt(e,t){if(t.cancelled)return;if(t.attempt>=this.opts.reconnectMaxAttempts){this.reconnectStates.delete(e),await this.setConnectionState(e,"error",`Reconnect failed after ${this.opts.reconnectMaxAttempts} attempts`);return}let n=Math.min(this.opts.reconnectBaseDelayMs*Math.pow(2,t.attempt),this.opts.reconnectMaxDelayMs);t.timer=setTimeout(()=>{if(t.cancelled)return;this.attemptReconnect(e,t).catch(()=>{})},n)}async attemptReconnect(e,t){if(t.cancelled)return;let n=this.appDb.getConnectionById(e);if(!n){this.cancelAutoReconnect(e);return}t.attempt++,await this.setConnectionState(e,"reconnecting");try{await this.closeTunnel(e);let r=this.passwords.get(e),s=r?{...n.config,password:r}:n.config;s=await this.setupSshTunnel(e,s);let i=ee(s),o=Se(s);if(await o.connect(s),t.cancelled){await o.disconnect(),await this.closeTunnel(e);return}let a=new Map;if(a.set(i,o),this.drivers.set(e,a),Y[s.type].supportsMultiDatabase&&"activeDatabases"in s&&s.activeDatabases){let u=s,l=(u.activeDatabases??[]).filter((d)=>d!==u.database).map((d)=>this.connectDatabase(e,u,d));await Promise.allSettled(l)}let c=t.hadTransaction;this.reconnectStates.delete(e),await this.setConnectionState(e,"connected",void 0,void 0,c),this.startHealthCheck(e)}catch{if(t.cancelled)return;await this.closeTunnel(e),this.scheduleReconnectAttempt(e,t)}}async gracefulDisconnect(e){let t=this.drivers.get(e);if(!t)return;for(let[n,r]of t)try{for(let s of r.getSessionIds()){try{await r.cancel(s)}catch{}if(r.inTransaction(s))try{await r.rollback(s)}catch{}}if(r.inTransaction())try{await r.rollback()}catch{}try{await r.cancel()}catch{}}finally{try{await r.disconnect()}finally{t.delete(n)}}this.drivers.delete(e)}async disconnectAllDrivers(e){let t=this.drivers.get(e);if(!t)return;for(let[n,r]of t)try{await r.disconnect()}finally{t.delete(n)}this.drivers.delete(e)}async connectDatabase(e,t,n){let r=this.drivers.get(e);if(!r)throw Error(`No active connection for id: ${e}`);let s=this.tunnels.get(e),i=s?{host:"127.0.0.1",port:s.localPort}:{},o={...t,...i,database:n},a=Se(o);await a.connect(o),r.set(n,a)}async setupSshTunnel(e,t){if(t.type!=="postgresql"||!t.sshTunnel?.enabled)return t;let n=await We(t.sshTunnel,t.host,t.port);return this.tunnels.set(e,n),{...t,host:"127.0.0.1",port:n.localPort}}async closeTunnel(e){let t=this.tunnels.get(e);if(t)await t.close(),this.tunnels.delete(e)}getActiveDatabases(e){let t=this.drivers.get(e);if(!t)return[];return[...t.keys()]}getDefaultDatabaseName(e){let t=this.appDb.getConnectionById(e);if(!t)throw Error(`Connection not found: ${e}`);return ee(t.config)}async setConnectionState(e,t,n,r,s){this.states.set(e,{state:t,error:n});let i=this.listeners.map((o)=>o({connectionId:e,state:t,error:n,errorCode:r,transactionLost:s||void 0}));await Promise.allSettled(i)}}function Se(e){let t;switch(e.type){case"postgresql":t=new qt;break;case"sqlite":t=new $t;break;case"mysql":t=new Ut;break;default:throw Error(`Unsupported connection type: ${e.type}`)}if(process.env.DEBUG_SQL)t=new kt(t);return t}function Ee(e,t=!1){if(!e?.type)throw Error("Connection config must have a type");let n=Y[e.type];if(!n)throw Error(`Unsupported connection type: ${e.type}`);if(n.hasHost&&B(e)){let r=n.label;if(!e.host)throw Error(`${r} host is required`);if(!e.port)throw Error(`${r} port is required`);if(!e.database)throw Error(`${r} database is required`);if(!e.user)throw Error(`${r} user is required`);if(!t&&(e.password===void 0||e.password===null))throw Error(`${r} password is required`)}else if(e.type==="sqlite"){if(!e.path)throw Error("SQLite path is required")}}var To,kr,Mr="SELECT datname AS name FROM pg_database WHERE datistemplate = false AND datallowconn = true ORDER BY datname",Ao;var Ur=C(()=>{me();q();Or();Ir();xr();Lr();To=["mysql","information_schema","performance_schema","sys"],kr=`SELECT schema_name AS name FROM information_schema.schemata WHERE schema_name NOT IN (${To.map((e)=>`'${e}'`).join(", ")}) ORDER BY schema_name`,Ao={healthCheckIntervalMs:30000,healthCheckTimeoutMs:1e4,reconnectBaseDelayMs:1000,reconnectMaxDelayMs:30000,reconnectMaxAttempts:5}});function vo(e){let t=[],n=/-c\s+([^\s=]+)=([^\s]+)/g,r;while((r=n.exec(e))!==null){let s=r[1],i=r[2].replace(/'/g,"''");t.push(`SET ${s} = '${i}';`)}return t.join(`
348
+ `)}function qr(){let e=process.env.DATABASE_URL;if(!e)return null;let t;try{t=new URL(e)}catch{return console.warn("DATABASE_URL: invalid URL, ignoring"),null}let n=t.protocol.replace(/:$/,"");if(n==="postgresql"||n==="postgres"){let r=t.hostname||"localhost",s=t.port?Number(t.port):5432,i=t.pathname.replace(/^\//,"")||"postgres",o=decodeURIComponent(t.username||"postgres"),a=decodeURIComponent(t.password||""),c=t.searchParams.get("options"),u=process.env.DOTAZ_INIT_SQL?.trim()||(c?vo(c):"")||void 0;return{name:`${r}/${i}`,config:{type:"postgresql",host:r,port:s,database:i,user:o,password:a,initSql:u}}}if(n==="mysql"){let r=t.hostname||"localhost",s=t.port?Number(t.port):3306,i=t.pathname.replace(/^\//,"")||"mysql",o=decodeURIComponent(t.username||"root"),a=decodeURIComponent(t.password||""),c=process.env.DOTAZ_INIT_SQL?.trim()||void 0;return{name:`${r}/${i}`,config:{type:"mysql",host:r,port:s,database:i,user:o,password:a,initSql:c}}}return console.warn(`DATABASE_URL: unsupported scheme "${n}", ignoring`),null}var ae="env-default";function Ht(e,t){if(!t.has(e.id))return e;return{...e,config:Mn(e.config),serverManaged:!0}}function Ve(e,t){return(...n)=>{let r=e(...n);return r instanceof Promise?r.then((s)=>Ht(s,t)):Ht(r,t)}}function Qt(){return Ge}function Fr(e,t){let n=crypto.randomUUID(),r=ge.create(":memory:"),s=new Ft(r),i=new pe(s,void 0,r),o=new yt(t),a=(g,y)=>{if(p.ws)p.ws.send(JSON.stringify({type:"message",channel:g,payload:y}))},{handlers:c,sessionManager:u}=vr(s,i,r,void 0,{encryption:o,emitMessage:a,allowServerFileAccess:!1}),l=new Set,d=qr();if(d){let g=ze.size>0?{...d.config,activeDatabases:[...ze]}:d.config;r.createConnectionWithId(ae,{name:d.name,config:g}),l.add(ae);let y=c["connections.list"];c["connections.list"]=()=>y().map((U)=>Ht(U,l));let S=c["connections.create"];c["connections.create"]=Ve(S,l);let m=c["connections.setReadOnly"];c["connections.setReadOnly"]=Ve(m,l);let w=c["connections.setGroup"];c["connections.setGroup"]=Ve(w,l);let E=c["connections.update"];c["connections.update"]=Ve((R)=>{if(l.has(R.id))throw Error("Server-managed connections cannot be reconfigured");return E(R)},l);let T=c["databases.activate"];c["databases.activate"]=async(R)=>{let U=await T(R);if(R.connectionId===ae)ze.add(R.database);return U};let D=c["databases.deactivate"];c["databases.deactivate"]=async(R)=>{let U=await D(R);if(R.connectionId===ae)ze.delete(R.database);return U}}let f=s.onSessionDead((g)=>{if(u.handleSessionDead(g.sessionId),p.ws)p.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:g.connectionId,sessions:u.listSessions(g.connectionId)}}))}),h=s.onStatusChanged(async(g)=>{if(p.ws)p.ws.send(JSON.stringify({type:"message",channel:"connections.statusChanged",payload:{connectionId:g.connectionId,state:g.state,error:g.error,errorCode:g.errorCode,transactionLost:g.transactionLost}}));if(g.state==="disconnected"||g.state==="error"){if(u.handleConnectionLost(g.connectionId),p.ws)p.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:g.connectionId,sessions:[]}}))}if(g.state==="connected")try{let y=await u.handleConnectionRestored(g.connectionId);if(y.length>0&&p.ws)p.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:g.connectionId,sessions:y}}))}catch(y){console.warn("Session restoration failed:",y instanceof Error?y.message:y)}}),p={id:n,appDb:r,connectionManager:s,queryExecutor:i,handlers:c,sessionManager:u,serverManagedIds:l,unsubscribe:()=>{f(),h()},ws:e,activeStreams:0,disconnectedAt:null,ttlTimer:null};if(Ge.set(n,p),d)s.connect(ae).catch((g)=>{console.warn("DATABASE_URL auto-connect failed:",g?.message??g)});return p}async function be(e){if(Ge.delete(e.id),e.ttlTimer)clearTimeout(e.ttlTimer),e.ttlTimer=null;e.unsubscribe(),e.sessionManager.dispose();for(let t of e.queryExecutor.getRunningQueryIds())await e.queryExecutor.cancelQuery(t);await e.connectionManager.disconnectAll(),e.appDb.close()}async function Hr(e){if(e.ws=null,e.disconnectedAt=Date.now(),e.activeStreams===0)await be(e);else e.ttlTimer=setTimeout(async()=>{if(Ge.has(e.id))await be(e)},Bt)}async function Kt(e){if(e.activeStreams--,e.ws===null&&e.activeStreams===0)await be(e)}function Yt(e,t,n,r,s){let i=crypto.randomUUID();return ce.set(i,{session:e,connectionId:n,database:r,params:s,type:t,createdAt:Date.now()}),i}function jt(e,t){let n=ce.get(e);if(!n)return null;if(n.type!==t)return null;if(Date.now()-n.createdAt>$r)return ce.delete(e),null;return ce.delete(e),n}function Br(){let e=Date.now();for(let[t,n]of ce)if(e-n.createdAt>$r)ce.delete(t)}var Bt=300000,$r=300000,Ge,ze,ce;var Qr=C(()=>{Rr();Ur();wt();Me();bt();me();Ge=new Map,ze=new Set;ce=new Map});import{resolve as Wt}from"path";async function Oo(e,t){let n=jt(t,"export");if(!n)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:r,connectionId:s,database:i,params:o}=n,a=o,c;try{c=r.connectionManager.getDriver(s,i)}catch(p){return new Response(JSON.stringify({error:p?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}r.activeStreams++;let u=Do[a.format]??"application/octet-stream",l=_o[a.format]??"dat",d=`${a.table}.${l}`,f=new AbortController;e.signal.addEventListener("abort",()=>f.abort());let h=new ReadableStream({async start(p){let g={write(y){if(typeof y==="string")p.enqueue(new TextEncoder().encode(y));else p.enqueue(y)},async end(){}};try{let y=await ot(c,a,g,f.signal,(S)=>{if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"export.progress",payload:{rowCount:S}}))});if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"export.complete",payload:{rowCount:y.rowCount}}));p.close()}catch(y){if(f.signal.aborted)try{p.close()}catch{}else p.error(y)}finally{await Kt(r)}}});return new Response(h,{headers:{"Content-Type":u,"Content-Disposition":`attachment; filename="${d}"`}})}async function Io(e,t){let n=jt(t,"import");if(!n)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:r,connectionId:s,database:i,params:o}=n,a=o,c;try{c=r.connectionManager.getDriver(s,i)}catch(l){return new Response(JSON.stringify({error:l?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}if(!e.body)return new Response(JSON.stringify({error:"Request body is required"}),{status:400,headers:{"Content-Type":"application/json"}});r.activeStreams++;let u=new AbortController;e.signal.addEventListener("abort",()=>u.abort());try{let l=await _e(c,e.body,a,u.signal,(d)=>{if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"import.progress",payload:{rowCount:d}}))});return new Response(JSON.stringify({rowCount:l.rowCount}),{headers:{"Content-Type":"application/json"}})}catch(l){return new Response(JSON.stringify({error:l?.message??"Import failed"}),{status:500,headers:{"Content-Type":"application/json"}})}finally{await Kt(r)}}var Ro,zt,Kr,V,Yr,No=60000,Do,_o,xo;var jr=C(()=>{sn();at();lt();Qr();Ro=Number(process.env.DOTAZ_PORT)||6401,zt=process.env.DOTAZ_HOST||"localhost",Kr=process.env.DOTAZ_DIST_DIR||Wt(import.meta.dir,"../../dist");try{V=Xt(zt)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}Yr=process.env.DOTAZ_ENCRYPTION_KEY;if(!Yr)console.error("DOTAZ_ENCRYPTION_KEY is required for web mode"),process.exit(1);setInterval(()=>{Br()},60000);setInterval(async()=>{let e=Date.now();for(let[,t]of Qt())if(t.disconnectedAt!==null&&e-t.disconnectedAt>Bt)await be(t)},No);Do={csv:"text/csv",json:"application/json",sql:"application/sql",markdown:"text/markdown",sql_update:"application/sql",html:"text/html",xml:"application/xml"},_o={csv:"csv",json:"json",sql:"sql",markdown:"md",sql_update:"sql",html:"html",xml:"xml"};xo=Bun.serve({port:Ro,hostname:zt,async fetch(e,t){let n=new URL(e.url);if(!Je(e,V))return new Response("Host not allowed",{status:403});if(n.pathname==="/api/bootstrap"&&e.method==="GET"){let a=J(e,V);if(!a.ok)return X(a,"json");return Response.json({ok:!0})}if(n.pathname==="/rpc"){let a=J(e,V);if(!a.ok)return X(a,"text");if(t.upgrade(e,{data:{}}))return;return new Response("WebSocket upgrade failed",{status:400})}let r=n.pathname.match(/^\/api\/stream\/export\/([a-f0-9-]+)$/);if(r&&e.method==="GET"){let a=J(e,V);if(!a.ok)return X(a,"json");return Oo(e,r[1])}let s=n.pathname.match(/^\/api\/stream\/import\/([a-f0-9-]+)$/);if(s&&e.method==="POST"){let a=J(e,V);if(!a.ok)return X(a,"json");return Io(e,s[1])}if(n.pathname==="/api/menu-action"&&e.method==="POST"){let a=J(e,V);if(!a.ok)return X(a,"json");try{let u=(await e.json())?.action;if(!u)return new Response(JSON.stringify({error:"Missing action"}),{status:400,headers:{"Content-Type":"application/json"}});for(let[,l]of Qt())if(l.ws)l.ws.send(JSON.stringify({type:"message",channel:"menu.action",payload:{action:u}}));return new Response(JSON.stringify({ok:!0}),{headers:{"Content-Type":"application/json"}})}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}}let i=Wt(Kr,n.pathname.slice(1)),o=Bun.file(i);if(await o.exists())return new Response(o);if(i=Wt(Kr,"index.html"),o=Bun.file(i),await o.exists())return new Response(o,{headers:{"Content-Type":"text/html"}});return new Response("Not found",{status:404})},websocket:{open(e){let t=Fr(e,Yr);Object.assign(e.data,t)},async close(e){await Hr(e.data)},async message(e,t){let n=rn(typeof t==="string"?t:new Uint8Array(t));if(!n){e.send(JSON.stringify(tn()));return}let s=await nn(n,(i)=>{if(i==="stream.createExportToken")return({connectionId:o,database:a,...c})=>({token:Yt(e.data,"export",o,a,c)});if(i==="stream.createImportToken")return({connectionId:o,database:a,...c})=>({token:Yt(e.data,"import",o,a,c)});return e.data.handlers[i]});e.send(JSON.stringify(s))}}});console.log(`Dotaz web server running at http://${zt}:${xo.port}`)});var{secrets:Wr}=globalThis.Bun;import{randomBytes as Po}from"crypto";import{resolve as Lo}from"path";function Ze(e){return typeof e==="string"&&e.trim().length>0}function en(e,t){if(Ze(t))return null;if(G(e))return null;return"DOTAZ_ENCRYPTION_KEY is required when binding Dotaz to a non-loopback host. Set it to a stable random value so saved credentials remain decryptable across restarts."}var zr="dev.dotaz.server",Vr="encryption-key",le=process.argv.slice(2),Jr=Number(process.env.DOTAZ_PORT)||6401,Vt=process.env.DOTAZ_HOST||"localhost";for(let e=0;e<le.length;e++){let t=le[e];if((t==="--port"||t==="-p")&&le[e+1])Jr=Number(le[e+1]),e++;else if((t==="--host"||t==="-H")&&le[e+1])Vt=le[e+1],e++;else if(t==="--help")console.log(`Usage: dotaz [options]
337
349
 
338
350
  Options:
339
351
  -p, --port <port> Port to listen on (default: 6401)
340
352
  -H, --host <host> Host to bind to (default: localhost)
341
353
  --help Show this help message
342
- `),process.exit(0)}var br=Ht(Mt,process.env.DOTAZ_ENCRYPTION_KEY);if(br)console.error(br),process.exit(1);if(!je(process.env.DOTAZ_ENCRYPTION_KEY)){let e=await Sr.get({service:wr,name:Er});if(!e){e=Si(32).toString("hex");try{await Sr.set({service:wr,name:Er,value:e})}catch{}}process.env.DOTAZ_ENCRYPTION_KEY=e}process.env.DOTAZ_PORT=String(Cr);process.env.DOTAZ_HOST=Mt;process.env.DOTAZ_DIST_DIR=wi(import.meta.dir,"../dist");await Promise.resolve().then(() => (yr(),{}));
354
+ `),process.exit(0)}var Gr=en(Vt,process.env.DOTAZ_ENCRYPTION_KEY);if(Gr)console.error(Gr),process.exit(1);if(!Ze(process.env.DOTAZ_ENCRYPTION_KEY)){let e=await Wr.get({service:zr,name:Vr});if(!e){e=Po(32).toString("hex");try{await Wr.set({service:zr,name:Vr,value:e})}catch{}}process.env.DOTAZ_ENCRYPTION_KEY=e}process.env.DOTAZ_PORT=String(Jr);process.env.DOTAZ_HOST=Vt;process.env.DOTAZ_DIST_DIR=Lo(import.meta.dir,"../dist");await Promise.resolve().then(() => (jr(),{}));