#!/usr/bin/env node
import{a as x,b as w}from"./chunk-OOJCYVYF.js";import{c as b}from"./chunk-MO4RPBN2.js";import{b as j}from"./chunk-YU6OGPZR.js";import{a as m}from"./chunk-SYG3IW7P.js";import{a as q,b as C}from"./chunk-GTNBSMZR.js";import{randomBytes as _}from"node:crypto";import{existsSync as E}from"node:fs";import{dirname as z,join as T}from"node:path";import{fileURLToPath as X}from"node:url";import{Worker as Y}from"node:worker_threads";import G from"sql.js";function V(e,t,r){switch(r.mode){case"list":return B(e,t,r);case"csv":return O(e,t,r);case"json":return I(e,t);case"line":return N(e,t,r);case"column":return R(e,t,r);case"table":return F(e,t,r);case"markdown":return Q(e,t,r);case"tabs":return U(e,t,r);case"box":return W(e,t,r);case"quote":return D(e,t,r);case"html":return H(e,t,r);case"ascii":return J(e,t,r)}}function f(e,t){return e==null?t: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 B(e,t,r){let n=[];r.header&&e.length>0&&n.push(e.join(r.separator));for(let a of t)n.push(a.map(o=>f(o,r.nullValue)).join(r.separator));return n.length>0?`${n.join(r.newline)}${r.newline}`:""}function O(e,t,r){let n=[];r.header&&e.length>0&&n.push(e.map(L).join(","));for(let a of t)n.push(a.map(o=>L(f(o,r.nullValue))).join(","));return n.length>0?`${n.join(`
`)}
`:""}function L(e){return e.includes(",")||e.includes('"')||e.includes("'")||e.includes(`
`)?`"${e.replace(/"/g,'""')}"`:e}function A(e){return e.toPrecision(17).replace(/\.?0+$/,"")}function P(e){return e===null?"null":typeof e=="number"?Number.isInteger(e)?String(e):A(e):JSON.stringify(e)}function I(e,t){return t.length===0?"":`[${t.map(n=>`{${e.map((o,i)=>`${JSON.stringify(o)}:${P(n[i])}`).join(",")}}`).join(`,
`)}]
`}function N(e,t,r){if(e.length===0||t.length===0)return"";let n=Math.max(5,...e.map(o=>o.length)),a=[];for(let o of t)for(let i=0;i<e.length;i++){let s=e[i].padStart(n);a.push(`${s} = ${f(o[i],r.nullValue)}`)}return`${a.join(`
`)}
`}function R(e,t,r){if(e.length===0)return"";let n=e.map(o=>o.length);for(let o of t)for(let i=0;i<o.length;i++){let s=f(o[i],r.nullValue).length;s>n[i]&&(n[i]=s)}let a=[];r.header&&(a.push(e.map((o,i)=>o.padEnd(n[i])).join("  ")),a.push(n.map(o=>"-".repeat(o)).join("  ")));for(let o of t)a.push(o.map((i,s)=>f(i,r.nullValue).padEnd(n[s])).join("  "));return a.length>0?`${a.join(`
`)}
`:""}function F(e,t,r){if(e.length===0)return"";let n=e.map(i=>i.length);for(let i of t)for(let s=0;s<i.length;s++){let p=f(i[s],r.nullValue).length;p>n[s]&&(n[s]=p)}let a=[],o=`+${n.map(i=>"-".repeat(i+2)).join("+")}+`;a.push(o),r.header&&(a.push(`| ${e.map((i,s)=>i.padEnd(n[s])).join(" | ")} |`),a.push(o));for(let i of t)a.push(`| ${i.map((s,p)=>f(s,r.nullValue).padEnd(n[p])).join(" | ")} |`);return a.push(o),`${a.join(`
`)}
`}function Q(e,t,r){if(e.length===0)return"";let n=[];r.header&&(n.push(`| ${e.join(" | ")} |`),n.push(`|${e.map(()=>"---").join("|")}|`));for(let a of t)n.push(`| ${a.map(o=>f(o,r.nullValue)).join(" | ")} |`);return n.length>0?`${n.join(`
`)}
`:""}function U(e,t,r){let n=[];r.header&&e.length>0&&n.push(e.join("	"));for(let a of t)n.push(a.map(o=>f(o,r.nullValue)).join("	"));return n.length>0?`${n.join(r.newline)}${r.newline}`:""}function W(e,t,r){if(e.length===0)return"";let n=e.map(o=>o.length);for(let o of t)for(let i=0;i<o.length;i++){let s=f(o[i],r.nullValue).length;s>n[i]&&(n[i]=s)}let a=[];a.push(`\u250C${n.map(o=>"\u2500".repeat(o+2)).join("\u252C")}\u2510`),a.push(`\u2502 ${e.map((o,i)=>o.padEnd(n[i])).join(" \u2502 ")} \u2502`),a.push(`\u251C${n.map(o=>"\u2500".repeat(o+2)).join("\u253C")}\u2524`);for(let o of t)a.push(`\u2502 ${o.map((i,s)=>f(i,r.nullValue).padEnd(n[s])).join(" \u2502 ")} \u2502`);return a.push(`\u2514${n.map(o=>"\u2500".repeat(o+2)).join("\u2534")}\u2518`),`${a.join(`
`)}
`}function D(e,t,r){let n=[];r.header&&e.length>0&&n.push(e.map(a=>`'${a}'`).join(","));for(let a of t)n.push(a.map(o=>o==null?"NULL":typeof o=="number"?Number.isInteger(o)?String(o):A(o):`'${String(o)}'`).join(","));return n.length>0?`${n.join(r.newline)}${r.newline}`:""}function H(e,t,r){let n=[];r.header&&e.length>0&&(n.push(`<TR>${e.map(a=>`<TH>${M(a)}</TH>`).join("")}`),n.push("</TR>"));for(let a of t)n.push(`<TR>${a.map(o=>`<TD>${M(f(o,r.nullValue))}</TD>`).join("")}`),n.push("</TR>");return n.length>0?`${n.join(`
`)}
`:""}function M(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function J(e,t,r){let o=[];r.header&&e.length>0&&o.push(e.join(""));for(let i of t)o.push(i.map(s=>f(s,r.nullValue)).join(""));return o.length>0?o.join("")+"":""}var K=5e3,Z={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 v(e){let t={mode:"list",header:!1,separator:"|",newline:`
`,nullValue:"",readonly:!1,bail:!1,echo:!1,cmd:null},r=null,n=null,a=!1,o=!1;for(let i=0;i<e.length;i++){let s=e[i];if(o){r===null?r=s:n===null&&(n=s);continue}if(s==="--")o=!0;else if(s==="-version")a=!0;else if(s==="-list")t.mode="list";else if(s==="-csv")t.mode="csv";else if(s==="-json")t.mode="json";else if(s==="-line")t.mode="line";else if(s==="-column")t.mode="column";else if(s==="-table")t.mode="table";else if(s==="-markdown")t.mode="markdown";else if(s==="-tabs")t.mode="tabs";else if(s==="-box")t.mode="box";else if(s==="-quote")t.mode="quote";else if(s==="-html")t.mode="html";else if(s==="-ascii")t.mode="ascii";else if(s==="-header")t.header=!0;else if(s==="-noheader")t.header=!1;else if(s==="-readonly")t.readonly=!0;else if(s==="-bail")t.bail=!0;else if(s==="-echo")t.echo=!0;else if(s==="-separator"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -separator
`,exitCode:1};t.separator=e[++i]}else if(s==="-newline"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -newline
`,exitCode:1};t.newline=e[++i]}else if(s==="-nullvalue"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -nullvalue
`,exitCode:1};t.nullValue=e[++i]}else if(s==="-cmd"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -cmd
`,exitCode:1};t.cmd=e[++i]}else{if(s.startsWith("-"))return{stdout:"",stderr:`sqlite3: Error: unknown option: ${s.startsWith("--")?s.slice(1):s}
Use -help for a list of options.
`,exitCode:1};r===null?r=s:n===null&&(n=s)}}return{options:t,database:r,sql:n,showVersion:a}}async function ee(){let e=await j.runTrustedAsync(()=>G()),t=new e.Database;try{let r=t.exec("SELECT sqlite_version()");return r.length>0&&r[0].values.length>0?String(r[0].values[0][0]):"unknown"}finally{t.close()}}function re(){let e=z(X(import.meta.url)),t=T(e,"../../commands/sqlite3/worker.js");if(E(t))return t;let r=T(e,"worker.js");if(E(r))return r;let n=T(e,"../../../dist/commands/sqlite3/worker.js");if(E(n))return n;throw new Error("sqlite3 worker not found. Run 'pnpm build' to compile the worker.")}var te={createWorker(e,t){return new Y(e,{workerData:t})}};function ne(){return _(16).toString("hex")}function oe(e,t){if(!e||typeof e!="object")return{success:!1,error:"Malformed worker response"};let r=e;return typeof r.protocolToken!="string"||r.protocolToken!==t?{success:!1,error:"Malformed worker response: invalid protocol token"}:r.type==="security-violation"?{success:!1,error:`Security violation: ${typeof r.violation?.type=="string"?r.violation.type:"unknown"}`}:typeof r.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:r.success?Array.isArray(r.results)?typeof r.hasModifications!="boolean"?{success:!1,error:"Malformed worker response: missing hasModifications flag"}:r.dbBuffer!==null&&r.dbBuffer!==void 0&&!(r.dbBuffer instanceof Uint8Array)?{success:!1,error:"Malformed worker response: invalid dbBuffer"}:{success:!0,results:r.results,hasModifications:r.hasModifications,dbBuffer:r.dbBuffer===void 0?null:r.dbBuffer,defenseStats:r.defenseStats}:{success:!1,error:"Malformed worker response: missing results array"}:{success:!1,error:typeof r.error=="string"&&r.error.length>0?r.error:"Worker execution failed"}}async function se(e,t,r){try{let n=re();return await new Promise((a,o)=>{let i=j.runTrusted(()=>te.createWorker(n,e)),s=b(r,"sqlite3","worker timeout callback",()=>{i.terminate(),a({success:!1,error:`Query timeout: execution exceeded ${t}ms limit`})}),c=x(()=>{try{s()}catch(u){let l=u instanceof Error?u.message:String(u);a({success:!1,error:m(l)})}},t),S=b(r,"sqlite3","worker message callback",u=>{w(c),a(oe(u,e.protocolToken))}),$=b(r,"sqlite3","worker error callback",u=>{w(c),o(u)}),y=b(r,"sqlite3","worker exit callback",u=>{w(c),u!==0&&a({success:!1,error:`Worker exited with code ${u}`})}),h=u=>{try{S(u)}catch(l){w(c);let d=l instanceof Error?l.message:String(l);a({success:!1,error:m(d)})}},k=u=>{try{$(u)}catch(l){w(c);let d=l instanceof Error?l.message:String(l);o(new Error(m(d)))}},g=u=>{try{y(u)}catch(l){w(c);let d=l instanceof Error?l.message:String(l);a({success:!1,error:m(d)})}};i.on("message",h),i.on("error",k),i.on("exit",g)})}catch(n){let a=m(n.message);throw new Error(`sqlite3 worker failed to load: ${a}`)}}var Se={name:"sqlite3",async execute(e,t){if(C(e)||e.includes("-help"))return q(Z);let r=v(e);if("exitCode"in r)return r;let{options:n,database:a,sql:o,showVersion:i}=r;if(i)return{stdout:`${await ee()}
`,stderr:"",exitCode:0};if(!a)return{stdout:"",stderr:`sqlite3: missing database argument
`,exitCode:1};let s=o||t.stdin.trim();if(n.cmd&&(s=n.cmd+(s?`; ${s}`:"")),!s)return{stdout:"",stderr:`sqlite3: no SQL provided
`,exitCode:1};let p=a===":memory:",c="",S=null;try{p||(c=t.fs.resolvePath(t.cwd,a),await t.fs.exists(c)&&(S=await t.fs.readFileBuffer(c)))}catch(l){let d=m(l.message);return{stdout:"",stderr:`sqlite3: unable to open database "${a}": ${d}
`,exitCode:1}}let $=t.limits?.maxSqliteTimeoutMs??K,y={protocolToken:ne(),dbBuffer:S,sql:s,options:{bail:n.bail,echo:n.echo}},h;try{h=await se(y,$,t.requireDefenseContext)}catch(l){return{stdout:"",stderr:`sqlite3: worker error: ${m(l.message)}
`,exitCode:1}}if(!h.success)return{stdout:"",stderr:`sqlite3: ${m(h.error)}
`,exitCode:1};let k={mode:n.mode,header:n.header,separator:n.separator,newline:n.newline,nullValue:n.nullValue},g="";n.echo&&(g+=`${s}
`);let u=!1;for(let l of h.results)if(l.type==="error"){if(n.bail)return{stdout:g,stderr:`Error: ${l.error}
`,exitCode:1};g+=`Error: ${l.error}
`,u=!0}else l.columns&&l.rows&&(l.rows.length>0||n.header)&&(g+=V(l.columns,l.rows,k));if(h.hasModifications&&!n.readonly&&!p&&c&&h.dbBuffer)try{await t.fs.writeFile(c,h.dbBuffer)}catch(l){let d=m(l.message);return{stdout:g,stderr:`sqlite3: failed to write database: ${d}
`,exitCode:1}}return{stdout:g,stderr:"",exitCode:u&&n.bail?1:0}}},$e={name:"sqlite3",flags:[],needsArgs:!0};export{te as a,Se as b,$e as c};
