#!/usr/bin/env node
import{a as b,b as $}from"./chunk-GTNBSMZR.js";import{existsSync as h}from"node:fs";import{dirname as B,join as p}from"node:path";import{fileURLToPath as U}from"node:url";import{Worker as D}from"node:worker_threads";import H from"sql.js";function q(e,r,n){switch(n.mode){case"list":return y(e,r,n);case"csv":return L(e,r,n);case"json":return V(e,r);case"line":return O(e,r,n);case"column":return A(e,r,n);case"table":return N(e,r,n);case"markdown":return P(e,r,n);case"tabs":return I(e,r,n);case"box":return M(e,r,n);case"quote":return R(e,r,n);case"html":return F(e,r,n);case"ascii":return Q(e,r,n)}}function u(e,r){return e==null?r:e instanceof Uint8Array||Buffer.isBuffer(e)?Buffer.from(e).toString("utf8"):typeof e=="number"&&!Number.isInteger(e)?e.toPrecision(17).replace(/\.?0+$/,""):String(e)}function y(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.join(n.separator));for(let l of r)t.push(l.map(i=>u(i,n.nullValue)).join(n.separator));return t.length>0?`${t.join(n.newline)}${n.newline}`:""}function L(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.map(j).join(","));for(let l of r)t.push(l.map(i=>j(u(i,n.nullValue))).join(","));return t.length>0?`${t.join(`
`)}
`:""}function j(e){return e.includes(",")||e.includes('"')||e.includes("'")||e.includes(`
`)?`"${e.replace(/"/g,'""')}"`:e}function E(e){return e.toPrecision(17).replace(/\.?0+$/,"")}function k(e){return e===null?"null":typeof e=="number"?Number.isInteger(e)?String(e):E(e):JSON.stringify(e)}function V(e,r){return r.length===0?"":`[${r.map(t=>`{${e.map((i,s)=>`${JSON.stringify(i)}:${k(t[s])}`).join(",")}}`).join(`,
`)}]
`}function O(e,r,n){if(e.length===0||r.length===0)return"";let t=Math.max(5,...e.map(i=>i.length)),l=[];for(let i of r)for(let s=0;s<e.length;s++){let o=e[s].padStart(t);l.push(`${o} = ${u(i[s],n.nullValue)}`)}return`${l.join(`
`)}
`}function A(e,r,n){if(e.length===0)return"";let t=e.map(i=>i.length);for(let i of r)for(let s=0;s<i.length;s++){let o=u(i[s],n.nullValue).length;o>t[s]&&(t[s]=o)}let l=[];n.header&&(l.push(e.map((i,s)=>i.padEnd(t[s])).join("  ")),l.push(t.map(i=>"-".repeat(i)).join("  ")));for(let i of r)l.push(i.map((s,o)=>u(s,n.nullValue).padEnd(t[o])).join("  "));return l.length>0?`${l.join(`
`)}
`:""}function N(e,r,n){if(e.length===0)return"";let t=e.map(s=>s.length);for(let s of r)for(let o=0;o<s.length;o++){let f=u(s[o],n.nullValue).length;f>t[o]&&(t[o]=f)}let l=[],i=`+${t.map(s=>"-".repeat(s+2)).join("+")}+`;l.push(i),n.header&&(l.push(`| ${e.map((s,o)=>s.padEnd(t[o])).join(" | ")} |`),l.push(i));for(let s of r)l.push(`| ${s.map((o,f)=>u(o,n.nullValue).padEnd(t[f])).join(" | ")} |`);return l.push(i),`${l.join(`
`)}
`}function P(e,r,n){if(e.length===0)return"";let t=[];n.header&&(t.push(`| ${e.join(" | ")} |`),t.push(`|${e.map(()=>"---").join("|")}|`));for(let l of r)t.push(`| ${l.map(i=>u(i,n.nullValue)).join(" | ")} |`);return t.length>0?`${t.join(`
`)}
`:""}function I(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.join("	"));for(let l of r)t.push(l.map(i=>u(i,n.nullValue)).join("	"));return t.length>0?`${t.join(n.newline)}${n.newline}`:""}function M(e,r,n){if(e.length===0)return"";let t=e.map(i=>i.length);for(let i of r)for(let s=0;s<i.length;s++){let o=u(i[s],n.nullValue).length;o>t[s]&&(t[s]=o)}let l=[];l.push(`\u250C${t.map(i=>"\u2500".repeat(i+2)).join("\u252C")}\u2510`),l.push(`\u2502 ${e.map((i,s)=>i.padEnd(t[s])).join(" \u2502 ")} \u2502`),l.push(`\u251C${t.map(i=>"\u2500".repeat(i+2)).join("\u253C")}\u2524`);for(let i of r)l.push(`\u2502 ${i.map((s,o)=>u(s,n.nullValue).padEnd(t[o])).join(" \u2502 ")} \u2502`);return l.push(`\u2514${t.map(i=>"\u2500".repeat(i+2)).join("\u2534")}\u2518`),`${l.join(`
`)}
`}function R(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.map(l=>`'${l}'`).join(","));for(let l of r)t.push(l.map(i=>i==null?"NULL":typeof i=="number"?Number.isInteger(i)?String(i):E(i):`'${String(i)}'`).join(","));return t.length>0?`${t.join(n.newline)}${n.newline}`:""}function F(e,r,n){let t=[];n.header&&e.length>0&&(t.push(`<TR>${e.map(l=>`<TH>${S(l)}</TH>`).join("")}`),t.push("</TR>"));for(let l of r)t.push(`<TR>${l.map(i=>`<TD>${S(u(i,n.nullValue))}</TD>`).join("")}`),t.push("</TR>");return t.length>0?`${t.join(`
`)}
`:""}function S(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Q(e,r,n){let i=[];n.header&&e.length>0&&i.push(e.join(""));for(let s of r)i.push(s.map(o=>u(o,n.nullValue)).join(""));return i.length>0?i.join("")+"":""}var J=5e3,W={name:"sqlite3",summary:"SQLite database CLI",usage:"sqlite3 [OPTIONS] DATABASE [SQL]",options:["-list           output in list mode (default)","-csv            output in CSV mode","-json           output in JSON mode","-line           output in line mode","-column         output in column mode","-table          output as ASCII table","-markdown       output as markdown table","-tabs           output in tab-separated mode","-box            output in Unicode box mode","-quote          output in SQL quote mode","-html           output as HTML table","-ascii          output in ASCII mode (control chars)","-header         show column headers","-noheader       hide column headers","-separator SEP  field separator for list mode (default: |)","-newline SEP    row separator (default: \\n)","-nullvalue TEXT text for NULL values (default: empty)","-readonly       open database read-only (no writeback)","-bail           stop on first error","-echo           print SQL before execution","-cmd COMMAND    run SQL command before main SQL","-version        show SQLite version","--              end of options","--help          show this help"],examples:['sqlite3 :memory: "CREATE TABLE t(x); INSERT INTO t VALUES(1); SELECT * FROM t"','sqlite3 -json data.db "SELECT * FROM users"','sqlite3 -csv -header data.db "SELECT id, name FROM products"','sqlite3 -box data.db "SELECT * FROM users"']};function _(e){let r={mode:"list",header:!1,separator:"|",newline:`
`,nullValue:"",readonly:!1,bail:!1,echo:!1,cmd:null},n=null,t=null,l=!1,i=!1;for(let s=0;s<e.length;s++){let o=e[s];if(i){n===null?n=o:t===null&&(t=o);continue}if(o==="--")i=!0;else if(o==="-version")l=!0;else if(o==="-list")r.mode="list";else if(o==="-csv")r.mode="csv";else if(o==="-json")r.mode="json";else if(o==="-line")r.mode="line";else if(o==="-column")r.mode="column";else if(o==="-table")r.mode="table";else if(o==="-markdown")r.mode="markdown";else if(o==="-tabs")r.mode="tabs";else if(o==="-box")r.mode="box";else if(o==="-quote")r.mode="quote";else if(o==="-html")r.mode="html";else if(o==="-ascii")r.mode="ascii";else if(o==="-header")r.header=!0;else if(o==="-noheader")r.header=!1;else if(o==="-readonly")r.readonly=!0;else if(o==="-bail")r.bail=!0;else if(o==="-echo")r.echo=!0;else if(o==="-separator"){if(s+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -separator
`,exitCode:1};r.separator=e[++s]}else if(o==="-newline"){if(s+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -newline
`,exitCode:1};r.newline=e[++s]}else if(o==="-nullvalue"){if(s+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -nullvalue
`,exitCode:1};r.nullValue=e[++s]}else if(o==="-cmd"){if(s+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -cmd
`,exitCode:1};r.cmd=e[++s]}else{if(o.startsWith("-"))return{stdout:"",stderr:`sqlite3: Error: unknown option: ${o.startsWith("--")?o.slice(1):o}
Use -help for a list of options.
`,exitCode:1};n===null?n=o:t===null&&(t=o)}}return{options:r,database:n,sql:t,showVersion:l}}async function z(){let e=await H(),r=new e.Database;try{let n=r.exec("SELECT sqlite_version()");return n.length>0&&n[0].values.length>0?String(n[0].values[0][0]):"unknown"}finally{r.close()}}function X(){let e=B(U(import.meta.url)),r=p(e,"../../commands/sqlite3/worker.js");if(h(r))return r;let n=p(e,"worker.js");if(h(n))return n;let t=p(e,"../../../dist/commands/sqlite3/worker.js");if(h(t))return t;throw new Error("sqlite3 worker not found. Run 'pnpm build' to compile the worker.")}async function Y(e,r){try{let n=X();return await new Promise((t,l)=>{let i=new D(n,{workerData:e}),s=setTimeout(()=>{i.terminate(),t({success:!1,error:`Query timeout: execution exceeded ${r}ms limit`})},r);i.on("message",o=>{clearTimeout(s),t(o)}),i.on("error",o=>{clearTimeout(s),l(o)}),i.on("exit",o=>{clearTimeout(s),o!==0&&t({success:!1,error:`Worker exited with code ${o}`})})})}catch(n){throw new Error(`sqlite3 worker failed to load: ${n.message}`)}}var oe={name:"sqlite3",async execute(e,r){if($(e)||e.includes("-help"))return b(W);let n=_(e);if("exitCode"in n)return n;let{options:t,database:l,sql:i,showVersion:s}=n;if(s)return{stdout:`${await z()}
`,stderr:"",exitCode:0};if(!l)return{stdout:"",stderr:`sqlite3: missing database argument
`,exitCode:1};let o=i||r.stdin.trim();if(t.cmd&&(o=t.cmd+(o?`; ${o}`:"")),!o)return{stdout:"",stderr:`sqlite3: no SQL provided
`,exitCode:1};let f=l===":memory:",m="",g=null;try{f||(m=r.fs.resolvePath(r.cwd,l),await r.fs.exists(m)&&(g=await r.fs.readFileBuffer(m)))}catch(a){return{stdout:"",stderr:`sqlite3: unable to open database "${l}": ${a.message}
`,exitCode:1}}let x=r.limits?.maxSqliteTimeoutMs??J,T={dbBuffer:g,sql:o,options:{bail:t.bail,echo:t.echo}},d;try{d=await Y(T,x)}catch(a){return{stdout:"",stderr:`sqlite3: worker error: ${a.message}
`,exitCode:1}}if(!d.success)return{stdout:"",stderr:`sqlite3: ${d.error}
`,exitCode:1};let C={mode:t.mode,header:t.header,separator:t.separator,newline:t.newline,nullValue:t.nullValue},c="";t.echo&&(c+=`${o}
`);let w=!1;for(let a of d.results)if(a.type==="error"){if(t.bail)return{stdout:c,stderr:`Error: ${a.error}
`,exitCode:1};c+=`Error: ${a.error}
`,w=!0}else a.columns&&a.rows&&(a.rows.length>0||t.header)&&(c+=q(a.columns,a.rows,C));if(d.hasModifications&&!t.readonly&&!f&&m&&d.dbBuffer)try{await r.fs.writeFile(m,d.dbBuffer)}catch(a){return{stdout:c,stderr:`sqlite3: failed to write database: ${a.message}
`,exitCode:1}}return{stdout:c,stderr:"",exitCode:w&&t.bail?1:0}}},ie={name:"sqlite3",flags:[],needsArgs:!0};export{oe as a,ie as b};
