bun-query-builder 0.3.9 → 0.3.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/cli.js CHANGED
@@ -1,35 +1,35 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import"../chunk-3hwsz4q7.js";import"../chunk-93ny6tvm.js";import"../chunk-ygwkzhkh.js";import"../chunk-dj2eazhq.js";import"../chunk-9wck98bv.js";import{Z,ee,te,ne,I,re,ie,se,ae,L,oe,K,F,le,ce,j,ue,de,C,fe,w,R,A,ye,be,q,Te,W,we,U,V,M,H,Se,De,Ee,$e,Q,xe,ve}from"../chunk-284e3ka8.js";import{EventEmitter as Le}from"events";import v from"process";import Oe from"process";import X from"process";import D from"process";import E from"process";import qe from"tty";import kt,{stdin as Gt,stdout as Ht}from"process";import{existsSync as Bt}from"fs";import G from"fs/promises";import Me from"os";import Y from"path";import S from"process";function J(e){return e.replace(/[<[].+/,"").trim()}function Ne(e){let t=/<([^>]+)>/g,i=/\[([^\]]+)\]/g,s=[],n=(d)=>{let a=!1,r=d[1];if(r.startsWith("..."))r=r.slice(3),a=!0;else if(r.endsWith("..."))r=r.slice(0,-3),a=!0;return{required:d[0].startsWith("<"),value:r.trim(),variadic:a}},o;while(o=t.exec(e))s.push(n(o));let m;while(m=i.exec(e))s.push(n(m));return s}function Pe(e){let t={alias:{},boolean:[]};for(let[i,s]of e.entries()){if(s.names.length>1)t.alias[s.names[0]]=s.names.slice(1);if(s.isBoolean)if(s.negated){if(!e.some((o,m)=>m!==i&&o.names.some((d)=>s.names.includes(d))&&typeof o.required==="boolean"))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t}function Ie(e){return e.reduce((t,i)=>t.length>=i.length?t:i,"")}function z(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function N(e){return e.replace(/([a-z])-([a-z])/g,(t,i,s)=>i+s.toUpperCase())}function We(e,t,i){let s=0,n=t.length,o=e,m;for(;s<n;++s)m=o[t[s]],o=o[t[s]]=s===n-1?i:m!=null?m:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]}function Fe(e,t){for(let i of Object.keys(t)){let s=t[i];if(e[i]===void 0)continue;if(s.shouldTransform){if(e[i]=Array.prototype.concat.call([],e[i]),typeof s.transformFunction==="function")e[i]=e[i].map(s.transformFunction)}}}function ze(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function _(e){return e.split(".").map((t,i)=>i===0?N(t):t).join(".")}class B extends Error{exitCode=2;isUsageError=!0;usage;constructor(e,t){super(e);if(this.name=this.constructor.name,t!==void 0)this.usage=t;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
3
+ import"../chunk-96qkj2sc.js";import"../chunk-wvae8521.js";import"../chunk-6jbg1hjx.js";import"../chunk-w47tdxa6.js";import"../chunk-6s2dqhn3.js";import{te,ne,re,ie,K,se,ae,oe,le,F,ce,j,q,ue,de,W,fe,me,R,he,S,A,N,Te,we,U,Se,V,De,H,Q,M,G,Ee,$e,xe,ve,J,ke,Ce}from"../chunk-9trv54hy.js";import{EventEmitter as Le}from"events";import v from"process";import ye from"process";import X from"process";import T from"process";import I from"process";import qe from"tty";import kt,{stdin as Gt,stdout as Ht}from"process";import{existsSync as Bt}from"fs";import P from"fs/promises";import Me from"os";import z from"path";import x from"process";function Y(e){return e.replace(/[<[].+/,"").trim()}function Ne(e){let t=/<([^>]+)>/g,i=/\[([^\]]+)\]/g,s=[],n=(d)=>{let a=!1,r=d[1];if(r.startsWith("..."))r=r.slice(3),a=!0;else if(r.endsWith("..."))r=r.slice(0,-3),a=!0;return{required:d[0].startsWith("<"),value:r.trim(),variadic:a}},o;while(o=t.exec(e))s.push(n(o));let m;while(m=i.exec(e))s.push(n(m));return s}function Pe(e){let t={alias:{},boolean:[]};for(let[i,s]of e.entries()){if(s.names.length>1)t.alias[s.names[0]]=s.names.slice(1);if(s.isBoolean)if(s.negated){if(!e.some((o,m)=>m!==i&&o.names.some((d)=>s.names.includes(d))&&typeof o.required==="boolean"))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t}function Oe(e){return e.reduce((t,i)=>t.length>=i.length?t:i,"")}function D(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function B(e){return e.replace(/([a-z])-([a-z])/g,(t,i,s)=>i+s.toUpperCase())}function We(e,t,i){let s=0,n=t.length,o=e,m;for(;s<n;++s)m=o[t[s]],o=o[t[s]]=s===n-1?i:m!=null?m:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]}function Fe(e,t){for(let i of Object.keys(t)){let s=t[i];if(e[i]===void 0)continue;if(s.shouldTransform){if(e[i]=Array.prototype.concat.call([],e[i]),typeof s.transformFunction==="function")e[i]=e[i].map(s.transformFunction)}}}function ze(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function k(e){return e.split(".").map((t,i)=>i===0?B(t):t).join(".")}class E extends Error{exitCode=2;isUsageError=!0;usage;constructor(e,t){super(e);if(this.name=this.constructor.name,t!==void 0)this.usage=t;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
4
4
 
5
5
  Stack trace:
6
- ${this.stack}`;return this.message}}function Ue(e){if(e instanceof B)return!0;return!!e&&typeof e==="object"&&e.name==="ClappError"&&typeof e.message==="string"}function Ge(){let{env:e}=Oe,{TERM:t,TERM_PROGRAM:i}=e;if(Oe.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||i==="Terminus-Sublime"||i==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var P="\x1B",b=`${P}[`;var ke={to(e,t){if(!t)return`${b}${e+1}G`;return`${b}${t+1};${e+1}H`},move(e,t){let i="";if(e<0)i+=`${b}${-e}D`;else if(e>0)i+=`${b}${e}C`;if(t<0)i+=`${b}${-t}A`;else if(t>0)i+=`${b}${t}B`;return i},up:(e=1)=>`${b}${e}A`,down:(e=1)=>`${b}${e}B`,forward:(e=1)=>`${b}${e}C`,backward:(e=1)=>`${b}${e}D`,nextLine:(e=1)=>`${b}E`.repeat(e),prevLine:(e=1)=>`${b}F`.repeat(e),left:`${b}G`,hide:`${b}?25l`,show:`${b}?25h`,save:`${P}7`,restore:`${P}8`};var Vt={screen:`${b}2J`,up:(e=1)=>`${b}1J`.repeat(e),down:(e=1)=>`${b}J`.repeat(e),line:`${b}2K`,lineEnd:`${b}K`,lineStart:`${b}1K`,lines(e){let t="";for(let i=0;i<e;i++)t+=this.line+(i<e-1?ke.up():"");if(e)t+=ke.left;return t}},Lt={screen:`${P}c`};function He(e,t){let i=[];for(let s=0;s<=t.length;s++)i[s]=[s];for(let s=0;s<=e.length;s++)i[0][s]=s;for(let s=1;s<=t.length;s++)for(let n=1;n<=e.length;n++)if(t.charAt(s-1)===e.charAt(n-1))i[s][n]=i[s-1][n-1];else i[s][n]=Math.min(i[s-1][n-1]+1,i[s][n-1]+1,i[s-1][n]+1);return i[t.length][e.length]}function Be(e,t,i=2,s=3){return t.map((n)=>({cmd:n,distance:He(e,n)})).filter(({distance:n})=>n<=i).sort((n,o)=>n.distance-o.distance).slice(0,s).map(({cmd:n})=>n)}function Ke(e,t={}){let i={_:[]},s=t.alias||{},n=new Set(t.boolean||[]),o={};for(let a of Object.keys(s))for(let r of s[a])o[r]=a;for(let a of n)if(s[a])for(let r of s[a])n.add(r);function m(a,r){if(a===void 0)return r;if(typeof r==="boolean")return r;return Array.isArray(a)?[...a,r]:[a,r]}function d(a,r){let c=o[a]||a,h=m(i[c],r);if(i[c]=h,s[c])for(let l of s[c])i[l]=h;if(o[a]&&s[o[a]])for(let l of s[o[a]])i[l]=h;i[a]=h}for(let a=0;a<e.length;a++){let r=e[a];if(r==="--"){i._.push(...e.slice(a+1));break}if(r.startsWith("--")){let c=r.indexOf("=");if(c!==-1){let h=N(r.slice(2,c)),l=r.slice(c+1);d(h,l)}else{let h=r.slice(2);if(h.startsWith("no-")){let f=N(h.slice(3));d(f,!1);continue}let l=N(h),y=o[l]||l;if(n.has(y)||n.has(l))d(l,!0);else{let f=e[a+1];if(f!==void 0&&!f.startsWith("-"))d(l,f),a++;else d(l,!0)}}}else if(r.startsWith("-")&&r.length>1){let c=r.slice(1);for(let h=0;h<c.length;h++){let l=c[h],y=o[l]||l;if(h===c.length-1&&!n.has(y)&&!n.has(l)){let f=e[a+1];if(f!==void 0&&!f.startsWith("-"))d(l,f),a++;else d(l,!0)}else d(l,!0)}}else i._.push(r)}return i}class je{rawName;description;name;names;isBoolean;required;config;negated;variadic;constructor(e,t,i){if(this.rawName=e,this.description=t,this.config=Object.assign({},i),e=e.replace(/\.\*/g,""),this.negated=!1,this.variadic=/[<[](?:\.\.\.[^\]>]+|[^\]>]+\.\.\.)[\]>]/.test(e),this.names=J(e).split(",").map((s)=>{let n=s.trim().replace(/^-{1,2}/,"");if(n.startsWith("no-"))this.negated=!0,n=n.replace(/^no-/,"");return _(n)}).sort((s,n)=>s.length>n.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var Dt=X.argv,Ye=`${X.platform}-${X.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,_e=D.argv,Qe=`${D.platform}-${D.arch} node-${D.version}`;class me{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,i,s){this.rawName=e,this.description=t,this.config=i,this.cli=s,this.options=[],this.aliasNames=[],this.name=J(e);let n=J(e),o=n.indexOf(":");if(o>0)this.namespace=n.substring(0,o),this.name=n.substring(o+1);if(this.args=Ne(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!i)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,i){let s=new je(e,t,i);return this.options.push(s),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof he}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){let t=_(e.split(".")[0]);return!!this.options.find((i)=>i.names.some((s)=>_(s)===t))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:i,options:s,helpCallback:n}=this.cli.globalCommand,o=[{body:`${e}${i?`/${i}`:""}`}];if(o.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let r=Ie(t.map((f)=>f.rawName)),c=new Map,h=[];for(let f of t)if(f.namespace){if(!c.has(f.namespace))c.set(f.namespace,[]);c.get(f.namespace).push(f)}else h.push(f);let l="";if(h.sort((f,T)=>f.rawName<T.rawName?-1:f.rawName>T.rawName?1:0),h.length>0)l+=h.map((f)=>` ${z(f.rawName,r.length)} ${f.description}`).join(`
7
- `);let y=Array.from(c.keys()).sort();for(let f of y){let T=c.get(f);if(l.length>0)l+=`
6
+ ${this.stack}`;return this.message}}function Ue(e){if(e instanceof E)return!0;return!!e&&typeof e==="object"&&e.name==="ClappError"&&typeof e.message==="string"}function Ge(){let{env:e}=ye,{TERM:t,TERM_PROGRAM:i}=e;if(ye.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||i==="Terminus-Sublime"||i==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var L="\x1B",b=`${L}[`;var Ie={to(e,t){if(!t)return`${b}${e+1}G`;return`${b}${t+1};${e+1}H`},move(e,t){let i="";if(e<0)i+=`${b}${-e}D`;else if(e>0)i+=`${b}${e}C`;if(t<0)i+=`${b}${-t}A`;else if(t>0)i+=`${b}${t}B`;return i},up:(e=1)=>`${b}${e}A`,down:(e=1)=>`${b}${e}B`,forward:(e=1)=>`${b}${e}C`,backward:(e=1)=>`${b}${e}D`,nextLine:(e=1)=>`${b}E`.repeat(e),prevLine:(e=1)=>`${b}F`.repeat(e),left:`${b}G`,hide:`${b}?25l`,show:`${b}?25h`,save:`${L}7`,restore:`${L}8`};var Vt={screen:`${b}2J`,up:(e=1)=>`${b}1J`.repeat(e),down:(e=1)=>`${b}J`.repeat(e),line:`${b}2K`,lineEnd:`${b}K`,lineStart:`${b}1K`,lines(e){let t="";for(let i=0;i<e;i++)t+=this.line+(i<e-1?Ie.up():"");if(e)t+=Ie.left;return t}},Lt={screen:`${L}c`};function He(e,t){let i=[];for(let s=0;s<=t.length;s++)i[s]=[s];for(let s=0;s<=e.length;s++)i[0][s]=s;for(let s=1;s<=t.length;s++)for(let n=1;n<=e.length;n++)if(t.charAt(s-1)===e.charAt(n-1))i[s][n]=i[s-1][n-1];else i[s][n]=Math.min(i[s-1][n-1]+1,i[s][n-1]+1,i[s-1][n]+1);return i[t.length][e.length]}function Be(e,t,i=2,s=3){return t.map((n)=>({cmd:n,distance:He(e,n)})).filter(({distance:n})=>n<=i).sort((n,o)=>n.distance-o.distance).slice(0,s).map(({cmd:n})=>n)}function Ke(e,t={}){let i={_:[]},s=t.alias||{},n=new Set(t.boolean||[]),o={};for(let a of Object.keys(s))for(let r of s[a])o[r]=a;for(let a of n)if(s[a])for(let r of s[a])n.add(r);function m(a,r){if(a===void 0)return r;if(typeof r==="boolean")return r;return Array.isArray(a)?[...a,r]:[a,r]}function d(a,r){let c=o[a]||a,h=m(i[c],r);if(i[c]=h,s[c])for(let l of s[c])i[l]=h;if(o[a]&&s[o[a]])for(let l of s[o[a]])i[l]=h;i[a]=h}for(let a=0;a<e.length;a++){let r=e[a];if(r==="--"){i._.push(...e.slice(a+1));break}if(r.startsWith("--")){let c=r.indexOf("=");if(c!==-1){let h=B(r.slice(2,c)),l=r.slice(c+1);d(h,l)}else{let h=r.slice(2);if(h.startsWith("no-")){let f=B(h.slice(3));d(f,!1);continue}let l=B(h),y=o[l]||l;if(n.has(y)||n.has(l))d(l,!0);else{let f=e[a+1];if(f!==void 0&&!f.startsWith("-"))d(l,f),a++;else d(l,!0)}}}else if(r.startsWith("-")&&r.length>1){let c=r.slice(1);for(let h=0;h<c.length;h++){let l=c[h],y=o[l]||l;if(h===c.length-1&&!n.has(y)&&!n.has(l)){let f=e[a+1];if(f!==void 0&&!f.startsWith("-"))d(l,f),a++;else d(l,!0)}else d(l,!0)}}else i._.push(r)}return i}class je{rawName;description;name;names;isBoolean;required;config;negated;variadic;constructor(e,t,i){if(this.rawName=e,this.description=t,this.config=Object.assign({},i),e=e.replace(/\.\*/g,""),this.negated=!1,this.variadic=/[<[](?:\.\.\.[^\]>]+|[^\]>]+\.\.\.)[\]>]/.test(e),this.names=Y(e).split(",").map((s)=>{let n=s.trim().replace(/^-{1,2}/,"");if(n.startsWith("no-"))this.negated=!0,n=n.replace(/^no-/,"");return k(n)}).sort((s,n)=>s.length>n.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var Dt=X.argv,Ye=`${X.platform}-${X.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,_e=T.argv,Qe=`${T.platform}-${T.arch} node-${T.version}`;class Z{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,i,s){this.rawName=e,this.description=t,this.config=i,this.cli=s,this.options=[],this.aliasNames=[],this.name=Y(e);let n=Y(e),o=n.indexOf(":");if(o>0)this.namespace=n.substring(0,o),this.name=n.substring(o+1);if(this.args=Ne(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!i)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,i){let s=new je(e,t,i);return this.options.push(s),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof ee}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){let t=k(e.split(".")[0]);return!!this.options.find((i)=>i.names.some((s)=>k(s)===t))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:i,options:s,helpCallback:n}=this.cli.globalCommand,o=[{body:`${e}${i?`/${i}`:""}`}];if(o.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let r=Oe(t.map((f)=>f.rawName)),c=new Map,h=[];for(let f of t)if(f.namespace){if(!c.has(f.namespace))c.set(f.namespace,[]);c.get(f.namespace).push(f)}else h.push(f);let l="";if(h.sort((f,_)=>f.rawName<_.rawName?-1:f.rawName>_.rawName?1:0),h.length>0)l+=h.map((f)=>` ${D(f.rawName,r.length)} ${f.description}`).join(`
7
+ `);let y=Array.from(c.keys()).sort();for(let f of y){let _=c.get(f);if(l.length>0)l+=`
8
8
 
9
9
  `;l+=` ${f}:
10
- `,l+=T.map((Ce)=>` ${z(Ce.rawName,r.length-2)} ${Ce.description}`).join(`
11
- `)}o.push({title:"Commands",body:l}),o.push({body:`Run \`${e} <command> --help\` for command details.`})}let d=new Set(this.options.flatMap((r)=>r.names)),a=this.isGlobalCommand?s:[...this.options,...(s||[]).filter((r)=>!r.names.some((c)=>d.has(c)))];if(!this.isGlobalCommand&&!this.isDefaultCommand)a=a.filter((r)=>r.name!=="version");if(a.length>0){let r=Ie(a.map((c)=>c.rawName));o.push({title:"Options",body:a.map((c)=>` ${z(c.rawName,r.length)} ${c.description} ${c.config.default===void 0?"":`(default: ${c.config.default})`}`).join(`
10
+ `,l+=_.map((be)=>` ${D(be.rawName,r.length-2)} ${be.description}`).join(`
11
+ `)}o.push({title:"Commands",body:l}),o.push({body:`Run \`${e} <command> --help\` for command details.`})}let d=new Set(this.options.flatMap((r)=>r.names)),a=this.isGlobalCommand?s:[...this.options,...(s||[]).filter((r)=>!r.names.some((c)=>d.has(c)))];if(!this.isGlobalCommand&&!this.isDefaultCommand)a=a.filter((r)=>r.name!=="version");if(a.length>0){let r=Oe(a.map((c)=>c.rawName));o.push({title:"Options",body:a.map((c)=>` ${D(c.rawName,r.length)} ${c.description} ${c.config.default===void 0?"":`(default: ${c.config.default})`}`).join(`
12
12
  `)})}if(this.examples.length>0)o.push({title:"Examples",body:this.examples.map((r)=>{if(typeof r==="function")return r(e);return r}).join(`
13
13
  `)});if(n)o=n(o)||o;console.log(o.map((r)=>r.title?`${r.title}:
14
14
  ${r.body}`:r.body).join(`
15
15
 
16
- `))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;if(t)console.log(`${e}/${t} ${typeof Bun<"u"?Ye:Qe}`)}get usageLine(){return`$ ${this.cli.name} ${this.usageText||this.rawName}`}checkRequiredArgs(){let e=this.args.filter((t)=>t.required).length;if(this.cli.args.length<e){let i=this.args.filter((n)=>n.required).slice(this.cli.args.length),s=i.map((n)=>`<${n.value}>`).join(" ");throw new B(`Missing required argument${i.length>1?"s":""}: ${s}
16
+ `))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;if(t)console.log(`${e}/${t} ${typeof Bun<"u"?Ye:Qe}`)}get usageLine(){return`$ ${this.cli.name} ${this.usageText||this.rawName}`}checkRequiredArgs(){let e=this.args.filter((t)=>t.required).length;if(this.cli.args.length<e){let i=this.args.filter((n)=>n.required).slice(this.cli.args.length),s=i.map((n)=>`<${n.value}>`).join(" ");throw new E(`Missing required argument${i.length>1?"s":""}: ${s}
17
17
 
18
- Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`,this.usageLine)}}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let i of Object.keys(e))if(i!=="--"&&!this.hasOption(i)&&!t.hasOption(i)){let n=[...t.options,...this.options].flatMap((r)=>r.names),o=_(i.split(".")[0]),m=i.length>1?`--${i}`:`-${i}`,d=Be(o,n),a=`Unknown option \`${m}\``;if(d.length>0)a+=`
18
+ Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`,this.usageLine)}}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let i of Object.keys(e))if(i!=="--"&&!this.hasOption(i)&&!t.hasOption(i)){let n=[...t.options,...this.options].flatMap((r)=>r.names),o=k(i.split(".")[0]),m=i.length>1?`--${i}`:`-${i}`,d=Be(o,n),a=`Unknown option \`${m}\``;if(d.length>0)a+=`
19
19
 
20
20
  Did you mean one of these?`,d.forEach((r)=>{let c=r.length>1?`--${r}`:`-${r}`;a+=`
21
21
  \u2022 ${c}`});throw a+=`
22
22
 
23
- Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new B(a,this.usageLine)}}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,i=[...t.options,...this.options];for(let s of i){let n=e[s.name.split(".")[0]];if(s.required){let o=i.some((m)=>m.negated&&m.names.includes(s.name));if(n===!0||n===!1&&!o)throw new B(`Option \`${s.rawName}\` requires a value.
23
+ Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new E(a,this.usageLine)}}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,i=[...t.options,...this.options];for(let s of i){let n=e[s.name.split(".")[0]];if(s.required){let o=i.some((m)=>m.negated&&m.names.includes(s.name));if(n===!0||n===!1&&!o)throw new E(`Option \`${s.rawName}\` requires a value.
24
24
 
25
- Example: ${this.cli.name} ${this.rawName} ${s.rawName} <value>`,this.usageLine)}}}}class he extends me{constructor(e){super("@@global@@","",{},e)}}var Je=me,x={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var O={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function Xe(){return!0}function Ze(){let e={};e.supportsColor=Xe();function t(s,n=[]){let o=s===""?[]:[...n,s],m=function(a){if(!e.supportsColor)return a;let r="",c="";for(let h of o)if(h in O&&O[h]in x){let l=O[h];r+=x[l][0],c=x[l][1]+c}else if(h in x)r+=x[h][0],c=x[h][1]+c;return r+a+c},d=[...Object.keys(x),...Object.keys(O)];for(let a of d)if(!(a in m))Object.defineProperty(m,a,{get(){return t(a,o)}});return m}let i=[...Object.keys(x),...Object.keys(O)];for(let s of i)if(!(s in e))Object.defineProperty(e,s,{get(){return t(s)}});return e}var k=Ze();class pe extends Le{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(e=""){super();this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new he(this),this.globalCommand.usage("<command> [options]")}handleSignals(e){if(this.signalHandlersSet)return this;let t=async(i)=>{if(console.log(`
25
+ Example: ${this.cli.name} ${this.rawName} ${s.rawName} <value>`,this.usageLine)}}}}class ee extends Z{constructor(e){super("@@global@@","",{},e)}}var Je=Z,w={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var C={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function Xe(){return!0}function Ze(){let e={};e.supportsColor=Xe();function t(s,n=[]){let o=s===""?[]:[...n,s],m=function(a){if(!e.supportsColor)return a;let r="",c="";for(let h of o)if(h in C&&C[h]in w){let l=C[h];r+=w[l][0],c=w[l][1]+c}else if(h in w)r+=w[h][0],c=w[h][1]+c;return r+a+c},d=[...Object.keys(w),...Object.keys(C)];for(let a of d)if(!(a in m))Object.defineProperty(m,a,{get(){return t(a,o)}});return m}let i=[...Object.keys(w),...Object.keys(C)];for(let s of i)if(!(s in e))Object.defineProperty(e,s,{get(){return t(s)}});return e}var O=Ze();class pe extends Le{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(e=""){super();this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new ee(this),this.globalCommand.usage("<command> [options]")}handleSignals(e){if(this.signalHandlersSet)return this;let t=async(i)=>{if(console.log(`
26
26
 
27
- Received ${i}, cleaning up...`),e)try{await e()}catch(s){console.error("Error during cleanup:",s)}v.exit(0)};return v.on("SIGINT",()=>t("SIGINT")),v.on("SIGTERM",()=>t("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(e=!0){return this.enableDidYouMean=e,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(e){return this.globalCommand.usage(e),this}command(e,t,i){if(!i)i={};let s=new Je(e,t||"",i,this);return s.globalCommand=this.globalCommand,this.commands.push(s),s}option(e,t,i){return this.globalCommand.option(e,t,i),this}help(e){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t="-v, --version"){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},i,s){if(this.args=e,this.options=t,i)this.matchedCommand=i;if(s)this.matchedCommandName=s;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(e){if(console.log(k.red(`
27
+ Received ${i}, cleaning up...`),e)try{await e()}catch(s){console.error("Error during cleanup:",s)}v.exit(0)};return v.on("SIGINT",()=>t("SIGINT")),v.on("SIGTERM",()=>t("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(e=!0){return this.enableDidYouMean=e,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(e){return this.globalCommand.usage(e),this}command(e,t,i){if(!i)i={};let s=new Je(e,t||"",i,this);return s.globalCommand=this.globalCommand,this.commands.push(s),s}option(e,t,i){return this.globalCommand.option(e,t,i),this}help(e){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t="-v, --version"){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},i,s){if(this.args=e,this.options=t,i)this.matchedCommand=i;if(s)this.matchedCommandName=s;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(e){if(console.log(O.red(`
28
28
  \u2717 Command "${e}" not found.
29
- `)),this.enableDidYouMean){let t=[];for(let s of this.commands){if(s.displayName)t.push(s.displayName);if(s.aliasNames)t.push(...s.aliasNames)}let i=Be(e,t);if(i.length>0)console.log(k.yellow("Did you mean one of these?")),i.forEach((s)=>console.log(` ${k.dim("\u2022")} ${this.name} ${s}`)),console.log("")}console.log(k.dim("Run"),`${this.name} --help`,k.dim("to see all available commands")),v.exit(1)}async parse(e=_e,t={}){let{run:i=!0,exitOnError:s=!1}=t;if(s)try{return await this.parse(e,{run:i})}catch(a){throw this.handleUsageError(a),a}if(this.rawArgs=e,!this.name)this.name=e[1]?ze(e[1]):"cli";let n=!0,o=e.slice(2),m=o[0];if(m&&!m.startsWith("-")){for(let a of this.commands)if(a.isMatched(m)){let r=this.mri(o,a);n=!1;let c={...r,args:r.args.slice(1)};this.setParsedInfo(c,a,m),this.emit(`command:${m}`,a);break}if(n){let a=o[1];if(a&&!a.startsWith("-")){let r=`${m}:${a}`;for(let c of this.commands)if(c.isMatched(r)){let h=this.mri(o,c);n=!1;let l={...h,args:h.args.slice(2)};this.setParsedInfo(l,c,r),this.emit(`command:${r}`,c);break}}}}if(n){for(let a of this.commands)if(a.name===""){n=!1;let r=this.mri(o,a);this.setParsedInfo(r,a),this.emit("command:!",a);break}}if(n){let a=this.mri(e.slice(2));this.setParsedInfo(a)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction||this.options.interaction===!1)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji||this.options.emoji===!1)this.useEmoji=!1;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache||this.options.cache===!1)this.isNoCache=!0;if(this.options.help&&this.showHelpOnExit)this.outputHelp(),i=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),i=!1,this.unsetMatchedCommand();let d={args:this.args,options:this.options};if(i)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return d}mri(e,t){let i=[...this.globalCommand.options,...t?t.options:[]],s=Pe(i),n=[],o=e.indexOf("--");if(o>-1)n=e.slice(o+1),e=e.slice(0,o);let m=Ke(e,s),d={_:m._};for(let l of Object.keys(m))if(l!=="_")d[_(l)]=m[l];let a=d._,r={"--":n},c=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,h=Object.create(null);for(let l of i){if(!c&&l.config.default!==void 0)for(let y of l.names)r[y]=l.config.default;if(Array.isArray(l.config.type)){if(h[l.name]===void 0)h[l.name]={shouldTransform:!0,transformFunction:l.config.type[0]}}}for(let l of Object.keys(d))if(l!=="_"){let y=l.split(".");We(r,y,d[l]),Fe(r,h)}for(let l of i){if(!l.variadic)continue;for(let y of l.names){let f=r[y];if(f===void 0||Array.isArray(f))continue;if(l.config.default!==void 0&&f===l.config.default)continue;r[y]=[f]}}return{args:a,options:r}}async run(e=_e){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!Ue(e)||e.isUsageError===!1)return;let t=e.message||"command-line error",i=this.name?`${this.name}: `:"",s=/--help/.test(t)?"":e.usage?`
29
+ `)),this.enableDidYouMean){let t=[];for(let s of this.commands){if(s.displayName)t.push(s.displayName);if(s.aliasNames)t.push(...s.aliasNames)}let i=Be(e,t);if(i.length>0)console.log(O.yellow("Did you mean one of these?")),i.forEach((s)=>console.log(` ${O.dim("\u2022")} ${this.name} ${s}`)),console.log("")}console.log(O.dim("Run"),`${this.name} --help`,O.dim("to see all available commands")),v.exit(1)}async parse(e=_e,t={}){let{run:i=!0,exitOnError:s=!1}=t;if(s)try{return await this.parse(e,{run:i})}catch(a){throw this.handleUsageError(a),a}if(this.rawArgs=e,!this.name)this.name=e[1]?ze(e[1]):"cli";let n=!0,o=e.slice(2),m=o[0];if(m&&!m.startsWith("-")){for(let a of this.commands)if(a.isMatched(m)){let r=this.mri(o,a);n=!1;let c={...r,args:r.args.slice(1)};this.setParsedInfo(c,a,m),this.emit(`command:${m}`,a);break}if(n){let a=o[1];if(a&&!a.startsWith("-")){let r=`${m}:${a}`;for(let c of this.commands)if(c.isMatched(r)){let h=this.mri(o,c);n=!1;let l={...h,args:h.args.slice(2)};this.setParsedInfo(l,c,r),this.emit(`command:${r}`,c);break}}}}if(n){for(let a of this.commands)if(a.name===""){n=!1;let r=this.mri(o,a);this.setParsedInfo(r,a),this.emit("command:!",a);break}}if(n){let a=this.mri(e.slice(2));this.setParsedInfo(a)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction||this.options.interaction===!1)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji||this.options.emoji===!1)this.useEmoji=!1;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache||this.options.cache===!1)this.isNoCache=!0;if(this.options.help&&this.showHelpOnExit)this.outputHelp(),i=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),i=!1,this.unsetMatchedCommand();let d={args:this.args,options:this.options};if(i)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return d}mri(e,t){let i=[...this.globalCommand.options,...t?t.options:[]],s=Pe(i),n=[],o=e.indexOf("--");if(o>-1)n=e.slice(o+1),e=e.slice(0,o);let m=Ke(e,s),d={_:m._};for(let l of Object.keys(m))if(l!=="_")d[k(l)]=m[l];let a=d._,r={"--":n},c=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,h=Object.create(null);for(let l of i){if(!c&&l.config.default!==void 0)for(let y of l.names)r[y]=l.config.default;if(Array.isArray(l.config.type)){if(h[l.name]===void 0)h[l.name]={shouldTransform:!0,transformFunction:l.config.type[0]}}}for(let l of Object.keys(d))if(l!=="_"){let y=l.split(".");We(r,y,d[l]),Fe(r,h)}for(let l of i){if(!l.variadic)continue;for(let y of l.names){let f=r[y];if(f===void 0||Array.isArray(f))continue;if(l.config.default!==void 0&&f===l.config.default)continue;r[y]=[f]}}return{args:a,options:r}}async run(e=_e){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!Ue(e)||e.isUsageError===!1)return;let t=e.message||"command-line error",i=this.name?`${this.name}: `:"",s=/--help/.test(t)?"":e.usage?`
30
30
  Usage: ${e.usage}`:`
31
31
  Run \`${this.name??"cli"} --help\` for usage.`;v.stderr.write(`${i}${t}${s}
32
- `),v.exit(e.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:i}=this;if(!i||!i.commandAction)return;i.checkUnknownOptions(),i.checkOptionValue(),i.checkRequiredArgs();let s=[];i.args.forEach((d,a)=>{if(d.variadic)s.push(e.slice(a));else s.push(e[a])}),s.push(t);let n={command:i,args:s,options:t};for(let d of i.beforeHooks)await d(n);let o,m=async()=>{let d=i.commandAction.apply(this,s);if(d instanceof Promise)o=await d;else o=d;return o};if(i.middleware.length>0){let d=0,a=async()=>{if(d<i.middleware.length){let r=i.middleware[d++];await r({...n,next:a})}else await m()};await a()}else await m();for(let d of i.afterHooks)await d(n);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return v.removeAllListeners("SIGINT"),v.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class Ae{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,i=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:i})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())if(e-i.timestamp>i.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var Wt=new Ae;function et(){if("FORCE_COLOR"in E.env)return E.env.FORCE_COLOR!=="0";if("NO_COLOR"in E.env||E.env.TERM==="dumb")return!1;if(E.platform==="win32")return!0;return qe.isatty(1)&&qe.isatty(2)}var Re=et();function g(e,t){if(!Re)return(i)=>i;return(i)=>e+i+t}var tt=g("\x1B[0m","\x1B[0m"),it=g("\x1B[31m","\x1B[39m"),st=g("\x1B[32m","\x1B[39m"),rt=g("\x1B[33m","\x1B[39m"),nt=g("\x1B[34m","\x1B[39m"),at=g("\x1B[35m","\x1B[39m"),ot=g("\x1B[36m","\x1B[39m"),lt=g("\x1B[37m","\x1B[39m"),ct=g("\x1B[90m","\x1B[39m"),ut=g("\x1B[1m","\x1B[22m"),dt=g("\x1B[3m","\x1B[23m"),mt=g("\x1B[4m","\x1B[24m"),ht=g("\x1B[2m","\x1B[22m"),ft=g("\x1B[7m","\x1B[27m"),pt=g("\x1B[8m","\x1B[28m"),gt=g("\x1B[9m","\x1B[29m"),bt=g("\x1B[41m","\x1B[49m"),yt=g("\x1B[42m","\x1B[49m"),$t=g("\x1B[43m","\x1B[49m"),vt=g("\x1B[44m","\x1B[49m"),wt=g("\x1B[45m","\x1B[49m"),xt=g("\x1B[46m","\x1B[49m"),Ct=g("\x1B[47m","\x1B[49m"),St=Re,Ot={reset:tt,red:it,green:st,yellow:rt,blue:nt,magenta:at,cyan:ot,white:lt,gray:ct,bold:ut,italic:dt,underline:mt,dim:ht,inverse:ft,hidden:pt,strikethrough:gt,bgRed:bt,bgGreen:yt,bgYellow:$t,bgBlue:vt,bgMagenta:wt,bgCyan:xt,bgWhite:Ct,isColorSupported:St},It=Ot,Et=["up","down","left","right","space","enter","cancel"],Kt={actions:new Set(Et),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var Yt=kt.platform.startsWith("win"),Qt=Symbol("clapp:cancel");var _t=Ge();var p=(e,t)=>_t?e:t,Jt=p("\u25C6","*"),Xt=p("\u25A0","x"),Zt=p("\u25B2","x"),ei=p("\u25C7","o"),ti=p("\u250C","T"),qt=p("\u2502","|"),ii=p("\u2514","\u2014"),si=p("\u25CF",">"),ri=p("\u25CB"," "),ni=p("\u25FB","[\u2022]"),ai=p("\u25FC","[+]"),oi=p("\u25FB","[ ]"),li=p("\u25AA","\u2022"),ci=p("\u2500","-"),ui=p("\u256E","+"),di=p("\u251C","+"),mi=p("\u256F","+"),hi=p("\u25CF","\u2022"),fi=p("\u25C6","*"),pi=p("\u25B2","!"),gi=p("\u25A0","x");var bi={light:p("\u2500","-"),heavy:p("\u2501","="),block:p("\u2588","#")};function Mt(){return`${It.gray(qt)} `}var yi=Mt();class Ve{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Me.homedir(),t=Y.join(e,".config","clapp");this.configPath=Y.join(t,"telemetry.json")}async isEnabled(){if(S.env.DO_NOT_TRACK==="1"||S.env.DO_NOT_TRACK==="true")return!1;if(S.env.NO_TELEMETRY==="1"||S.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let s={event:e,...t,timestamp:Date.now(),platform:Me.platform(),nodeVersion:S.version};if(this.events.push(s),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:S.env.DO_NOT_TRACK==="1"||S.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Bt(this.configPath)){let e=await G.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=Y.dirname(this.configPath);await G.mkdir(t,{recursive:!0}),await G.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var Si=new Ve;var ge="0.3.9";var u=new pe("query-builder");u.command("introspect <dir>","Load models and print inferred schema").option("--verbose","Enable verbose logging").example("query-builder introspect ./app/Models --verbose").action(async(e,t)=>{await de(e,t)});u.command("introspect:db","Reverse-introspect the live database into defineModel() source (#1047)").option("--table <table>","Limit to a single table (repeatable)").example("query-builder introspect:db > app/Models/generated.ts").action(async(e)=>{let t=e?.table,i=t?Array.isArray(t)?t:[t]:void 0,s=await C({tables:i});console.log(`import { defineModel } from 'bun-query-builder'
32
+ `),v.exit(e.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:i}=this;if(!i||!i.commandAction)return;i.checkUnknownOptions(),i.checkOptionValue(),i.checkRequiredArgs();let s=[];i.args.forEach((d,a)=>{if(d.variadic)s.push(e.slice(a));else s.push(e[a])}),s.push(t);let n={command:i,args:s,options:t};for(let d of i.beforeHooks)await d(n);let o,m=async()=>{let d=i.commandAction.apply(this,s);if(d instanceof Promise)o=await d;else o=d;return o};if(i.middleware.length>0){let d=0,a=async()=>{if(d<i.middleware.length){let r=i.middleware[d++];await r({...n,next:a})}else await m()};await a()}else await m();for(let d of i.afterHooks)await d(n);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return v.removeAllListeners("SIGINT"),v.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class Ae{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,i=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:i})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())if(e-i.timestamp>i.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var Wt=new Ae;function et(){if("FORCE_COLOR"in I.env)return I.env.FORCE_COLOR!=="0";if("NO_COLOR"in I.env||I.env.TERM==="dumb")return!1;if(I.platform==="win32")return!0;return qe.isatty(1)&&qe.isatty(2)}var Re=et();function g(e,t){if(!Re)return(i)=>i;return(i)=>e+i+t}var tt=g("\x1B[0m","\x1B[0m"),it=g("\x1B[31m","\x1B[39m"),st=g("\x1B[32m","\x1B[39m"),rt=g("\x1B[33m","\x1B[39m"),nt=g("\x1B[34m","\x1B[39m"),at=g("\x1B[35m","\x1B[39m"),ot=g("\x1B[36m","\x1B[39m"),lt=g("\x1B[37m","\x1B[39m"),ct=g("\x1B[90m","\x1B[39m"),ut=g("\x1B[1m","\x1B[22m"),dt=g("\x1B[3m","\x1B[23m"),mt=g("\x1B[4m","\x1B[24m"),ht=g("\x1B[2m","\x1B[22m"),ft=g("\x1B[7m","\x1B[27m"),pt=g("\x1B[8m","\x1B[28m"),gt=g("\x1B[9m","\x1B[29m"),bt=g("\x1B[41m","\x1B[49m"),yt=g("\x1B[42m","\x1B[49m"),$t=g("\x1B[43m","\x1B[49m"),vt=g("\x1B[44m","\x1B[49m"),wt=g("\x1B[45m","\x1B[49m"),xt=g("\x1B[46m","\x1B[49m"),Ct=g("\x1B[47m","\x1B[49m"),St=Re,Ot={reset:tt,red:it,green:st,yellow:rt,blue:nt,magenta:at,cyan:ot,white:lt,gray:ct,bold:ut,italic:dt,underline:mt,dim:ht,inverse:ft,hidden:pt,strikethrough:gt,bgRed:bt,bgGreen:yt,bgYellow:$t,bgBlue:vt,bgMagenta:wt,bgCyan:xt,bgWhite:Ct,isColorSupported:St},It=Ot,Et=["up","down","left","right","space","enter","cancel"],Kt={actions:new Set(Et),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var Yt=kt.platform.startsWith("win"),Qt=Symbol("clapp:cancel");var _t=Ge();var p=(e,t)=>_t?e:t,Jt=p("\u25C6","*"),Xt=p("\u25A0","x"),Zt=p("\u25B2","x"),ei=p("\u25C7","o"),ti=p("\u250C","T"),qt=p("\u2502","|"),ii=p("\u2514","\u2014"),si=p("\u25CF",">"),ri=p("\u25CB"," "),ni=p("\u25FB","[\u2022]"),ai=p("\u25FC","[+]"),oi=p("\u25FB","[ ]"),li=p("\u25AA","\u2022"),ci=p("\u2500","-"),ui=p("\u256E","+"),di=p("\u251C","+"),mi=p("\u256F","+"),hi=p("\u25CF","\u2022"),fi=p("\u25C6","*"),pi=p("\u25B2","!"),gi=p("\u25A0","x");var bi={light:p("\u2500","-"),heavy:p("\u2501","="),block:p("\u2588","#")};function Mt(){return`${It.gray(qt)} `}var yi=Mt();class Ve{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Me.homedir(),t=z.join(e,".config","clapp");this.configPath=z.join(t,"telemetry.json")}async isEnabled(){if(x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true")return!1;if(x.env.NO_TELEMETRY==="1"||x.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let s={event:e,...t,timestamp:Date.now(),platform:Me.platform(),nodeVersion:x.version};if(this.events.push(s),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Bt(this.configPath)){let e=await P.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=z.dirname(this.configPath);await P.mkdir(t,{recursive:!0}),await P.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var Si=new Ve;var ge="0.3.10";var u=new pe("query-builder");u.command("introspect <dir>","Load models and print inferred schema").option("--verbose","Enable verbose logging").example("query-builder introspect ./app/Models --verbose").action(async(e,t)=>{await me(e,t)});u.command("introspect:db","Reverse-introspect the live database into defineModel() source (#1047)").option("--table <table>","Limit to a single table (repeatable)").example("query-builder introspect:db > app/Models/generated.ts").action(async(e)=>{let t=e?.table,i=t?Array.isArray(t)?t:[t]:void 0,s=await R({tables:i});console.log(`import { defineModel } from 'bun-query-builder'
33
33
 
34
34
  ${s.map((n)=>n.source).join(`
35
- `)}`)});u.command("sql <dir> <table>","Build a sample query for a table").option("--limit <n>","Limit rows",{default:10}).example("query-builder sql ./app/Models users --limit 5").action(async(e,t,i)=>{await Ee(e,t,i)});u.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await we()});u.command("wait-ready","Wait for database to become ready").option("--attempts <n>","Number of attempts",{default:10}).option("--delay <ms>","Delay between attempts",{default:100}).example("query-builder wait-ready --attempts 30 --delay 250").action(async(e)=>{try{await ve(e)}catch{let t=await import("process");t.default.exitCode=1}});u.command("unsafe <sql>","Execute an unsafe SQL string (one statement with params)").option("--params <json>","JSON array of parameters").example('query-builder unsafe "SELECT * FROM users WHERE id = $1" --params "[1]"').action(async(e,t)=>{await $e(e,t)});u.command("file <path>","Execute a SQL file (supports $1, $2 params)").option("--params <json>","JSON array of parameters").example("query-builder file ./migrations/seed.sql").example('query-builder file ./reports/top.sql --params "[30]"').action(async(e,t)=>{await ce(e,t)});u.command("migrate <dir>","Generate SQL migrations from models").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--apply","Execute the generated SQL against the database").option("--full","Force full migration SQL instead of incremental diff").option("--from-db","Diff the models against the live database instead of the model snapshot").option("--strict","Fail when the migrated schema does not match the models").example("query-builder migrate ./app/Models --dialect postgres").example("query-builder migrate ./app/Models --from-db --strict").action(async(e,t)=>{try{await w(e,{dialect:t.dialect,state:t.state,apply:t.apply,full:t.full,fromDb:t.fromDb}),await R(void 0,{strict:t.strict,auditDrift:t.strict?"always":!0})}catch(i){console.error("-- Migration failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("explain <sql>","Explain a query").example('query-builder explain "SELECT * FROM users WHERE active = true"').action(async(e)=>{await le(e)});u.command("query:explain-all <path>","Run EXPLAIN on all SQL files in a directory").option("--verbose","Enable verbose output").option("--json","Output as JSON").example("query-builder query:explain-all ./queries").example("query-builder query:explain-all ./queries/users.sql").action(async(e,t)=>{try{await U(e,{verbose:t.verbose,json:t.json})}catch(i){console.error("-- Explain all failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("relation:diagram","Generate relationship diagram from models").option("--dir <path>","Models directory (defaults to app/Models)").option("--format <fmt>","Output format (mermaid|dot)",{default:"mermaid"}).option("--output <path>","Output file path").option("--verbose","Enable verbose output").example("query-builder relation:diagram").example("query-builder relation:diagram --format dot --output schema.dot").example("query-builder relation:diagram --output schema.mmd").action(async(e)=>{try{await V({dir:e.dir,format:e.format,output:e.output,verbose:e.verbose})}catch(t){console.error("-- Diagram generation failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("migrate:fresh <dir>","Reset database and run all migrations").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate:fresh ./app/Models --dialect postgres").action(async(e,t)=>{try{console.log("-- Resetting database..."),await A(e,{dialect:t.dialect,state:t.state}),console.log("-- Generating fresh migrations..."),await w(e,{dialect:t.dialect,state:t.state,full:t.full}),console.log("-- Executing migrations..."),await R()}catch(i){console.error("-- Migrate fresh failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("reset <dir>","Drop all tables and reset database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").example("query-builder reset ./app/Models --dialect postgres").action(async(e,t)=>{try{await A(e,{dialect:t.dialect,state:t.state})}catch(i){console.error("-- Reset failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("seed","Run database seeders").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder seed").example("query-builder seed --class UserSeeder").example("query-builder seed --dir ./database/seeders").action(async(e)=>{try{if(e.class)await H(e.class,{verbose:e.verbose});else await M({seedersDir:e.dir,verbose:e.verbose})}catch(t){console.error("-- Seeding failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:seed","Run database seeders (alias for seed)").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder db:seed").example("query-builder db:seed --class UserSeeder").action(async(e)=>{try{if(e.class)await H(e.class,{verbose:e.verbose});else await M({seedersDir:e.dir,verbose:e.verbose})}catch(t){console.error("-- Seeding failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("make:seeder <name>","Create a new seeder file").example("query-builder make:seeder User").example("query-builder make:seeder UserSeeder").action(async(e)=>{try{await Se(e)}catch(t){console.error("-- Failed to create seeder:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:fresh","Drop all tables, re-run migrations and seed the database").option("--models <path>","Path to models directory (defaults to app/Models)").option("--seeders <path>","Path to seeders directory (defaults to database/seeders)").option("--verbose","Enable verbose logging").example("query-builder db:fresh").example("query-builder db:fresh --models ./app/Models --seeders ./database/seeders").action(async(e)=>{try{await De({modelsDir:e.models,seedersDir:e.seeders,verbose:e.verbose})}catch(t){console.error("-- Database fresh failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("make:model <name>","Create a new model file").option("--table <name>","Table name (defaults to plural of model name)").option("--dir <path>","Models directory (defaults to app/Models)").option("--timestamps","Include timestamp fields (default: true)").example("query-builder make:model User").example("query-builder make:model Post --table=blog_posts").action(async(e,t)=>{try{await fe(e,{table:t.table,dir:t.dir,timestamps:t.timestamps})}catch(i){console.error("-- Failed to create model:",i);let s=await import("process");s.default.exitCode=1}});u.command("model:show <name>","Show detailed model information").option("--dir <path>","Models directory (defaults to app/Models)").option("--json","Output as JSON").option("--verbose","Enable verbose output").example("query-builder model:show User").example("query-builder model:show Post --json").action(async(e,t)=>{try{await W(e,{dir:t.dir,json:t.json,verbose:t.verbose})}catch(i){console.error("-- Failed to show model:",i);let s=await import("process");s.default.exitCode=1}});u.command("migrate:status","Show migration status").example("query-builder migrate:status").action(async()=>{try{await q()}catch(e){console.error("-- Failed to get migration status:",e);let t=await import("process");t.default.exitCode=1}});u.command("migrate:list","List all migrations (alias for migrate:status)").example("query-builder migrate:list").action(async()=>{try{await Te()}catch(e){console.error("-- Failed to list migrations:",e);let t=await import("process");t.default.exitCode=1}});u.command("migrate:rollback","Rollback migrations").option("--steps <n>","Number of migrations to rollback",{default:1}).option("--no-reverse-schema","Only remove the migration records; leave the schema alone").option("--delete-files","Also delete the rolled-back migration files from disk").example("query-builder migrate:rollback").example("query-builder migrate:rollback --steps 2").example("query-builder migrate:rollback --no-reverse-schema").action(async(e)=>{try{await be({steps:Number(e.steps),reverseSchema:e.reverseSchema,deleteFiles:Boolean(e.deleteFiles)})}catch(t){console.error("-- Rollback failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("migrate:generate [dir]","Generate migration from model changes").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file").option("--apply","Execute the generated SQL").option("--full","Force full migration SQL").example("query-builder migrate:generate").example("query-builder migrate:generate ./app/Models --dialect postgres").action(async(e,t)=>{try{await ye(e,{dialect:t?.dialect,state:t?.state,apply:t?.apply,full:t?.full})}catch(i){console.error("-- Generate migration failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("db:info","Show database information and statistics").example("query-builder db:info").action(async()=>{try{await L()}catch(e){console.error("-- Failed to get database info:",e);let t=await import("process");t.default.exitCode=1}});u.command("db:stats","Show database statistics (alias for db:info)").example("query-builder db:stats").action(async()=>{try{await oe()}catch(e){console.error("-- Failed to get database stats:",e);let t=await import("process");t.default.exitCode=1}});u.command("db:wipe","Drop all tables from the database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--force","Skip confirmation prompt").option("--verbose","Enable verbose output").example("query-builder db:wipe").example("query-builder db:wipe --force").action(async(e)=>{try{await F({dialect:e.dialect,force:e.force,verbose:e.verbose})}catch(t){console.error("-- Wipe failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:optimize","Optimize database tables (VACUUM, ANALYZE, OPTIMIZE)").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--aggressive","Use aggressive optimization (VACUUM FULL for postgres)").option("--tables <tables>","Comma-separated list of tables to optimize").option("--verbose","Enable verbose output").example("query-builder db:optimize").example("query-builder db:optimize --aggressive").example("query-builder db:optimize --tables users,posts").action(async(e)=>{try{await K({dialect:e.dialect,aggressive:e.aggressive,tables:e.tables?e.tables.split(","):void 0,verbose:e.verbose})}catch(t){console.error("-- Optimize failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("console","Start interactive query console").example("query-builder console").action(async()=>{try{await I()}catch(e){console.error("-- Console failed:",e);let t=await import("process");t.default.exitCode=1}});u.command("tinker","Start interactive query console (alias for console)").example("query-builder tinker").action(async()=>{try{await re()}catch(e){console.error("-- Tinker failed:",e);let t=await import("process");t.default.exitCode=1}});u.command("inspect <table>","Inspect a table structure").option("--verbose","Enable verbose output",{default:!0}).example("query-builder inspect users").action(async(e,t)=>{try{await j(e,{verbose:t.verbose})}catch(i){console.error("-- Failed to inspect table:",i);let s=await import("process");s.default.exitCode=1}});u.command("table:info <table>","Show table information (alias for inspect)").option("--verbose","Enable verbose output",{default:!0}).example("query-builder table:info users").action(async(e,t)=>{try{await ue(e,{verbose:t.verbose})}catch(i){console.error("-- Failed to get table info:",i);let s=await import("process");s.default.exitCode=1}});u.command("cache:clear","Clear the query cache").example("query-builder cache:clear").action(async()=>{try{await ee()}catch(e){console.error("-- Failed to clear cache:",e);let t=await import("process");t.default.exitCode=1}});u.command("cache:stats","Show cache statistics").example("query-builder cache:stats").action(async()=>{try{await te()}catch(e){console.error("-- Failed to get cache stats:",e);let t=await import("process");t.default.exitCode=1}});u.command("cache:config","Configure cache settings").option("--size <n>","Set maximum cache size").example("query-builder cache:config --size 500").action(async(e)=>{try{await ne({size:e.size})}catch(t){console.error("-- Failed to configure cache:",t);let i=await import("process");i.default.exitCode=1}});u.command("benchmark","Run performance benchmarks").option("--operations <ops>","Comma-separated list of operations (select,insert,update,delete,count)").option("--iterations <n>","Number of iterations per operation",{default:1000}).example("query-builder benchmark").example("query-builder benchmark --operations select,insert --iterations 5000").action(async(e)=>{try{await Z({operations:e.operations,iterations:e.iterations?Number(e.iterations):void 0})}catch(t){console.error("-- Benchmark failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("validate:schema [dir]","Validate models against database schema").example("query-builder validate:schema").example("query-builder validate:schema ./app/Models").action(async(e)=>{try{await Q(e)}catch(t){console.error("-- Validation failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("check [dir]","Validate schema (alias for validate:schema)").example("query-builder check").action(async(e)=>{try{await xe(e)}catch(t){console.error("-- Check failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("export <table>","Export data from a table").option("--format <fmt>","Export format (json|csv|sql)",{default:"json"}).option("--output <path>","Output file path").option("--limit <n>","Limit number of rows").example("query-builder export users").example("query-builder export users --format csv --output users.csv").example("query-builder export users --format sql --limit 100").action(async(e,t)=>{try{await ie(e,{format:t.format,output:t.output,limit:t.limit?Number(t.limit):void 0})}catch(i){console.error("-- Export failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("import <table> <file>","Import data into a table").option("--format <fmt>","Import format (json|csv)").option("--truncate","Truncate table before import").example("query-builder import users users.json").example("query-builder import users users.csv --truncate").action(async(e,t,i)=>{try{await se(e,t,{format:i.format,truncate:i.truncate})}catch(s){console.error("-- Import failed:",s);let n=await import("process");n.default.exitCode=1}});u.command("dump","Dump database to SQL file").option("--tables <tables>","Comma-separated list of tables to dump").option("--output <path>","Output file path").example("query-builder dump").example("query-builder dump --tables users,posts").example("query-builder dump --output backup.sql").action(async(e)=>{try{await ae({tables:e.tables,output:e.output})}catch(t){console.error("-- Dump failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("version","Show the version of the CLI").action(()=>{console.log(ge)});u.version(ge);u.help();u.parse();
35
+ `)}`)});u.command("sql <dir> <table>","Build a sample query for a table").option("--limit <n>","Limit rows",{default:10}).example("query-builder sql ./app/Models users --limit 5").action(async(e,t,i)=>{await xe(e,t,i)});u.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await De()});u.command("wait-ready","Wait for database to become ready").option("--attempts <n>","Number of attempts",{default:10}).option("--delay <ms>","Delay between attempts",{default:100}).example("query-builder wait-ready --attempts 30 --delay 250").action(async(e)=>{try{await Ce(e)}catch{let t=await import("process");t.default.exitCode=1}});u.command("unsafe <sql>","Execute an unsafe SQL string (one statement with params)").option("--params <json>","JSON array of parameters").example('query-builder unsafe "SELECT * FROM users WHERE id = $1" --params "[1]"').action(async(e,t)=>{await ve(e,t)});u.command("file <path>","Execute a SQL file (supports $1, $2 params)").option("--params <json>","JSON array of parameters").example("query-builder file ./migrations/seed.sql").example('query-builder file ./reports/top.sql --params "[30]"').action(async(e,t)=>{await de(e,t)});u.command("migrate <dir>","Generate SQL migrations from models").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--apply","Execute the generated SQL against the database").option("--full","Force full migration SQL instead of incremental diff").option("--from-db","Diff the models against the live database instead of the model snapshot").option("--strict","Fail when the migrated schema does not match the models").example("query-builder migrate ./app/Models --dialect postgres").example("query-builder migrate ./app/Models --from-db --strict").action(async(e,t)=>{try{await S(e,{dialect:t.dialect,state:t.state,apply:t.apply,full:t.full,fromDb:t.fromDb}),await A(void 0,{strict:t.strict,auditDrift:t.strict?"always":!0})}catch(i){console.error("-- Migration failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("explain <sql>","Explain a query").example('query-builder explain "SELECT * FROM users WHERE active = true"').action(async(e)=>{await ue(e)});u.command("query:explain-all <path>","Run EXPLAIN on all SQL files in a directory").option("--verbose","Enable verbose output").option("--json","Output as JSON").example("query-builder query:explain-all ./queries").example("query-builder query:explain-all ./queries/users.sql").action(async(e,t)=>{try{await H(e,{verbose:t.verbose,json:t.json})}catch(i){console.error("-- Explain all failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("relation:diagram","Generate relationship diagram from models").option("--dir <path>","Models directory (defaults to app/Models)").option("--format <fmt>","Output format (mermaid|dot)",{default:"mermaid"}).option("--output <path>","Output file path").option("--verbose","Enable verbose output").example("query-builder relation:diagram").example("query-builder relation:diagram --format dot --output schema.dot").example("query-builder relation:diagram --output schema.mmd").action(async(e)=>{try{await Q({dir:e.dir,format:e.format,output:e.output,verbose:e.verbose})}catch(t){console.error("-- Diagram generation failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("migrate:fresh <dir>","Reset database and run all migrations").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate:fresh ./app/Models --dialect postgres").action(async(e,t)=>{try{console.log("-- Resetting database..."),await N(e,{dialect:t.dialect,state:t.state}),console.log("-- Generating fresh migrations..."),await S(e,{dialect:t.dialect,state:t.state,full:t.full}),console.log("-- Executing migrations..."),await A()}catch(i){console.error("-- Migrate fresh failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("reset <dir>","Drop all tables and reset database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").example("query-builder reset ./app/Models --dialect postgres").action(async(e,t)=>{try{await N(e,{dialect:t.dialect,state:t.state})}catch(i){console.error("-- Reset failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("seed","Run database seeders").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder seed").example("query-builder seed --class UserSeeder").example("query-builder seed --dir ./database/seeders").action(async(e)=>{try{if(e.class)await G(e.class,{verbose:e.verbose});else await M({seedersDir:e.dir,verbose:e.verbose})}catch(t){console.error("-- Seeding failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:seed","Run database seeders (alias for seed)").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder db:seed").example("query-builder db:seed --class UserSeeder").action(async(e)=>{try{if(e.class)await G(e.class,{verbose:e.verbose});else await M({seedersDir:e.dir,verbose:e.verbose})}catch(t){console.error("-- Seeding failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("make:seeder <name>","Create a new seeder file").example("query-builder make:seeder User").example("query-builder make:seeder UserSeeder").action(async(e)=>{try{await Ee(e)}catch(t){console.error("-- Failed to create seeder:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:fresh","Drop all tables, re-run migrations and seed the database").option("--models <path>","Path to models directory (defaults to app/Models)").option("--seeders <path>","Path to seeders directory (defaults to database/seeders)").option("--verbose","Enable verbose logging").example("query-builder db:fresh").example("query-builder db:fresh --models ./app/Models --seeders ./database/seeders").action(async(e)=>{try{await $e({modelsDir:e.models,seedersDir:e.seeders,verbose:e.verbose})}catch(t){console.error("-- Database fresh failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("make:model <name>","Create a new model file").option("--table <name>","Table name (defaults to plural of model name)").option("--dir <path>","Models directory (defaults to app/Models)").option("--timestamps","Include timestamp fields (default: true)").example("query-builder make:model User").example("query-builder make:model Post --table=blog_posts").action(async(e,t)=>{try{await he(e,{table:t.table,dir:t.dir,timestamps:t.timestamps})}catch(i){console.error("-- Failed to create model:",i);let s=await import("process");s.default.exitCode=1}});u.command("model:show <name>","Show detailed model information").option("--dir <path>","Models directory (defaults to app/Models)").option("--json","Output as JSON").option("--verbose","Enable verbose output").example("query-builder model:show User").example("query-builder model:show Post --json").action(async(e,t)=>{try{await V(e,{dir:t.dir,json:t.json,verbose:t.verbose})}catch(i){console.error("-- Failed to show model:",i);let s=await import("process");s.default.exitCode=1}});u.command("migrate:status","Show migration status").example("query-builder migrate:status").action(async()=>{try{await U()}catch(e){console.error("-- Failed to get migration status:",e);let t=await import("process");t.default.exitCode=1}});u.command("migrate:list","List all migrations (alias for migrate:status)").example("query-builder migrate:list").action(async()=>{try{await Se()}catch(e){console.error("-- Failed to list migrations:",e);let t=await import("process");t.default.exitCode=1}});u.command("migrate:rollback","Rollback migrations").option("--steps <n>","Number of migrations to rollback",{default:1}).option("--no-reverse-schema","Only remove the migration records; leave the schema alone").option("--delete-files","Also delete the rolled-back migration files from disk").example("query-builder migrate:rollback").example("query-builder migrate:rollback --steps 2").example("query-builder migrate:rollback --no-reverse-schema").action(async(e)=>{try{await we({steps:Number(e.steps),reverseSchema:e.reverseSchema,deleteFiles:Boolean(e.deleteFiles)})}catch(t){console.error("-- Rollback failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("migrate:generate [dir]","Generate migration from model changes").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file").option("--apply","Execute the generated SQL").option("--full","Force full migration SQL").example("query-builder migrate:generate").example("query-builder migrate:generate ./app/Models --dialect postgres").action(async(e,t)=>{try{await Te(e,{dialect:t?.dialect,state:t?.state,apply:t?.apply,full:t?.full})}catch(i){console.error("-- Generate migration failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("db:info","Show database information and statistics").example("query-builder db:info").action(async()=>{try{await F()}catch(e){console.error("-- Failed to get database info:",e);let t=await import("process");t.default.exitCode=1}});u.command("db:stats","Show database statistics (alias for db:info)").example("query-builder db:stats").action(async()=>{try{await ce()}catch(e){console.error("-- Failed to get database stats:",e);let t=await import("process");t.default.exitCode=1}});u.command("db:wipe","Drop all tables from the database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--force","Skip confirmation prompt").option("--verbose","Enable verbose output").example("query-builder db:wipe").example("query-builder db:wipe --force").action(async(e)=>{try{await q({dialect:e.dialect,force:e.force,verbose:e.verbose})}catch(t){console.error("-- Wipe failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:optimize","Optimize database tables (VACUUM, ANALYZE, OPTIMIZE)").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--aggressive","Use aggressive optimization (VACUUM FULL for postgres)").option("--tables <tables>","Comma-separated list of tables to optimize").option("--verbose","Enable verbose output").example("query-builder db:optimize").example("query-builder db:optimize --aggressive").example("query-builder db:optimize --tables users,posts").action(async(e)=>{try{await j({dialect:e.dialect,aggressive:e.aggressive,tables:e.tables?e.tables.split(","):void 0,verbose:e.verbose})}catch(t){console.error("-- Optimize failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("console","Start interactive query console").example("query-builder console").action(async()=>{try{await K()}catch(e){console.error("-- Console failed:",e);let t=await import("process");t.default.exitCode=1}});u.command("tinker","Start interactive query console (alias for console)").example("query-builder tinker").action(async()=>{try{await se()}catch(e){console.error("-- Tinker failed:",e);let t=await import("process");t.default.exitCode=1}});u.command("inspect <table>","Inspect a table structure").option("--verbose","Enable verbose output",{default:!0}).example("query-builder inspect users").action(async(e,t)=>{try{await W(e,{verbose:t.verbose})}catch(i){console.error("-- Failed to inspect table:",i);let s=await import("process");s.default.exitCode=1}});u.command("table:info <table>","Show table information (alias for inspect)").option("--verbose","Enable verbose output",{default:!0}).example("query-builder table:info users").action(async(e,t)=>{try{await fe(e,{verbose:t.verbose})}catch(i){console.error("-- Failed to get table info:",i);let s=await import("process");s.default.exitCode=1}});u.command("cache:clear","Clear the query cache").example("query-builder cache:clear").action(async()=>{try{await ne()}catch(e){console.error("-- Failed to clear cache:",e);let t=await import("process");t.default.exitCode=1}});u.command("cache:stats","Show cache statistics").example("query-builder cache:stats").action(async()=>{try{await re()}catch(e){console.error("-- Failed to get cache stats:",e);let t=await import("process");t.default.exitCode=1}});u.command("cache:config","Configure cache settings").option("--size <n>","Set maximum cache size").example("query-builder cache:config --size 500").action(async(e)=>{try{await ie({size:e.size})}catch(t){console.error("-- Failed to configure cache:",t);let i=await import("process");i.default.exitCode=1}});u.command("benchmark","Run performance benchmarks").option("--operations <ops>","Comma-separated list of operations (select,insert,update,delete,count)").option("--iterations <n>","Number of iterations per operation",{default:1000}).example("query-builder benchmark").example("query-builder benchmark --operations select,insert --iterations 5000").action(async(e)=>{try{await te({operations:e.operations,iterations:e.iterations?Number(e.iterations):void 0})}catch(t){console.error("-- Benchmark failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("validate:schema [dir]","Validate models against database schema").example("query-builder validate:schema").example("query-builder validate:schema ./app/Models").action(async(e)=>{try{await J(e)}catch(t){console.error("-- Validation failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("check [dir]","Validate schema (alias for validate:schema)").example("query-builder check").action(async(e)=>{try{await ke(e)}catch(t){console.error("-- Check failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("export <table>","Export data from a table").option("--format <fmt>","Export format (json|csv|sql)",{default:"json"}).option("--output <path>","Output file path").option("--limit <n>","Limit number of rows").example("query-builder export users").example("query-builder export users --format csv --output users.csv").example("query-builder export users --format sql --limit 100").action(async(e,t)=>{try{await ae(e,{format:t.format,output:t.output,limit:t.limit?Number(t.limit):void 0})}catch(i){console.error("-- Export failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("import <table> <file>","Import data into a table").option("--format <fmt>","Import format (json|csv)").option("--truncate","Truncate table before import").example("query-builder import users users.json").example("query-builder import users users.csv --truncate").action(async(e,t,i)=>{try{await oe(e,t,{format:i.format,truncate:i.truncate})}catch(s){console.error("-- Import failed:",s);let n=await import("process");n.default.exitCode=1}});u.command("dump","Dump database to SQL file").option("--tables <tables>","Comma-separated list of tables to dump").option("--output <path>","Output file path").example("query-builder dump").example("query-builder dump --tables users,posts").example("query-builder dump --output backup.sql").action(async(e)=>{try{await le({tables:e.tables,output:e.output})}catch(t){console.error("-- Dump failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("version","Show the version of the CLI").action(()=>{console.log(ge)});u.version(ge);u.help();u.parse();
@@ -0,0 +1,49 @@
1
+ /**
2
+ * How a JavaScript `Date` reaches the database driver.
3
+ *
4
+ * Every `Date` this library binds is sent as `date.toISOString()`: an absolute
5
+ * instant in UTC (`2026-10-13T20:45:42.123Z`), which Postgres reads correctly
6
+ * into `timestamptz`, `timestamp` (the UTC wall-clock time, the same value
7
+ * Bun's prepared path stores) and `date` (the UTC calendar day), and which is
8
+ * what the libSQL driver already sent. An invalid `Date` throws here, naming
9
+ * the parameter, instead of reaching the database as the text "Invalid Date".
10
+ *
11
+ * Why it cannot be left to the driver:
12
+ *
13
+ * - Bun's Postgres driver with `prepare: false` (`pool.preparedStatements:
14
+ * false`) sends a `Date` as `String(date)`, e.g. `Tue Oct 13 2026 20:45:42
15
+ * GMT+0000 (Coordinated Universal Time)`. Postgres refuses that for every
16
+ * temporal type (`invalid input syntax for type timestamp`, or `time zone
17
+ * "gmt-0700" not recognized` outside UTC).
18
+ * - With prepared statements on, a `Date` bound to a `date` parameter, or
19
+ * inside an array (`= ANY($1)`), fails the same way.
20
+ * - `bun:sqlite` binds a `Date` as NULL, silently.
21
+ *
22
+ * MySQL-family connections are left alone: their `DATETIME` literal cannot
23
+ * carry the `T`/`Z` of an ISO string (see `temporalLiteral` in client.ts).
24
+ */
25
+ /** One bound value, with any `Date` (also inside arrays) serialized. */
26
+ export declare function bindingValue(value: unknown, position?: number): unknown;
27
+ /**
28
+ * A parameter list with every `Date` serialized.
29
+ *
30
+ * Returns the SAME array when nothing needs changing, so the common case
31
+ * (no dates) allocates nothing and callers that compare or reuse the array
32
+ * see no difference.
33
+ */
34
+ export declare function serializeBindings<T extends readonly unknown[] | undefined | null>(params: T): T;
35
+ /**
36
+ * Wrap a Bun SQL Postgres connection so every statement it runs binds `Date`
37
+ * parameters as ISO strings, whatever path built the statement.
38
+ *
39
+ * Covers `unsafe(sql, params)`, tagged templates (`sql\`... ${date}\``), the
40
+ * helper (`sql({ at: date })`, `sql([row, row])`, an IN list `sql([date, date])`),
41
+ * `array()`, `file()`, and the
42
+ * connections it hands out: `begin`/`transaction`/`savepoint`/
43
+ * `beginDistributed`/`distributed` callbacks and `reserve()`. Anything that is
44
+ * not a Bun Postgres connection (SQLite wrapper, MySQL, a test double) is
45
+ * returned unchanged, and wrapping twice is a no-op.
46
+ */
47
+ export declare function withDateBindings<T>(connection: T): T;
48
+ /** A Bun SQL connection: callable (tagged template, helper) with methods. */
49
+ declare type DriverFunction = Function & Record<PropertyKey, any>;
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{p,B,n,e,t,s,Le,T,r,m,Gt,E,l,ee,We,Ue}from"./chunk-96qkj2sc.js";import{Buffer as Bt}from"buffer";import{serialize as Ft}from"v8";function Wt(w){return m(e.relations?.singularizeStrategy)(w)}function x(w,R,S,H={}){let ae=H.singularize??Wt,le=w.relations?.[R]?.belongsToMany?.[S];if(le==null)return null;let ke=typeof le==="object",Se=ke?le:null,pe=ke?Se.model:le,Ge=w.modelToTable[pe]||pe,Ye,nt;if(Se?.table)Ye=Se.table;else if(Se?.through){if(nt=Se.through,Ye=w.modelToTable[Se.through],!Ye)throw Error(`[query-builder] belongsToMany relation '${S}' on '${R}' references unknown through model '${Se.through}'. Make sure '${Se.through}' is registered via defineModels({...}).`)}else{let je=ae(R),g=ae(Ge);Ye=[je,g].sort().join("_")}let rt=Se?.foreignKey??`${ae(R)}_id`,yt=Se?.relatedKey??`${ae(Ge)}_id`,se={};if(Se?.pivot?.columns)Object.assign(se,Se.pivot.columns);if(nt&&H.models){let je=H.models[nt],g=je?.definition??je?.getDefinition?.()??je,f=g?.attributes??{};for(let[d,y]of Object.entries(f)){if(d===rt||d===yt||d===(g?.primaryKey??"id"))continue;se[d]={default:y?.default,nullable:y?.nullable,validation:y?.validation}}}let ve=Boolean(Se?.pivot?.timestamps),Ce=Object.keys(se);return{pivotTable:Ye,fkParent:rt,fkRelated:yt,pivotColumns:Ce,pivotColumnDefs:se,pivotModelName:nt,timestamps:ve,relatedModelName:pe,relatedTable:Ge,hasConfig:ke}}function*Kn(w,R={}){let S=w.relations;if(!S)return;for(let[H,ae]of Object.entries(S)){let A=ae?.belongsToMany;if(!A)continue;for(let le of Object.keys(A)){let ke=x(w,H,le,R);if(ke)yield{parentTable:H,relationKey:le,resolved:ke}}}}function _e(w){return typeof w==="object"&&w!==null&&"raw"in w&&typeof w.raw==="string"}function St(w,R,S){if(Array.isArray(R)){let ae=s(R.length,S.length+1),A=l(w,R,!1,ae);return S.push(...R),A}let H=`${w} = ${t(S.length+1)}`;return S.push(R),H}function ze(w){return typeof w==="object"&&w!==null&&"sql"in w&&typeof w.sql==="string"&&(!("parameters"in w)||Array.isArray(w.parameters))}function Jt(w,R){let[S,...H]=R;if(H.length>0||S!==void 0&&!Array.isArray(S))throw TypeError("[query-builder] db.raw(sql, bindings): pass the bindings as one array, db.raw('a = ? AND b = ?', [a, b]).");let ae={sql:w,parameters:[...S??[]]};return Object.defineProperty(ae,"then",{enumerable:!1,value:(A,le)=>{let ke=TypeError("[query-builder] db.raw(sql, bindings) builds a fragment for set() or where(), not a query. Run SQL with db.unsafe(sql, params).");if(typeof le==="function")return le(ke);throw ke}}),ae}function ut(w){return w instanceof Promise&&typeof w.execute==="function"&&typeof w.cancel==="function"}function ct(w){throw TypeError(`[query-builder] ${w}: a Bun \`sql\`...\`\` query cannot be used as a fragment, because its SQL text is not readable. Bind values with db.raw('name = ?', [value]) or { sql, parameters }, or use the exported \`raw\` tagged template.`)}function Xe(w,R){let S=w.parameters??(Array.isArray(w.values)?w.values:[]);if(e.dialect!=="postgres"||S.length===0)return{text:w.sql,parameters:S};let H=0,{text:ae}=We(w.sql,()=>H<S.length?t(R+H++):void 0);if(H!==S.length)throw TypeError(`[query-builder] SQL expression declares ${S.length} parameters but contains only ${H} placeholders`);return{text:ae,parameters:S}}function Ot(w,R){if(R.length===2){let[S,H]=R;if(Array.isArray(H)&&typeof S==="number"&&H[S]===w)return!1;if(H instanceof Set&&S===w&&H.has(w))return!1;if(H instanceof Map&&H.get(S)===w)return!1}return R.some((S)=>S!==void 0&&!(Array.isArray(S)&&S.length===0))}function nn(w,...R){if(typeof w==="string"){if(!(R.length===1&&Number.isInteger(R[0])&&R[0]>=0&&!w.includes("?"))&&Ot(w,R))throw TypeError("[query-builder] raw(string) takes no values, so the argument(s) after the string would be dropped. Use raw as a tagged template instead, which interpolates each value as an escaped literal.");return{raw:w}}let S=w[0];for(let H=0;H<R.length;H++)S+=He(R[H])+w[H+1];return{raw:S}}function Re(w){return n(e.dialect)?`\`${w.replace(/`/g,"``")}\``:`"${w.replace(/"/g,'""')}"`}function mt(w,R=1){let S=Object.keys(w[0]??{}),H=[],ae=R,A=w.map((le)=>`(${S.map((Se)=>(H.push(le[Se]),t(ae++))).join(", ")})`);return{colsSql:S.map(Re).join(", "),valuesSql:A.join(", "),params:H,nextIndex:ae}}function dt(w){return Boolean(w&&(w.onSlowQuery||w.slowQueryThresholdMs!=null&&w.slowQueryThresholdMs>=0))}function c(w,R=e.dialect){if(!n(R))return w;let S=/^([A-Z_][\w$]*)(?:\.([A-Z_][\w$]*))?(?:\s+as\s+([A-Z_][\w$]*))?$/i.exec(w.trim());if(!S)return w;let[,H,ae,A]=S,le=ae?`\`${H}\`.\`${ae}\``:`\`${H}\``;return A?`${le} AS \`${A}\``:le}function At(w,R=e.dialect){if(!n(R)||w===null||w===void 0)return w;if(typeof w==="string"){let S=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(w);if(!S)return w;let[,H,ae]=S;return`${H} ${ae.length===5?`${ae}:00`:ae}`}if(!(w instanceof Date)||Number.isNaN(w.getTime()))return w;return w.toISOString().replace("T"," ").replace(/\.\d+Z$/,"")}function Dt(w){if(typeof w==="string")return c(w);if(_e(w))return w.raw;if(w&&typeof w==="object"){let R=w;if(typeof R.raw==="function")return String(R.raw());if(typeof R.sql==="string")return R.sql;let S=String(w);if(S!=="[object Object]")return S}throw TypeError(`[query-builder] select(): unsupported column ${String(w)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function Kt(w){let R=/\(|\)|\bORDER\s+BY\b/gi,S=0,H;while(H=R.exec(w))if(H[0]==="(")S++;else if(H[0]===")")S=Math.max(0,S-1);else if(S===0)return!0;return!1}var he={SELECT_STAR:/^SELECT\s+\*/i,SELECT:/^SELECT\s+/i,SELECT_FROM:/^SELECT\s+(.+?)\s+FROM/i,WHERE:/\bWHERE\b/i,ORDER_BY:/\bORDER\s+BY\b/i,GROUP_BY:/\bGROUP\s+BY\b/i,LIMIT:/\sLIMIT\s+\d+/i,OFFSET:/\sOFFSET\s+\d+/i,IDENTIFIER:/^[A-Z_][\w.]*$/i,DELETED_AT:/\bdeleted_at\b/i},Et=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function K(w,R){if(!he.IDENTIFIER.test(w)){let S=R?` in ${R}`:"";throw Error(`[query-builder] Invalid identifier${S}: '${w}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function De(w,R){if(typeof w!=="string")throw TypeError(`[query-builder] ${R}: operator must be a string, got ${typeof w}`);let S=w.toLowerCase();if(!Et.has(S))throw TypeError(`[query-builder] ${R}: refusing to use '${w}' as a SQL operator \u2014 not in the allowed set (${[...Et].join(", ")})`);return w}function Ve(w,R,S,H){let ae=R.toLowerCase();if(ae!=="is"&&ae!=="is not")return null;if(S!==null&&S!==void 0)throw TypeError(`[query-builder] ${H}: operator '${R}' only accepts NULL/undefined as value, got ${typeof S} (${String(S)})`);return`${w} IS ${ae==="is not"?"NOT ":""}NULL`}function Qe(w,R){if(typeof w!=="string"||w.length===0)throw TypeError(`[query-builder] ${R}: identifier must be a non-empty string, got ${typeof w}`);if(w.length>129)throw TypeError(`[query-builder] ${R}: identifier '${w}' too long`);let S=w.split(".");if(S.length>2)throw TypeError(`[query-builder] ${R}: identifier '${w}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let H of S)if(!/^[A-Z_][A-Z0-9_]*$/i.test(H))throw TypeError(`[query-builder] ${R}: identifier segment '${H}' contains characters outside [A-Za-z0-9_]`)}function Ze(w,R,S=[]){let H=typeof w==="object"&&w!==null?w.parameters??w.values:void 0;if(Ot(w,S)||Array.isArray(H)&&H.length>0){let ae=R.startsWith("whereRaw(")?", or use where(). Model.query().whereRaw(sql, ...bindings) is the builder that binds `?` values.":R.startsWith("orWhereRaw(")?", or use orWhere(). Model.query().orWhereRaw(sql, ...bindings) is the builder that binds `?` values.":".";throw TypeError(`[query-builder] ${R}: this method takes a single fragment and no bindings, so the argument(s) after it would be dropped. Interpolate values with the exported \`raw\` tagged template, which inlines them as escaped literals${ae}`)}if(typeof w==="string")return jt(R),w;if(w===null||w===void 0)throw TypeError(`[query-builder] ${R}: fragment must be a SqlFragment, got ${w}`);if(_e(w))return w.raw;if(typeof w==="object"){let ae=w;if(typeof ae.raw==="string")return ae.raw;if(typeof ae.raw==="function"){let le=ae.raw();if(typeof le==="string")return le}if(typeof ae.sql==="string")return ae.sql;let A=String(w);if(A!=="[object Object]"&&A!=="[object Promise]")return A}throw TypeError(`[query-builder] ${R}: cannot render this value as a SQL fragment. `+"A Bun `sql`...`` query object cannot be converted to SQL text \u2014 pass a "+"string, or use the exported `raw` helper: raw`count(*) as c` / raw('age > 18').")}function _t(w,R){if(!R||R.length===0)return;if(e.dialect!=="postgres")return;if(/\$\d/.test(w))return;let S=ee(w),H=`${R.length} binding${R.length===1?"":"s"}`,ae=S>0?`the query binds them with ${S} \`?\` placeholder${S===1?"":"s"}, which Postgres reads as an operator rather than a parameter`:"the query contains no $n placeholder for them to bind to";throw TypeError(`[query-builder] unsafe(): ${H} supplied, but ${ae}. Postgres numbers `+"its parameters, so write $1, $2 \u2026 in the order the bindings should bind: "+"unsafe('SELECT * FROM users WHERE email = $1 LIMIT 1', [email]). `?` is correct on SQLite and MySQL, which is why this call may work there.")}var Rt=new Set;function jt(w){if(Rt.has(w))return;Rt.add(w),console.warn(`[query-builder] ${w}: bare string passed to a *Raw method. Prefer the \`raw\`...\`\` tagged template, which escapes interpolated `+"values for the configured dialect \u2014 concatenating request input into SQL "+"is an injection vector. This will become a hard error in a future release.")}function Nt(w,R=e.dialect){return n(R)?w.replace(/\\/g,"\\\\").replace(/'/g,"''"):w.replace(/'/g,"''")}function He(w){if(w===null)return"NULL";if(typeof w==="number"&&Number.isFinite(w))return String(w);if(typeof w==="boolean")return w?"1":"0";if(typeof w==="string")return`'${Nt(w)}'`;if(w instanceof Date)return`'${w.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof w}`)}function Ut(w,R){let S=Array.isArray(w)?w:w?[w]:[],H=[];if(S.length)H.push(`PARTITION BY ${S.join(", ")}`);if(R&&R.length)H.push(`ORDER BY ${R.map(([ae,A])=>`${ae} ${A==="desc"?"DESC":"ASC"}`).join(", ")}`);return H.length?`OVER (${H.join(" ")})`:"OVER ()"}class It{cache=new Map;maxSize=100;get(w){let R=this.cache.get(w);if(!R)return null;if(Date.now()>R.expiresAt)return this.cache.delete(w),null;return this.cache.delete(w),this.cache.set(w,R),R.data}set(w,R,S){if(this.cache.has(w))this.cache.delete(w);if(this.cache.size>=this.maxSize){let H=Date.now(),ae=!1;for(let[A,le]of this.cache)if(H>le.expiresAt){if(this.cache.delete(A),ae=!0,this.cache.size<this.maxSize)break}if(!ae){let A=this.cache.keys().next().value;if(A!==void 0)this.cache.delete(A)}}this.cache.set(w,{data:R,expiresAt:Date.now()+S})}clear(){this.cache.clear()}setMaxSize(w){this.maxSize=Math.max(0,Math.floor(w));while(this.cache.size>this.maxSize){let R=this.cache.keys().next().value;if(R===void 0)break;this.cache.delete(R)}}}var wt=new It,kt=new WeakMap,Ht=0;function Vt(w,R,S){let H=kt.get(w);if(H===void 0)H=++Ht,kt.set(w,H);let ae=S.map((A)=>ArrayBuffer.isView(A)?["view",Bt.isBuffer(A)?"Buffer":Object.prototype.toString.call(A),Bt.from(A.buffer,A.byteOffset,A.byteLength).toString("base64")]:["value",Ft(A).toString("base64")]);return`${H}\x00${R}\x00${JSON.stringify(ae)}`}function Yt(w){let R=String(w?.message||"").toLowerCase();return R.includes("deadlock")||R.includes("serialization failure")||R.includes("could not serialize access")||R.includes("deadlock found when trying to get lock")||R.includes("lock wait timeout exceeded")||R.includes("database is locked")||R.includes("busy")}function zt(w,R){if(!R||R.length===0)return!1;let S=w&&(w.code||w.sqlState||w.sqlstate);if(!S)return!1;return R.includes(S)}function Xt(w){return new Promise((R)=>setTimeout(R,w))}var pt=new Map,Zt=500,en=[{key:"GROUP_BY",pattern:/GROUP\s+BY\b/iy},{key:"ORDER_BY",pattern:/ORDER\s+BY\b/iy},{key:"HAVING",pattern:/HAVING\b/iy},{key:"OFFSET",pattern:/OFFSET\b/iy},{key:"LIMIT",pattern:/LIMIT\b/iy},{key:"WHERE",pattern:/WHERE\b/iy}],tn=[{key:"tail",pattern:/GROUP\s+BY\b/iy},{key:"tail",pattern:/ORDER\s+BY\b/iy},{key:"tail",pattern:/HAVING\b/iy},{key:"tail",pattern:/LIMIT\b/iy},{key:"tail",pattern:/OFFSET\b/iy},{key:"tail",pattern:/WINDOW\b/iy},{key:"tail",pattern:/UNION\b/iy},{key:"tail",pattern:/INTERSECT\b/iy},{key:"tail",pattern:/EXCEPT\b/iy},{key:"tail",pattern:/FOR\s+UPDATE\b/iy},{key:"tail",pattern:/FOR\s+SHARE\b/iy},{key:"tail",pattern:/LOCK\s+IN\s+SHARE\s+MODE\b/iy}],rn=[{key:"cut",pattern:/GROUP\s+BY\b/iy},{key:"cut",pattern:/ORDER\s+BY\b/iy},{key:"cut",pattern:/WHERE\b/iy},{key:"cut",pattern:/HAVING\b/iy},{key:"cut",pattern:/LIMIT\b/iy},{key:"cut",pattern:/OFFSET\b/iy},{key:"cut",pattern:/UNION\b/iy}];function et(w){let R=pt.get(w);if(R!==void 0)return R;let S=sn(w);if(pt.size>=Zt)pt.clear();return pt.set(w,S),S}function sn(w){let R=Ue(w,en);if(R.length<=1)return w;let S=w.slice(0,R[0].start).trimEnd(),H={};for(let le=0;le<R.length;le++){let ke=R[le].start,Se=le+1<R.length?R[le+1].start:w.length,pe=w.slice(ke,Se).trim();if(!H[R[le].key])H[R[le].key]=[];H[R[le].key].push(pe)}let A=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((le)=>H[le]).map((le)=>H[le].join(" ")).join(" ");return A?`${S} ${A}`:S}function an(w,R){let S=Math.max(1,R?.baseMs??50),H=Math.max(1,R?.factor??2),ae=Math.max(S,R?.maxMs??2000),A=Math.min(ae,S*H**Math.max(0,w-1));if(R?.jitter)A=Math.min(ae,A*(0.9+Math.random()*0.2));return Math.floor(A)}function i(w){let R=B(w?.sql??T()),S=w?.meta,H=w?.schema,ae;function A(g,f){let d=R.unsafe(g,f);if(typeof d.sql!=="string")ae??=new WeakMap,ae.set(d,{sql:g,params:f?.slice()});return d}let le,ke=(g,f)=>{let d=S?.temporalColumns?.[g];if(!d||d.length===0||!n(e.dialect))return f;return f.map((y)=>{let I=null;for(let b of d){if(!(b in y))continue;let X=At(y[b]);if(X!==y[b])I=I??{...y},I[b]=X}return I??y})};function Se(g){if(typeof g==="number")return g;let f=String(g),d=7;for(let y=0;y<f.length;y++)d=d*31+f.charCodeAt(y)|0;return Math.abs(d)}function pe(){if(!w?.hooks)return e.hooks;return{...e.hooks,...w.hooks}}let Ge=new Map;function Ye(g){if(Array.isArray(g)){let[b,X,W]=g;K(b,"where(column)");let j=String(b);switch(X){case"in":if(Array.isArray(W)){let v=s(W.length);return A(`${j} IN (${v})`,W)}return A(`${j} IN (${t(1)})`,[W]);case"not in":if(Array.isArray(W)){let v=s(W.length);return A(`${j} NOT IN (${v})`,W)}return A(`${j} NOT IN (${t(1)})`,[W]);case"like":return A(`${j} LIKE ${t(1)}`,[W]);case"is":case"is not":{if(W!==null&&W!==void 0)throw TypeError(`[query-builder] where(..., '${X}', ?): operator '${X}' only accepts NULL/undefined as value, got ${typeof W} (${String(W)})`);return A(`${j} IS ${X==="is not"?"NOT ":""}NULL`)}case"!=":return A(`${j} <> ${t(1)}`,[W]);case"<":case">":case"<=":case">=":case"=":return A(`${j} ${X} ${t(1)}`,[W]);default:throw TypeError(`[query-builder] where(..., '${String(X)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in g)return g.raw;let f=Object.keys(g);if(f.length===0)return A("");let d=[],y=[],I=1;for(let b of f){K(b,"where(object key)");let X=g[b];if(Array.isArray(X)){let W=s(X.length,I);d.push(`${b} IN (${W})`),y.push(...X),I+=X.length}else d.push(`${b} = ${t(I++)}`),y.push(X)}return A(d.join(" AND "),y)}function nt(g,f,d){if(!d)return f;let y=Ye(d);return R`${f} WHERE ${y}`}function rt(g){let f=ae?.get(g);if(f)return f.sql;let d=e.debug?.captureText;if(e.debug)e.debug.captureText=!0;let y=String(g);if(e.debug)e.debug.captureText=d;return y}function yt(g){let f=ae?.get(g);if(f)return f.params;if(!g||typeof g!=="object")return;if(Array.isArray(g.values))return g.values;if(Array.isArray(g.parameters))return g.parameters;if(Array.isArray(g.params))return g.params;return}function se(g,f,d){let y=pe(),I=y?.slowQueryThresholdMs,b=I!=null&&I>=0,X=Boolean(y?.onSlowQuery||b),W=y&&(y.onQueryStart||y.onQueryEnd||y.onQueryError||y.startSpan||X),j=d?.timeoutMs&&d.timeoutMs>0||d?.signal;if(!W&&!j)return g.execute();let v=rt(g),k=yt(g),_=Date.now(),O;try{if(y?.onQueryStart?.({sql:v,params:k,kind:f}),y?.startSpan)O=y.startSpan({sql:v,params:k,kind:f})}catch{}let L=!1,V=(Y,ne,F=Boolean(Y))=>{if(L)return;L=!0;let G=Date.now()-_;try{if(F)y?.onQueryError?.({sql:v,params:k,error:Y,durationMs:G,kind:f});else if(y?.onQueryEnd?.({sql:v,params:k,durationMs:G,rowCount:ne,kind:f}),b&&G>=I)if(y?.onSlowQuery)y.onSlowQuery({sql:v,params:k,durationMs:G,kind:f});else console.warn(`[query-builder] slow query (${G}ms >= ${I}ms): ${v}`)}catch{}try{O?.end(Y)}catch{}};if(typeof g.executeSync==="function"){let Y,ne,F=!1;try{Y=g.executeSync()}catch(re){ne=re,F=!0}if(d?.signal?.aborted){try{g.cancel?.()}catch{}ne=Object.assign(Error("Query aborted"),{code:"EBQBABORT"}),F=!0}if(F)return V(ne,void 0,!0),Promise.reject(ne);let G=Array.isArray(Y)?Y.length:typeof Y==="number"?Y:void 0;return V(void 0,G),Promise.resolve(Y)}let J=g.execute(),U=[J],z;if(d?.timeoutMs&&d.timeoutMs>0){let Y=new Promise((ne,F)=>{z=setTimeout(()=>{try{g.cancel?.()}catch{}let G=Error(`Query timed out after ${d.timeoutMs}ms`);G.code="EBQBTIMEOUT",F(G)},d.timeoutMs)});U.push(Y)}if(d?.signal){if(d.signal.aborted){try{g.cancel?.()}catch{}let ne=Error("Query aborted");return ne.code="EBQBABORT",V(ne),Promise.reject(ne)}let Y=()=>{try{g.cancel?.()}catch{}};d.signal.addEventListener("abort",Y,{once:!0}),J.finally(()=>{d.signal?.removeEventListener("abort",Y)})}return Promise.race(U).then((Y)=>{clearTimeout(z);let ne=Array.isArray(Y)?Y.length:typeof Y==="number"?Y:void 0;return V(void 0,ne),Y}).catch((Y)=>{throw clearTimeout(z),V(Y),Y})}function ve(g){if(typeof g==="number")return Number.isFinite(g)?g:0;if(typeof g==="bigint")return Number(g);if(!g||typeof g!=="object")return 0;let f=g;for(let d of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(f[d]!==void 0&&f[d]!==null)return ve(f[d]);if(Array.isArray(g))return g.reduce((d,y)=>d+ve(y),0);return 0}function Ce(g,f){let d=f??rt(g);return{sql:d,toString:()=>d,execute:()=>g.execute(),values:()=>g.values(),raw:()=>g.raw()}}function je(g,f){let d=R,y=f&&f.length>0?`SELECT ${f.join(", ")} FROM ${String(g)}`:`SELECT * FROM ${String(g)}`,I=[],b=[],X=!1,W=!1,j=!1,v=null,k=()=>{if(v===null){let a=et(J());v=b.length>0?A(a,b):A(a)}return v},_=(a="",o="",u=[])=>A(`${a}${et(J())}${o}`,[...b,...u]),O=(a,o)=>{I.push({conn:a,sql:o}),v=null},L=(a,o)=>{O(a==="OR"?"OR":"AND",o)},V=(a)=>{let o=Ue(a,tn,1);return o.length>0?o[0].start:-1},J=(a)=>{let o=E(a?[...I,a]:I);if(!o)return y;if(X)return`${y} ${W?"AND":"WHERE"} ${o}`;let u=V(y);return u>=0?`${y.slice(0,u)}WHERE ${o} ${y.slice(u)}`:`${y} WHERE ${o}`},U=(a,o,u,h)=>{let D=typeof u?.__sqlState==="function"?u.__sqlState():void 0,N;if(D){let q=b.length;N=q>0&&e.dialect==="postgres"?D.sql.replace(/\$(\d+)/g,(P,M)=>`$${Number(M)+q}`):D.sql,b.push(...D.params)}else N=String(u.toSQL());O(a,`${o} ${h?"NOT IN":"IN"} (${N})`)},z=(a,o)=>{let u=je(g);o(u);let h=u.__whereState?.();if(!h||!h.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let D=b.length,N=D>0&&e.dialect==="postgres"?h.body.replace(/\$(\d+)/g,(q,P)=>`$${Number(P)+D}`):h.body;b.push(...h.params),O(a,`(${N})`)},Y=(a,o,u,h,D,N)=>{if(typeof h==="string"&&D!==void 0){K(String(h),`${u}(column)`),De(D,`${u}(operator)`);let q=Ve(String(h),String(D),N,u);if(q)return O(o,q),a;let P=b.length+1;return b.push(N),O(o,`${String(h)} ${String(D)} ${t(P)}`),a}if(Array.isArray(h)){let[q,P,M]=h,C=String(q);K(C,`${u}(column)`);let Q=De(P,`${u}(operator)`);if(Q==="in"||Q==="not in"){let Z=Array.isArray(M)?M:[M],ie=s(Z.length,b.length+1),$e=l(c(C),Z,Q==="not in",ie);b.push(...Z),O(o,$e)}else{let Z=Ve(C,Q,M,u);if(Z)return O(o,Z),a;let ie=b.length+1;b.push(M),O(o,`${C} ${Q} ${t(ie)}`)}return a}if(typeof h==="function")return z(o,h),a;if(ut(h))ct(`${u}(expr)`);if(ze(h)){let q=Xe(h,b.length+1);return b.push(...q.parameters),O(o,q.text),a}if(h&&typeof h==="object"&&!("raw"in h)){let q=[];for(let P of Object.keys(h)){K(P,`${u}(column)`);let M=h[P];if(Array.isArray(M)){let C=s(M.length,b.length+1);q.push(l(c(P),M,!1,C)),b.push(...M)}else{let C=b.length+1;q.push(`${P} = ${t(C)}`),b.push(M)}}if(q.length>0)O(o,q.length>1?`(${q.join(" AND ")})`:q[0]);return a}if(h&&typeof h.raw<"u")return O(o,h.raw),a;return a},ne=(a,o)=>{if(I.length>0)y=J(),I.length=0;X=!0;let u=o.__rawState?.();if(u){let h=b.length,D=e.dialect==="postgres"?u.sql.replace(/\$(\d+)/g,(N,q)=>`$${Number(q)+h}`):u.sql;y+=` ${a} ${D}`,b.push(...u.params),W=o.__hasPredicate?.()??he.WHERE.test(D)}else{let h=String(o.toSQL());y+=` ${a} ${h}`,W=o.__hasPredicate?.()??he.WHERE.test(h)}v=null},F=(a)=>{let o=Ue(y,rn,1),u=o.length>0?o[0].start:-1;y=u>=0?`${y.slice(0,u)}${a} ${y.slice(u)}`:`${y} ${a}`,v=null},G=new Set,re,te,ye=!1,we=!1,xe=!1,Pe=new Map,Fe=new Set,Tt=60000,fe=(a)=>m(e.relations.singularizeStrategy)(a),qe=(a)=>{if(!S)return null;return x(S,String(g),a,{singularize:fe,models:S.models})},st=(a)=>{if(!a||typeof a!=="object"||Fe.size===0)return a;let o;for(let u of Object.keys(a))if(u.startsWith("pivot_")){if(!o)o={};o[u.slice(6)]=a[u],delete a[u]}if(o)a.pivot=o;return a},at=(a)=>{if(Fe.size===0||!a)return a;if(Array.isArray(a))for(let o=0;o<a.length;o++)st(a[o]);else st(a);return a},ot=(a)=>{if(!S)return;if(G.has(a.pivotTable))return;let o=String(g),u=S.primaryKeys[o]??"id";K(a.pivotTable,"wherePivot auto-join (pivot table)"),K(a.fkParent,"wherePivot auto-join (parent FK)"),K(o,"wherePivot auto-join (parent table)"),K(u,"wherePivot auto-join (parent PK)"),v=d`${k()} LEFT JOIN ${d(a.pivotTable)} ON ${d(`${a.pivotTable}.${a.fkParent}`)} = ${d(`${o}.${u}`)}`,y=`${y} LEFT JOIN ${a.pivotTable} ON ${a.pivotTable}.${a.fkParent} = ${o}.${u}`,G.add(a.pivotTable)},it=(a)=>{if(he.SELECT_STAR.test(y))y=y.replace(he.SELECT_STAR,`SELECT *, ${a}`);else if(he.SELECT.test(y))y=y.replace(he.SELECT_FROM,`SELECT $1, ${a} FROM`);let o=String(k());if(he.SELECT_STAR.test(o)){let u=o.replace(he.SELECT_STAR,`SELECT *, ${a}`);v=A(u)}else if(he.SELECT.test(o)){if(he.SELECT_FROM.exec(o)){let h=o.replace(he.SELECT_FROM,`SELECT $1, ${a} FROM`);v=A(h)}}},Je=(a,o,u,h)=>{it(`${a} ${Ut(u,h)} AS ${o}`)},ht=(a,o,u,h)=>{K(a,"relationship subquery (parent table)"),K(o,"relationship subquery (target table)"),K(u,"relationship subquery (primary key)");let D=`${a.endsWith("s")?a.slice(0,-1):a}_id`;K(D,"relationship subquery (foreign key)");let N=`SELECT 1 FROM ${o} WHERE ${o}.${D} = ${a}.${u}`;if(h){let P=h({where:(M,C,Q)=>(K(M,"relationship subquery condition"),`${o}.${M} ${De(C,"whereHas callback")} ${He(Q)}`)});if(P)N+=` AND ${P}`}return N},gt=(a,o,u,h)=>{K(a,"relationship subquery (parent table)"),K(o,"relationship subquery (target table)"),K(u,"relationship subquery (primary key)");let D=`${o.endsWith("s")?o.slice(0,-1):o}_id`;K(D,"relationship subquery (foreign key)");let N=`SELECT 1 FROM ${o} WHERE ${o}.${u} = ${a}.${D}`;if(h){let P=h({where:(M,C,Q)=>(K(M,"relationship subquery condition"),`${o}.${M} ${De(C,"whereHas callback")} ${He(Q)}`)});if(P)N+=` AND ${P}`}return N},ft=(a,o,u,h,D,N)=>{K(a,"relationship subquery (parent table)"),K(o,"relationship subquery (target table)"),K(u,"relationship subquery (primary key)"),K(h,"relationship subquery (target primary key)");let q=N&&S?x(S,a,N,{singularize:fe,models:S.models}):null,P=fe(a),M=fe(o),C=q?.pivotTable??[P,M].sort().join("_"),Q=q?.fkParent??`${P}_id`,Z=q?.fkRelated??`${M}_id`;K(C,"relationship subquery (pivot table)"),K(Q,"relationship subquery (foreign key A)"),K(Z,"relationship subquery (foreign key B)");let ie=`SELECT 1 FROM ${C} JOIN ${o} ON ${o}.${h} = ${C}.${Z} WHERE ${C}.${Q} = ${a}.${u}`;if(D){let oe=D({where:(Be,Oe,Ae)=>(K(Be,"relationship subquery condition"),`${o}.${Be} ${De(Oe,"whereHas callback")} ${He(Ae)}`)});if(oe)ie+=` AND ${oe}`}return ie},xt=(a,o,u)=>{K(a,"withCount (parent table)"),K(o,"withCount (target table)"),K(u,"withCount (primary key)");let h=`${a.endsWith("s")?a.slice(0,-1):a}_id`;return K(h,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${o} WHERE ${o}.${h} = ${a}.${u})`},Lt=(a,o,u,h)=>{K(a,"withCount (parent table)"),K(o,"withCount (target table)"),K(u,"withCount (primary key)");let D=h&&S?x(S,a,h,{singularize:fe,models:S.models}):null,N=fe(a),q=fe(o),P=D?.pivotTable??[N,q].sort().join("_"),M=D?.fkParent??`${N}_id`;return K(P,"withCount (pivot table)"),K(M,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${P} WHERE ${P}.${M} = ${a}.${u})`},bt=(a,o,u)=>{if(!S)return;K(u,`with${a[0]}${a.slice(1).toLowerCase()} (column)`);let h=String(g),D=S.relations?.[h];if(!D)return;let N=Object.entries(D).find(([oe,Be])=>Be&&typeof Be==="object"&&(o in Be));if(!N)return;let[q,P]=N,M=P[o],C=typeof M==="string"?M:M?.model||M?.target||M,Q=S.modelToTable[C]||C,Z=S.primaryKeys[h]??"id";K(Q,`with${a} (target table)`);let ie=`${a}(${Q}.${u})`,$e;if(q==="hasMany"||q==="hasOne"){let oe=`${h.endsWith("s")?h.slice(0,-1):h}_id`;K(oe,`with${a} (foreign key)`),$e=`(SELECT ${ie} FROM ${Q} WHERE ${Q}.${oe} = ${h}.${Z})`}else if(q==="belongsToMany"){let oe=S?x(S,h,o,{singularize:fe,models:S.models}):null,Be=fe(h),Oe=fe(Q),Ae=oe?.pivotTable??[Be,Oe].sort().join("_"),Ee=oe?.fkParent??`${Be}_id`,ue=oe?.fkRelated??`${Oe}_id`,lt=S.primaryKeys[Q]??"id";K(Ae,`with${a} (pivot table)`),K(Ee,`with${a} (foreign key)`),K(ue,`with${a} (related key)`),$e=`(SELECT ${ie} FROM ${Ae} JOIN ${Q} ON ${Q}.${lt} = ${Ae}.${ue} WHERE ${Ae}.${Ee} = ${h}.${Z})`}else return;it(`${$e} AS ${o}_${a.toLowerCase()}_${u}`)},$t=()=>{if(Pe.size===0)return;let a=[];for(let[o,u]of Pe.entries()){let h=qe(o);if(!h)continue;for(let N of u)K(N,"withPivot");let D=u.map((N)=>`${h.pivotTable}.${N} AS pivot_${N}`);a.push(...D)}if(a.length>0){let o=a.join(", ");it(o)}};return new Proxy({distinct(){return y=y.replace(/^SELECT\s+/i,"SELECT DISTINCT "),v=null,this},distinctOn(...a){let o=a.map(String).join(", ");return y=y.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${o}) `),v=null,this},selectRaw(a,...o){let u=Ze(a,"selectRaw(fragment)",o),h=y.indexOf(" FROM ");if(h!==-1)y=`${y.substring(0,h)}, ${u}${y.substring(h)}`;else y+=`, ${u}`;return v=null,this},rowNumber(a="row_number",o,u){let h=[];if(o){let P=Array.isArray(o)?o:[o];h.push(`PARTITION BY ${P.join(", ")}`)}if(u&&u.length)h.push(`ORDER BY ${u.map(([P,M])=>`${P} ${M==="desc"?"DESC":"ASC"}`).join(", ")}`);let N=`ROW_NUMBER() ${h.length?`OVER (${h.join(" ")})`:"OVER ()"} AS ${a}`,q=y.indexOf(" FROM ");if(q!==-1)y=`${y.substring(0,q)}, ${N}${y.substring(q)}`;else y+=`, ${N}`;return v=null,this},denseRank(a="dense_rank",o,u){let h=Array.isArray(o)?o:o?[o]:[],D=[];if(h.length)D.push(`PARTITION BY ${h.join(", ")}`);if(u&&u.length)D.push(`ORDER BY ${u.map(([M,C])=>`${M} ${C==="desc"?"DESC":"ASC"}`).join(", ")}`);let q=`DENSE_RANK() ${D.length?`OVER (${D.join(" ")})`:"OVER ()"} AS ${a}`,P=y.indexOf(" FROM ");if(P!==-1)y=`${y.substring(0,P)}, ${q}${y.substring(P)}`;else y+=`, ${q}`;return v=null,this},rank(a="rank",o,u){let h=Array.isArray(o)?o:o?[o]:[],D=[];if(h.length)D.push(`PARTITION BY ${h.join(", ")}`);if(u&&u.length)D.push(`ORDER BY ${u.map(([M,C])=>`${M} ${C==="desc"?"DESC":"ASC"}`).join(", ")}`);let q=`RANK() ${D.length?`OVER (${D.join(" ")})`:"OVER ()"} AS ${a}`,P=y.indexOf(" FROM ");if(P!==-1)y=`${y.substring(0,P)}, ${q}${y.substring(P)}`;else y+=`, ${q}`;return v=null,this},over(a,o,u={}){return Je(a,o,u.partitionBy,u.orderBy),this},lag(a,o={}){let u=[a,String(o.offset??1)];if(o.defaultValue!==void 0)u.push(String(o.defaultValue));return Je(`LAG(${u.join(", ")})`,o.alias??`${a}_lag`,o.partitionBy,o.orderBy),this},lead(a,o={}){let u=[a,String(o.offset??1)];if(o.defaultValue!==void 0)u.push(String(o.defaultValue));return Je(`LEAD(${u.join(", ")})`,o.alias??`${a}_lead`,o.partitionBy,o.orderBy),this},sumOver(a,o={}){return Je(`SUM(${a})`,o.alias??`${a}_sum`,o.partitionBy,o.orderBy),this},avgOver(a,o={}){return Je(`AVG(${a})`,o.alias??`${a}_avg`,o.partitionBy,o.orderBy),this},countOver(a="*",o={}){return Je(`COUNT(${a})`,o.alias??"count_over",o.partitionBy,o.orderBy),this},minOver(a,o={}){return Je(`MIN(${a})`,o.alias??`${a}_min`,o.partitionBy,o.orderBy),this},maxOver(a,o={}){return Je(`MAX(${a})`,o.alias??`${a}_max`,o.partitionBy,o.orderBy),this},firstValue(a,o={}){return Je(`FIRST_VALUE(${a})`,o.alias??`${a}_first`,o.partitionBy,o.orderBy),this},lastValue(a,o={}){return Je(`LAST_VALUE(${a})`,o.alias??`${a}_last`,o.partitionBy,o.orderBy),this},selectAll(){return this},select(a){if(!a)return this;let o=Array.isArray(a)?a:[a];if(o.length===0)return this;let u=o.map(Dt),h=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(y),D=h?h[1]:"",N=y.indexOf(" FROM ");if(N!==-1)y=`SELECT ${D}${u.join(", ")}${y.substring(N)}`;else y=`SELECT ${D}${u.join(", ")} FROM ${g}`;return v=null,this},addSelect(...a){if(!a.length)return this;let o=a.map(Dt),u=y.indexOf(" FROM ");if(u!==-1)y=`${y.substring(0,u)}, ${o.join(", ")}${y.substring(u)}`;else y+=`, ${o.join(", ")}`;return v=null,this},with(...a){if(!S||!a||a.length===0)return this;let o=[];for(let C of a){if(!C)continue;if(typeof C==="string")o.push({name:C});else if(typeof C==="object"&&!Array.isArray(C))for(let[Q,Z]of Object.entries(C))if(typeof Z==="function")o.push({name:Q,callback:Z});else o.push({name:Q})}if(o.length===0)return this;let u=e.relations.maxEagerLoad??50;if(o.length>u)throw Error(`[query-builder] Too many relationships to eager load (${o.length}). Maximum allowed: ${u}`);let h=String(g),D=new Set,N=new Set,q=new Map,P=(C)=>{let Q=S.relations?.[C];if(!Q)return[];return[...Object.keys(Q.hasOne||{}),...Object.keys(Q.hasMany||{}),...Object.keys(Q.belongsTo||{}),...Object.keys(Q.belongsToMany||{}),...Object.keys(Q.hasOneThrough||{}),...Object.keys(Q.hasManyThrough||{}),...Object.keys(Q.morphOne||{}),...Object.keys(Q.morphMany||{}),...Object.keys(Q.morphToMany||{}),...Object.keys(Q.morphedByMany||{})]},M=(C,Q,Z=0,ie)=>{let $e=e.relations.maxDepth??10;if(Z>=$e)throw Error(`[query-builder] Maximum relationship depth (${$e}) exceeded at '${Q}'. Consider using separate queries or increasing maxDepth.`);let oe=S.relations?.[C];if(!oe)return C;let Be=(ce)=>{if(e.softDeletes?.enabled&&e.softDeletes?.defaultFilter){let de=e.softDeletes.column||"deleted_at";return` AND ${ce}.${de} IS NULL`}return""},Oe=(ce)=>{if(!ie)return"";let de=[],be=(Te,Ie,Ke)=>{K(String(Te),"with() constraint column");let tt=De(Ie,"with() constraint operator");de.push(`${ce}.${String(Te)} ${tt} ${He(Ke)}`)},ge=(Te)=>()=>{throw Error(`[query-builder] with('${Q}', ...): ${Te} is not supported inside a constraint callback on the JOIN-based builder \u2014 apply it to the outer query, or use the model layer's eager loading. (Silently ignoring it would return wrong data.)`)},me={where:(Te,Ie,Ke)=>{if(Array.isArray(Te))be(Te[0],Te[1],Te[2]);else if(Te&&typeof Te==="object")for(let tt of Object.keys(Te))be(tt,"=",Te[tt]);else if(Ie!==void 0&&Ke!==void 0)be(Te,Ie,Ke);else if(Ie!==void 0)be(Te,"=",Ie);return me},whereIn:(Te,Ie)=>(K(String(Te),"with() constraint column"),de.push(`${ce}.${String(Te)} IN (${Ie.map(He).join(", ")})`),me),whereNull:(Te)=>(K(String(Te),"with() constraint column"),de.push(`${ce}.${String(Te)} IS NULL`),me),whereNotNull:(Te)=>(K(String(Te),"with() constraint column"),de.push(`${ce}.${String(Te)} IS NOT NULL`),me),orderBy:ge("orderBy()"),limit:ge("limit()"),offset:ge("offset()"),take:ge("take()")};return ie(me),de.length?` AND ${de.join(" AND ")}`:""},Ae=()=>{let ce=(ge)=>{let me=ge?.[Q];return me?S.modelToTable[me]:void 0},de=(ge)=>{let me=ge?.[Q],Te=typeof me==="string"?me:me?.model;return Te?S.modelToTable[Te]:void 0},be=(ge)=>{let me=ge?.[Q];return me?.target?S.modelToTable[me.target]:void 0};return ce(oe?.hasOne)||ce(oe?.hasMany)||ce(oe?.belongsTo)||de(oe?.belongsToMany)||be(oe?.hasOneThrough)||be(oe?.hasManyThrough)||ce(oe?.morphOne)||ce(oe?.morphMany)||ce(oe?.morphToMany)||ce(oe?.morphedByMany)},Ee=Ae()??(S.modelToTable[Q]||S.tableToModel[Q]?S.modelToTable[Q]??Q:Q),ue=String(Ee);if(!Ee||!Ae()&&!S.modelToTable[Q]&&!S.tableToModel[Q]){let ce=P(C);if(ce.length>0&&!ce.includes(Q)){let de=` Available relationships: ${ce.join(", ")}`;throw Error(`[query-builder] Relationship '${Q}' not found on table '${C}'.${de}`)}}if(e.relations.detectCycles!==!1){let ce=`${C}->${ue}`;if(D.has(ce))throw Error(`[query-builder] Circular relationship detected: ${ce}. This would cause an infinite loop.`);D.add(ce)}if(!ue||ue===C)return C;let lt=oe?.hasOneThrough?.[Q]||oe?.hasManyThrough?.[Q];if(lt){let{through:ce,target:de}=lt,be=S.modelToTable[ce]||ce,ge=S.modelToTable[de]||de,me=S.primaryKeys[C]??"id",Te=S.primaryKeys[be]??"id",Ie=`${fe(C)}_id`,Ke=`${fe(be)}_id`;return F(`LEFT JOIN ${be} ON ${be}.${Ie} = ${C}.${me} LEFT JOIN ${ge} ON ${ge}.${Ke} = ${be}.${Te}`),G.add(be),G.add(ge),ge}if(Boolean(oe?.belongsToMany?.[Q])){let ce=x(S,C,Q,{singularize:fe,models:S.models}),de=ce?.pivotTable??[fe(C),fe(ue)].sort().join("_"),be=S.primaryKeys[C]??"id",ge=S.primaryKeys[ue]??"id",me=ce?.fkParent??`${fe(C)}_id`,Te=ce?.fkRelated??`${fe(ue)}_id`;return F(`LEFT JOIN ${de} ON ${de}.${me} = ${C}.${be} LEFT JOIN ${ue} ON ${ue}.${ge} = ${de}.${Te}${Oe(ue)}`),G.add(de),G.add(ue),ue}if(Boolean(oe?.morphToMany?.[Q])){let ce=Q,de=`${fe(ue)}_${ce}`,be=S.primaryKeys[C]??"id",ge=S.primaryKeys[ue]??"id",me=`${ce}_type`,Te=`${ce}_id`,Ie=`${fe(ue)}_id`,Ke=He(S.tableToModel[C]||C);return F(`LEFT JOIN ${de} ON ${de}.${Te} = ${C}.${be} AND ${de}.${me} = ${Ke} LEFT JOIN ${ue} ON ${ue}.${ge} = ${de}.${Ie}`),G.add(de),G.add(ue),ue}if(Boolean(oe?.morphedByMany?.[Q])){let ce=oe.morphedByMany?.[Q]||Q,de=S.modelToTable[ce]||ce,be=fe(C),ge=`${fe(de)}_${be}`,me=S.primaryKeys[C]??"id",Te=S.primaryKeys[de]??"id",Ie=`${be}_type`,Ke=`${be}_id`,tt=`${fe(de)}_id`,Mt=He(S.tableToModel[de]||de);return F(`LEFT JOIN ${ge} ON ${ge}.${tt} = ${C}.${me} LEFT JOIN ${de} ON ${de}.${Te} = ${ge}.${Ke} AND ${ge}.${Ie} = ${Mt}`),G.add(ge),G.add(de),de}if(Boolean(oe?.belongsTo?.[Q])){let ce=`${fe(ue)}_id`,de=S.primaryKeys[ue]??"id";return F(`LEFT JOIN ${ue} ON ${C}.${ce} = ${ue}.${de}${Oe(ue)}`),G.add(ue),ue}let Ct=Boolean(oe?.morphOne?.[Q]),Pt=Boolean(oe?.morphMany?.[Q]);if(Ct||Pt){let ce=`${Q}_type`,de=`${Q}_id`,be=S.primaryKeys[C]??"id",ge=He(S.tableToModel[C]||C);return F(`LEFT JOIN ${ue} ON ${ue}.${de} = ${C}.${be} AND ${ue}.${ce} = ${ge}`),G.add(ue),ue}let qt=`${fe(C)}_id`,Qt=S.primaryKeys[C]??"id",vt=`${Be(ue)}${Oe(ue)}`;return F(`LEFT JOIN ${ue} ON ${ue}.${qt} = ${C}.${Qt}${vt}`),G.add(ue),ue};for(let C of o){let Q=C.name.trim();if(C.callback)q.set(Q,C.callback);let Z=Q.split("."),ie=h,$e=0;for(let oe of Z){if(!oe||oe.trim().length===0)continue;let Be=oe.trim(),Oe=q.get(Be);ie=M(ie,Be,$e,Oe)||ie,$e++}N.add(Q)}if(Pe.size>0){let C=[];for(let[Q,Z]of Pe.entries()){let ie=qe(Q);if(!ie)continue;let $e=Z.map((oe)=>`${ie.pivotTable}.${oe} AS pivot_${oe}`);C.push(...$e)}if(C.length>0){let Q=C.join(", ");it(Q)}}return v=null,this},whereHas(a,o){if(!S)return this;let u=String(g),h=S.relations?.[u];if(!h)throw Error(`[query-builder] No relationships defined for table '${u}'`);let D=Object.entries(h).find(([Z,ie])=>ie&&typeof ie==="object"&&(a in ie));if(!D)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[N,q]=D,P=q[a],M=typeof P==="string"?P:P?.model||P?.target||P,C=S.modelToTable[M]||M,Q;if(N==="hasMany"||N==="hasOne"){let Z=S.primaryKeys[u]??"id";Q=ht(u,C,Z,o)}else if(N==="belongsTo"){let Z=S.primaryKeys[C]??"id";Q=gt(u,C,Z,o)}else if(N==="belongsToMany"){let Z=S.primaryKeys[u]??"id",ie=S.primaryKeys[C]??"id";Q=ft(u,C,Z,ie,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${N}' for whereHas`);return L("WHERE",`EXISTS (${Q})`),this},whereDoesntHave(a,o){if(!S)return this;let u=String(g),h=S.relations?.[u];if(!h)throw Error(`[query-builder] No relationships defined for table '${u}'`);let D=Object.entries(h).find(([Z,ie])=>ie&&typeof ie==="object"&&(a in ie));if(!D)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[N,q]=D,P=q[a],M=typeof P==="string"?P:P?.model||P?.target||P,C=S.modelToTable[M]||M,Q;if(N==="hasMany"||N==="hasOne"){let Z=S.primaryKeys[u]??"id";Q=ht(u,C,Z,o)}else if(N==="belongsTo"){let Z=S.primaryKeys[C]??"id";Q=gt(u,C,Z,o)}else if(N==="belongsToMany"){let Z=S.primaryKeys[u]??"id",ie=S.primaryKeys[C]??"id";Q=ft(u,C,Z,ie,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${N}' for whereDoesntHave`);return L("WHERE",`NOT EXISTS (${Q})`),this},has(a){if(!S)return this;let o=String(g),u=S.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let h=Object.entries(u).find(([Q,Z])=>Z&&typeof Z==="object"&&(a in Z));if(!h)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[D,N]=h,q=N[a],P=typeof q==="string"?q:q?.model||q?.target||q,M=S.modelToTable[P]||P,C;if(D==="hasMany"||D==="hasOne"){let Q=S.primaryKeys[o]??"id";C=ht(o,M,Q)}else if(D==="belongsTo"){let Q=S.primaryKeys[M]??"id";C=gt(o,M,Q)}else if(D==="belongsToMany"){let Q=S.primaryKeys[o]??"id",Z=S.primaryKeys[M]??"id";C=ft(o,M,Q,Z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${D}' for has`);return L("WHERE",`EXISTS (${C})`),this},doesntHave(a){if(!S)return this;let o=String(g),u=S.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let h=Object.entries(u).find(([Q,Z])=>Z&&typeof Z==="object"&&(a in Z));if(!h)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[D,N]=h,q=N[a],P=typeof q==="string"?q:q?.model||q?.target||q,M=S.modelToTable[P]||P,C;if(D==="hasMany"||D==="hasOne"){let Q=S.primaryKeys[o]??"id";C=ht(o,M,Q)}else if(D==="belongsTo"){let Q=S.primaryKeys[M]??"id";C=gt(o,M,Q)}else if(D==="belongsToMany"){let Q=S.primaryKeys[o]??"id",Z=S.primaryKeys[M]??"id";C=ft(o,M,Q,Z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${D}' for doesntHave`);return L("WHERE",`NOT EXISTS (${C})`),this},withCount(...a){if(!S||!a||a.length===0)return this;let o=String(g);for(let u of a){let h=S.relations?.[o];if(!h)continue;let D=Object.entries(h).find(([$e,oe])=>oe&&typeof oe==="object"&&(u in oe));if(!D)continue;let[N,q]=D,P=q[u],M=typeof P==="string"?P:P?.model||P?.target||P,C=S.modelToTable[M]||M,Q=S.primaryKeys[o]??"id",Z;if(N==="hasMany"||N==="hasOne")Z=xt(o,C,Q);else if(N==="belongsToMany")Z=Lt(o,C,Q,u);else continue;let ie=`${u}_count`;it(`${Z} AS ${ie}`)}return this},withSum(a,o){return bt("SUM",a,o),this},withAvg(a,o){return bt("AVG",a,o),this},withMax(a,o){return bt("MAX",a,o),this},withMin(a,o){return bt("MIN",a,o),this},applyPivotColumns(){return $t(),this},withPivot(a,...o){if(!S)return this;let u=String(g),h=qe(a);if(!h)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${u}'`);let D=o&&o.length>0?o:h.hasConfig?h.pivotColumns:[];if(D.length===0)return this;if(Pe.set(a,D),h.hasConfig)Fe.add(a);return $t(),this},wherePivot(a,o,u,h){if(!S)return this;let D=qe(a);if(!D)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(g)}'`);K(D.pivotTable,"wherePivot (pivot table)"),K(o,"wherePivot (column)"),ot(D);let N=h===void 0?"=":String(u),q=h===void 0?u:h,P=b.length+1,M=`${D.pivotTable}.${o} ${N} ${t(P)}`;if(b.push(q),O("AND",M),D.hasConfig)Fe.add(a);return this},wherePivotIn(a,o,u){if(!S||!Array.isArray(u))return this;let h=qe(a);if(!h)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(g)}'`);K(h.pivotTable,"wherePivotIn (pivot table)"),K(o,"wherePivotIn (column)"),ot(h);let D=s(u.length,b.length+1),N=l(`${h.pivotTable}.${o}`,u,!1,D);if(b.push(...u),O("AND",N),h.hasConfig)Fe.add(a);return this},wherePivotNotIn(a,o,u){if(!S||!Array.isArray(u)||u.length===0)return this;let h=qe(a);if(!h)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(g)}'`);K(h.pivotTable,"wherePivotNotIn (pivot table)"),K(o,"wherePivotNotIn (column)"),ot(h);let D=s(u.length,b.length+1),N=`${h.pivotTable}.${o} NOT IN (${D})`;if(b.push(...u),O("AND",N),h.hasConfig)Fe.add(a);return this},wherePivotNull(a,o){if(!S)return this;let u=qe(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(g)}'`);if(K(u.pivotTable,"wherePivotNull (pivot table)"),K(o,"wherePivotNull (column)"),ot(u),O("AND",`${u.pivotTable}.${o} IS NULL`),u.hasConfig)Fe.add(a);return this},wherePivotNotNull(a,o){if(!S)return this;let u=qe(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(g)}'`);if(K(u.pivotTable,"wherePivotNotNull (pivot table)"),K(o,"wherePivotNotNull (column)"),ot(u),O("AND",`${u.pivotTable}.${o} IS NOT NULL`),u.hasConfig)Fe.add(a);return this},where(a,o,u){if(typeof a==="string"&&o!==void 0){K(String(a),"where(column)"),De(o,"where(operator)");let h=String(o).toLowerCase();if(h==="in"||h==="not in"){let q=Array.isArray(u)?u:[u],P=s(q.length,b.length+1),M=l(c(String(a)),q,h==="not in",P);return b.push(...q),O("AND",M),this}let D=Ve(c(String(a)),h,u,"where");if(D)return O("AND",D),this;let N=b.length+1;return b.push(u),O("AND",`${c(String(a))} ${String(o)} ${t(N)}`),this}if(Array.isArray(a)){let[h,D,N]=a,q=String(h);K(q,"where(column)");let P=De(D,"where(operator)");if(P==="in"||P==="not in"){let M=Array.isArray(N)?N:[N],C=s(M.length,b.length+1),Q=l(c(q),M,P==="not in",C);b.push(...M),O("AND",Q)}else{let M=Ve(c(q),P,N,"where");if(M)return O("AND",M),this;let C=b.length+1;b.push(N),O("AND",`${c(q)} ${P} ${t(C)}`)}return this}if(ut(a))ct("where(expr)");if(ze(a)){let h=Xe(a,b.length+1);return b.push(...h.parameters),O("AND",h.text),this}if(a&&typeof a==="object"&&!_e(a)){let h=a,D=Object.keys(h),N=[];for(let q of D){K(q,"where(column)");let P=h[q];if(Array.isArray(P)){let M=s(P.length,b.length+1);N.push(l(c(q),P,!1,M)),b.push(...P)}else{let M=b.length+1;N.push(`${c(q)} = ${t(M)}`),b.push(P)}}if(N.length>0)O("AND",N.length>1?`(${N.join(" AND ")})`:N[0]);return this}if(_e(a))return O("AND",a.raw),this;if(typeof a==="function")return z("AND",a),this;if(a===void 0||a===null)throw TypeError("where() was called with no condition.");if(typeof a==="string")throw TypeError(`where(${JSON.stringify(a)}) is missing an operator and a value. Pass where(column, operator, value), or whereRaw() for a raw fragment.`);throw TypeError(`where() does not understand a condition of type ${typeof a}.`)},whereNull(a){return K(String(a),"whereNull(column)"),O("AND",`${String(a)} IS NULL`),this},whereNotNull(a){return K(String(a),"whereNotNull(column)"),O("AND",`${String(a)} IS NOT NULL`),this},orWhereNull(a){return K(String(a),"orWhereNull(column)"),O("OR",`${String(a)} IS NULL`),this},orWhereNotNull(a){return K(String(a),"orWhereNotNull(column)"),O("OR",`${String(a)} IS NOT NULL`),this},whereBetween(a,o,u){K(String(a),"whereBetween(column)");let h=b.length+1;return b.push(o,u),O("AND",`${String(a)} BETWEEN ${t(h)} AND ${t(h+1)}`),this},orWhereBetween(a,o,u){K(String(a),"orWhereBetween(column)");let h=b.length+1;return b.push(o,u),O("OR",`${String(a)} BETWEEN ${t(h)} AND ${t(h+1)}`),this},whereExists(a){return O("AND",`EXISTS (${a.toSQL()})`),this},orWhereExists(a){return O("OR",`EXISTS (${a.toSQL()})`),this},whereGroup(a){return z("AND",a),this},orWhereGroup(a){return z("OR",a),this},__whereState(){return{body:E(I),params:[...b]}},__sqlState(){return{sql:et(J()),params:[...b]}},whereJsonContains(a,o){K(String(a),"whereJsonContains(column)");let u=e.dialect,h=b.length+1;if(u==="postgres"){let N=typeof o==="number"||typeof o==="boolean"?`to_jsonb(${t(h)})`:t(h);if(e.sql?.jsonContainsMode==="function")O("AND",`jsonb_contains(${a}, ${N})`);else O("AND",`${a} @> ${N}`);b.push(o)}else if(n(u))O("AND",`JSON_CONTAINS(${a}, ${t(h)})`),b.push(JSON.stringify(o));else if(Array.isArray(o)){let D=o.map((N,q)=>`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(h+q)})`);O("AND",`(${D.join(" AND ")})`);for(let N of o)b.push(N)}else if(o!==null&&typeof o==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else O("AND",`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(h)})`),b.push(o);return this},whereJsonPath(a,o,u){if(De(o,"whereJsonPath(op)"),typeof a!=="string"||a.length===0||a.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof a==="string"?`'${a.slice(0,32)}...'`:typeof a}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(a))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${a}' \u2014 contains characters outside the allowed JSON-path set`);let h=e.dialect,D=b.length+1;if(h==="postgres")O("AND",`${a} ${o} ${t(D)}`);else if(n(h))O("AND",`JSON_EXTRACT(${a}) ${o} ${t(D)}`);else O("AND",`json_extract(${a}) ${o} ${t(D)}`);return b.push(u),this},whereLike(a,o,u=!1){let h=t(b.length+1);return L("WHERE",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?h:`LOWER(${h})`}`),b.push(o),v=null,this},whereILike(a,o){let u=t(b.length+1);if(e.dialect==="postgres")L("WHERE",`${String(a)} ILIKE ${u}`);else L("WHERE",`LOWER(${String(a)}) LIKE LOWER(${u})`);return b.push(o),v=null,this},orWhereLike(a,o,u=!1){let h=t(b.length+1);return L("OR",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?h:`LOWER(${h})`}`),b.push(o),v=null,this},orWhereILike(a,o){let u=t(b.length+1);if(e.dialect==="postgres")L("OR",`${String(a)} ILIKE ${u}`);else L("OR",`LOWER(${String(a)}) LIKE LOWER(${u})`);return b.push(o),v=null,this},whereNotLike(a,o,u=!1){let h=t(b.length+1);return L("WHERE",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?h:`LOWER(${h})`}`),b.push(o),v=null,this},whereNotILike(a,o){let u=t(b.length+1);if(e.dialect==="postgres")L("WHERE",`${String(a)} NOT ILIKE ${u}`);else L("WHERE",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return b.push(o),v=null,this},orWhereNotLike(a,o,u=!1){let h=t(b.length+1);return L("OR",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?h:`LOWER(${h})`}`),b.push(o),v=null,this},orWhereNotILike(a,o){let u=t(b.length+1);if(e.dialect==="postgres")L("OR",`${String(a)} NOT ILIKE ${u}`);else L("OR",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return b.push(o),v=null,this},whereAny(a,o,u){if(a.length===0)return O("AND",`(${Gt})`),this;let h=b.length+1,D=a.map((N,q)=>`${N} ${o} ${t(h+q)}`);for(let N=0;N<a.length;N++)b.push(u);return O("AND",`(${D.join(" OR ")})`),this},whereAll(a,o,u){if(a.length===0)return this;let h=b.length+1,D=a.map((N,q)=>`${N} ${o} ${t(h+q)}`);for(let N=0;N<a.length;N++)b.push(u);return O("AND",`(${D.join(" AND ")})`),this},whereNone(a,o,u){if(a.length===0)return this;let h=b.length+1,D=a.map((N,q)=>`${N} ${o} ${t(h+q)}`);for(let N=0;N<a.length;N++)b.push(u);return O("AND",`NOT (${D.join(" OR ")})`),this},whereNotBetween(a,o,u){K(String(a),"whereNotBetween(column)");let h=b.length+1;return b.push(o,u),O("AND",`${a} NOT BETWEEN ${t(h)} AND ${t(h+1)}`),this},whereDate(a,o,u){K(a,"whereDate(column)");let h=u instanceof Date?u.toISOString():typeof u==="string"?u:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof u}`)})(),D=b.length+1;return b.push(h),O("AND",`${a} ${o} ${t(D)}`),this},whereRaw(a,...o){return O("AND",Ze(a,"whereRaw(fragment)",o)),this},orWhereRaw(a,...o){return O("OR",Ze(a,"orWhereRaw(fragment)",o)),this},whereColumn(a,o,u){return K(a,"whereColumn(left)"),K(u,"whereColumn(right)"),O("AND",`${a} ${o} ${u}`),this},orWhereColumn(a,o,u){return K(a,"orWhereColumn(left)"),K(u,"orWhereColumn(right)"),O("OR",`${a} ${o} ${u}`),this},whereIn(a,o){if(K(String(a),"whereIn(column)"),Array.isArray(o)){let u=s(o.length,b.length+1),h=l(a,o,!1,u);b.push(...o),O("AND",h)}else U("AND",a,o,!1);return this},orWhereIn(a,o){if(K(String(a),"orWhereIn(column)"),Array.isArray(o)){let u=s(o.length,b.length+1),h=l(a,o,!1,u);b.push(...o),O("OR",h)}else U("OR",a,o,!1);return this},whereNotIn(a,o){if(K(String(a),"whereNotIn(column)"),Array.isArray(o)){let u=s(o.length,b.length+1),h=l(a,o,!0,u);b.push(...o),O("AND",h)}else U("AND",a,o,!0);return this},orWhereNotIn(a,o){if(K(String(a),"orWhereNotIn(column)"),Array.isArray(o)){let u=s(o.length,b.length+1),h=l(a,o,!0,u);b.push(...o),O("OR",h)}else U("OR",a,o,!0);return this},whereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return O("AND",`(${o})`),this},orWhereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return O("OR",`(${o})`),this},andWhere(a,o,u){return Y(this,"AND","andWhere",a,o,u)},orWhere(a,o,u){return Y(this,"OR","orWhere",a,o,u)},orderBy(a,o="asc"){let u=o==="asc"?"ASC":"DESC",h=c(String(a));return y=he.ORDER_BY.test(y)?`${y}, ${h} ${u}`:`${y} ORDER BY ${h} ${u}`,v=null,this},orderByDesc(a){return y=he.ORDER_BY.test(y)?`${y}, ${a} DESC`:`${y} ORDER BY ${a} DESC`,v=null,this},inRandomOrder(){let a=e.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return y=he.ORDER_BY.test(y)?`${y}, ${a}`:`${y} ORDER BY ${a}`,v=null,this},reorder(a,o="asc"){return y=y.replace(/ORDER BY[\s\S]*$/i,""),y+=` ORDER BY ${a} ${o==="asc"?"ASC":"DESC"}`,v=null,this},latest(a){let o=a??e.timestamps.defaultOrderColumn;return y=he.ORDER_BY.test(y)?`${y}, ${o} DESC`:`${y} ORDER BY ${o} DESC`,v=null,this},oldest(a){let o=a??e.timestamps.defaultOrderColumn;return y=he.ORDER_BY.test(y)?`${y}, ${o} ASC`:`${y} ORDER BY ${o} ASC`,v=null,this},limit(a){if(!Number.isFinite(a)||a<0||!Number.isInteger(a))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${a}`);return y=he.LIMIT.test(y)?y.replace(he.LIMIT,` LIMIT ${a}`):`${y} LIMIT ${a}`,v=null,this},offset(a){if(!Number.isFinite(a)||a<0||!Number.isInteger(a))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${a}`);return y=he.OFFSET.test(y)?y.replace(he.OFFSET,` OFFSET ${a}`):`${y} OFFSET ${a}`,v=null,this},join(a,o,u,h){return K(a,"join(table)"),Qe(o,"join(onLeft)"),Qe(h,"join(onRight)"),De(u,"join(operator)"),F(`JOIN ${a} ON ${o} ${u} ${h}`),G.add(a),this},joinSub(a,o,u,h,D){return K(o,"joinSub(alias)"),Qe(u,"joinSub(onLeft)"),Qe(D,"joinSub(onRight)"),De(h,"joinSub(operator)"),F(`JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${h} ${D}`),G.add(o),this},innerJoin(a,o,u,h){return K(a,"innerJoin(table)"),Qe(o,"innerJoin(onLeft)"),Qe(h,"innerJoin(onRight)"),De(u,"innerJoin(operator)"),F(`INNER JOIN ${a} ON ${o} ${u} ${h}`),G.add(a),this},leftJoin(a,o,u,h){return K(a,"leftJoin(table)"),Qe(o,"leftJoin(onLeft)"),Qe(h,"leftJoin(onRight)"),De(u,"leftJoin(operator)"),F(`LEFT JOIN ${a} ON ${o} ${u} ${h}`),G.add(a),this},leftJoinSub(a,o,u,h,D){return K(o,"leftJoinSub(alias)"),Qe(u,"leftJoinSub(onLeft)"),Qe(D,"leftJoinSub(onRight)"),De(h,"leftJoinSub(operator)"),F(`LEFT JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${h} ${D}`),G.add(o),this},rightJoin(a,o,u,h){return K(a,"rightJoin(table)"),Qe(o,"rightJoin(onLeft)"),Qe(h,"rightJoin(onRight)"),De(u,"rightJoin(operator)"),F(`RIGHT JOIN ${a} ON ${o} ${u} ${h}`),G.add(a),this},crossJoin(a){return K(a,"crossJoin(table)"),F(`CROSS JOIN ${a}`),G.add(a),this},crossJoinSub(a,o){return K(o,"crossJoinSub(alias)"),F(`CROSS JOIN (${String(a.toSQL())}) AS ${o}`),G.add(o),this},selectAllRelations(){if(!H)return this;let a=String(g),o=Object.keys(H[a]?.columns??{}),u=[];if(o.length>0)u.push(d`${d(a)}.*`);for(let h of G){let D=Object.keys(H[h]?.columns??{});for(let N of D){let q=e.aliasing.relationColumnAliasFormat==="camelCase"?`${h}_${N}`.replace(/_([a-z])/g,(P,M)=>M.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${h}.${N}`:`${h}_${N}`;u.push(d`${d(`${h}.${N}`)} AS ${d(q)}`)}}if(u.length>0){let h=o.length>0?`${a}.*`:"",D=[];for(let P of G){let M=Object.keys(H[P]?.columns??{});for(let C of M){let Q=e.aliasing.relationColumnAliasFormat==="camelCase"?`${P}_${C}`.replace(/_([a-z])/g,(Z,ie)=>ie.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${P}.${C}`:`${P}_${C}`;D.push(`${P}.${C} AS ${Q}`)}}let N=[h,...D].filter(Boolean).join(", "),q=y.indexOf(" FROM ");if(q!==-1)y=`SELECT ${N}${y.substring(q)}`;else y=`SELECT ${N} FROM ${a}`;v=null}return this},groupBy(...a){if(a.length)y=he.GROUP_BY.test(y)?`${y}, ${a.map((o)=>c(String(o))).join(", ")}`:`${y} GROUP BY ${a.map((o)=>c(String(o))).join(", ")}`,v=null;return this},groupByRaw(a,...o){let u=Ze(a,"groupByRaw(fragment)",o);return y=he.GROUP_BY.test(y)?`${y}, ${u}`:`${y} GROUP BY ${u}`,v=null,this},having(a){let o=j?"AND":"HAVING";if(Array.isArray(a)){let u=b.length+1;y=`${y} ${o} ${a[0]} ${a[1]} ${t(u)}`,b.push(a[2]),j=!0,v=null}else if(a&&typeof a==="object"&&!("raw"in a)){let u=Object.keys(a),h=u.length;if(h){let D=b.length,N=Array.from({length:h});for(let q=0;q<h;q++){let P=u[q];N[q]=`${P} = ${t(D+q+1)}`,b.push(a[P])}y=`${y} ${o} ${N.join(" AND ")}`,j=!0,v=null}}else if(a&&typeof a.raw<"u")y+=` ${o} ${a.raw}`,j=!0,v=null;return this},havingRaw(a,...o){let u=Ze(a,"havingRaw(fragment)",o);return y+=` ${j?"AND":"HAVING"} ${u}`,j=!0,v=null,this},orderByRaw(a,...o){let u=Ze(a,"orderByRaw(fragment)",o);return y=he.ORDER_BY.test(y)?`${y}, ${u}`:`${y} ORDER BY ${u}`,v=null,this},$call(a){return a(this),this},union(a){return ne("UNION",a),this},unionAll(a){return ne("UNION ALL",a),this},intersect(a){return ne("INTERSECT",a),this},intersectAll(a){return ne("INTERSECT ALL",a),this},except(a){return ne("EXCEPT",a),this},exceptAll(a){return ne("EXCEPT ALL",a),this},forPage(a,o){let u=Math.max(1,Math.floor(a)),h=Math.max(1,Math.floor(o));return y+=` LIMIT ${h} OFFSET ${(u-1)*h}`,v=null,this},toSQL(){let a=et(J());return{sql:a,toString:()=>a,execute:()=>k().execute(),values:()=>k().values(),raw:()=>k().raw()}},async value(a){let o=_(""," LIMIT 1"),u=await se(o,"select",{signal:te,timeoutMs:re}),[h]=u;return h?.[a]},async pluck(a,o){let u=await se(k(),"select",{signal:te,timeoutMs:re});if(o){let h={};for(let D of u){let N=String(D?.[o]);if(Object.prototype.hasOwnProperty.call(h,N))throw Error(`[query-builder] pluck(${a}, ${o}): duplicate key '${N}' \u2014 multiple rows share this value, so the resulting map would silently drop data. Use a unique key column or pluck without a key to get an array.`);h[N]=D?.[a]}return h}return u.map((h)=>h?.[a])},async exists(){let a=_("SELECT EXISTS (",") as e"),o=await se(a,"select",{signal:te,timeoutMs:re}),[u]=o;return Boolean(u?.e)},async doesntExist(){return!await this.exists()},async paginate(a,o=1,u={}){if(typeof a==="object"&&a!==null){let Z=a;o=Z.page??1,u=Z.tx?{tx:Z.tx}:{},a=Z.perPage??10}if(!Number.isFinite(a)||a<=0||!Number.isInteger(a))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${a}`);if(!Number.isFinite(o)||o<1||!Number.isInteger(o))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${o}`);if(u.tx){let Z=et(J()),ie=p([...b]),$e=await u.tx.unsafe(`SELECT COUNT(*) as c FROM (${Z}) as sub`,ie),oe=Number($e?.[0]?.c??0),Be=Math.max(1,Math.ceil(oe/a)),Oe=Math.max(1,Math.min(o,Be)),Ae=(Oe-1)*a;return{data:await u.tx.unsafe(`${Z} LIMIT ${a} OFFSET ${Ae}`,ie),meta:{perPage:a,page:Oe,total:oe,lastPage:Be}}}let h=_("SELECT COUNT(*) as c FROM (",") as sub"),D=await se(h,"select",{signal:te,timeoutMs:re}),[N]=D,q=Number(N?.c??0),P=Math.max(1,Math.ceil(q/a)),M=Math.max(1,Math.min(o,P)),C=(M-1)*a;return{data:await se(_("",` LIMIT ${t(b.length+1)} OFFSET ${t(b.length+2)}`,[a,C]),"select",{signal:te,timeoutMs:re}),meta:{perPage:a,page:M,total:q,lastPage:P}}},async simplePaginate(a,o=1){let u=Math.max(1,o),h=(u-1)*a,D=await se(_("",` LIMIT ${t(b.length+1)} OFFSET ${t(b.length+2)}`,[a+1,h]),"select",{signal:te,timeoutMs:re}),N=D.length>a;return{data:N?D.slice(0,a):D,meta:{perPage:a,page:u,hasMore:N}}},async cursorPaginate(a,o,u="id",h="asc"){if(!Number.isInteger(a)||a<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${a}`);let D=(Array.isArray(u)?u:[u]).map(String);for(let Ee of D)K(Ee,"cursorPaginate(column)");let N=h==="asc"?">":"<",q=h==="asc"?"ASC":"DESC",P=[...b],M="";if(o!==void 0&&o!==null)if(Array.isArray(u)){let Ee=o.map((ue)=>(P.push(ue),t(P.length)));M=`(${D.join(", ")}) ${N} (${Ee.join(", ")})`}else P.push(o),M=`${D[0]} ${N} ${t(P.length)}`;let C=et(M?J({conn:"AND",sql:M}):J()),Q=D.map((Ee)=>`${Ee} ${q}`).join(", ");if(Kt(C))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${Q} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let Z=P.length>0?A(`${C} ORDER BY ${Q} LIMIT ${a+1}`,P):A(`${C} ORDER BY ${Q} LIMIT ${a+1}`),ie=await se(Z,"select",{signal:te,timeoutMs:re}),$e=ie.length>a,oe=ie.slice(0,a),Be=oe[oe.length-1],Oe=$e&&Be?Array.isArray(u)?u.map((Ee)=>Be[Ee]):Be[u]:null,Ae=oe.length?Array.isArray(u)?u.map((Ee)=>oe[0]?.[Ee]):oe[0]?.[u]:null;return{data:oe,meta:{perPage:a,nextCursor:Oe??null,prevCursor:Ae}}},async chunk(a,o){let u=1;while(!0){let{data:h,meta:D}=await this.paginate(a,u);if(h.length===0)break;if(await o(h),u>=D.lastPage)break;u+=1}},async chunkById(a,o="id",u){let h;while(!0){let{data:D,meta:N}=await this.cursorPaginate(a,h,o,"asc");if(D.length===0)break;if(u)await u(D);if(h=N.nextCursor,!h)break}},async eachById(a,o="id",u){await this.chunkById(a,o,async(h)=>{for(let D of h)await u?.(D)})},withTimeout(a){return re=Math.max(1,Math.floor(a)),this},abort(a){return te=a,this},withTrashed(){return ye=!0,we=!1,this},onlyTrashed(){ye=!0,we=!0;let a=e.softDeletes?.column||"deleted_at";return O("AND",`${g}.${a} IS NOT NULL`),this},scope(a,o){let u=String(g),D=S?.scopes?.[u]?.[a];if(D)return D(this,o);return this},when(a,o,u){if(a)return o(this);if(u)return u(this);return this},tap(a){return a(this),this},dump(){return console.log(String(k())),this},dd(){throw console.log(String(k())),Error("Dump and Die")},cache(a=60000){return Tt=a,xe=!0,this},async explain(){let a=_("EXPLAIN ");return await se(a,"select",{signal:te,timeoutMs:re})},simple(){return k().simple()},toText(){return J()},async get(){let a=pe(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||dt(a));if(!e.softDeletes?.enabled&&!xe&&!re&&!te&&!o){let P=R._prepareStatement;if(P){let M=P(J());return at(b.length>0?M.all(...b):M.all())}}let u=J();if(v=b.length>0?A(u,b):A(u),!e.softDeletes?.enabled&&!xe&&!re&&!te&&!o){let P=k()._stmt,M=k()._params;if(P)return at(M&&M.length>0?P.all(...M):P.all());return at(await k().execute())}if(!e.softDeletes?.enabled&&!xe&&!re&&!te)return at(await se(k(),"select"));let h=k();if(e.softDeletes?.enabled&&e.softDeletes.defaultFilter&&!ye){let P=e.softDeletes.column,M=String(g);if((H?Boolean(H[M]?.columns?.[P]):!0)&&!he.DELETED_AT.test(J()))L("WHERE",`${String(P)} IS ${we?"NOT ":""}NULL`),h=k()}let D=xe&&!w?.inTransaction,N=D?Vt(R,J(),b):"";if(D){let P=wt.get(N);if(P)return P}let q=await se(h,"select",{signal:te,timeoutMs:re});if(D)wt.set(N,q,Tt);return at(q)},async executeTakeFirst(){let a=await se(k(),"select",{signal:te,timeoutMs:re});return st(Array.isArray(a)?a[0]:a)},async executeTakeFirstOrThrow(){let a=await this.executeTakeFirst();if(!a)throw Error("Record not found");return a},async first(){let a=pe(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||dt(a));if(!e.softDeletes?.enabled&&!xe&&!re&&!te&&!o){let D=R._prepareStatement;if(D){let N=J(),q=N.includes(" LIMIT ")?N:`${N} LIMIT 1`,P=D(q),M=b.length>0?P.all(...b):P.all();return st(M[0])}}let u=await se(_(""," LIMIT 1"),"select",{signal:te,timeoutMs:re}),[h]=u;return st(h)},async firstOrFail(){let a=await this.first();if(!a)throw Error("Record not found");return a},async find(a){let o=S?.primaryKeys[String(g)]??"id",u=await se(_("",` WHERE ${Re(o)} = ${t(b.length+1)} LIMIT 1`,[a]),"select",{signal:te,timeoutMs:re}),[h]=u;return h},async findOrFail(a){let o=await this.find(a);if(!o)throw Error("Record not found");return o},async findMany(a){let o=S?.primaryKeys[String(g)]??"id";return await se(_("",` WHERE ${l(Re(String(o)),a,!1,s(a.length,b.length+1))}`,a),"select",{signal:te,timeoutMs:re})},async*lazy(){let a,o=S?.primaryKeys[String(g)]??"id";while(!0){let h=await(a==null?d`${k()} ORDER BY ${d(String(o))} ASC LIMIT 100`:d`${k()} WHERE ${d(String(o))} > ${a} ORDER BY ${d(String(o))} ASC LIMIT 100`).execute();if(h.length===0)break;for(let D of h)yield D;if(a=h[h.length-1]?.[o],a==null)break}},async*lazyById(){let a=S?.primaryKeys[String(g)]??"id",o;while(!0){let h=await(o==null?d`${k()} ORDER BY ${d(String(a))} ASC LIMIT 100`:d`${k()} WHERE ${d(String(a))} > ${o} ORDER BY ${d(String(a))} ASC LIMIT 100`).execute();if(h.length===0)break;for(let D of h)yield D;if(o=h[h.length-1]?.[a],o==null)break}},pipe(a){return a(this)},async count(){let a=J(),o=a.indexOf(" FROM "),u=/ GROUP BY /i.test(a),h;if(u)h=`SELECT COUNT(*) as c FROM (${a}) AS _bqb_count_sub`;else if(o!==-1)h=`SELECT COUNT(*) as c${a.substring(o)}`;else h=`SELECT COUNT(*) as c FROM ${g}`;let D=pe(),N=D&&(D.onQueryStart||D.onQueryEnd||D.onQueryError||D.startSpan||dt(D));if(!e.softDeletes?.enabled&&!xe&&!re&&!te&&!N){let C=R._prepareStatement;if(C){let Q=C(h),Z=b.length>0?Q.all(...b):Q.all();return Number(Z[0]?.c??0)}}let q=b.length>0?A(h,b):A(h),P=await se(q,"select",{signal:te,timeoutMs:re}),[M]=P;return Number(M?.c??0)},async avg(a){let o=J(),u=o.indexOf(" FROM "),h=u!==-1?`SELECT AVG(${a}) as a${o.substring(u)}`:`SELECT AVG(${a}) as a FROM ${g}`,D=pe(),N=D&&(D.onQueryStart||D.onQueryEnd||D.onQueryError||D.startSpan||dt(D));if(!e.softDeletes?.enabled&&!xe&&!re&&!te&&!N){let C=R._prepareStatement;if(C){let Q=C(h),Z=b.length>0?Q.all(...b):Q.all();return Number(Z[0]?.a??0)}}let q=b.length>0?A(h,b):A(h),P=await se(q,"select",{signal:te,timeoutMs:re}),[M]=P;return Number(M?.a??0)},async sum(a){let o=J(),u=o.indexOf(" FROM "),h=u!==-1?`SELECT SUM(${a}) as s${o.substring(u)}`:`SELECT SUM(${a}) as s FROM ${g}`,D=b.length>0?A(h,b):A(h),N=await se(D,"select",{signal:te,timeoutMs:re}),[q]=N;return Number(q?.s??0)},async max(a){let o=J(),u=o.indexOf(" FROM "),h=u!==-1?`SELECT MAX(${a}) as m${o.substring(u)}`:`SELECT MAX(${a}) as m FROM ${g}`,D=b.length>0?A(h,b):A(h),N=await se(D,"select",{signal:te,timeoutMs:re}),[q]=N;return q?.m},async min(a){let o=J(),u=o.indexOf(" FROM "),h=u!==-1?`SELECT MIN(${a}) as m${o.substring(u)}`:`SELECT MIN(${a}) as m FROM ${g}`,D=b.length>0?A(h,b):A(h),N=await se(D,"select",{signal:te,timeoutMs:re}),[q]=N;return q?.m},lockForUpdate(){return y+=" FOR UPDATE",v=null,this},sharedLock(){let a=e.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return y+=` ${a}`,v=null,this},withCTE(a,o){return K(a,"withCTE(name)"),y=`WITH ${a} AS (${String(o.toSQL())}) ${y}`,v=null,this},withRecursive(a,o){return K(a,"withRecursive(name)"),y=`WITH RECURSIVE ${a} AS (${String(o.toSQL())}) ${y}`,v=null,this},execute(){return se(k(),"select",{signal:te,timeoutMs:re})},values(){return k().values()},toParams(){return[...b]},__rawState(){return{sql:et(J()),params:[...b]}},__hasPredicate(){return I.length>0||W},raw(){return k().raw()},get rows(){return},get row(){return},cancel(){try{k().cancel()}catch{}}},{get(a,o,u){let h=Reflect.get(a,o,u);if(h!==void 0)return h;if(typeof o==="string"&&(o.startsWith("where")||o.startsWith("orWhere")||o.startsWith("andWhere"))){let D=o.startsWith("orWhere"),N=o.startsWith("andWhere"),q=`${String(g)}|${o}`,P=Ge.get(q);if(P===void 0){let C=o.replace(/^(?:or|and)?where/i,"");if(!C)Ge.set(q,""),P="";else{let Q=C.charAt(0).toLowerCase()+C.slice(1),Z=C.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ie=H?Object.keys(H[String(g)]?.columns??{}):[];P=[Z,Q,Q.toLowerCase()].find(($e)=>ie.includes($e))??Z,Ge.set(q,P)}}if(P==="")return()=>u;let M=P;return(C)=>{if(Array.isArray(C)){let Q=s(C.length,b.length+1);L(D?"OR":N?"AND":"WHERE",`${M} IN (${Q})`),b.push(...C)}else{let Q=t(b.length+1);L(D?"OR":N?"AND":"WHERE",`${M} = ${Q}`),b.push(C)}return u}}return Reflect.get(a,o,u)}})}return{configure(g){return Le(g),this},id(g){if(!he.IDENTIFIER.test(g))throw Error(`[query-builder] Invalid identifier: '${g}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return R(String(g))},ids(...g){for(let f of g)if(!he.IDENTIFIER.test(f))throw Error(`[query-builder] Invalid identifier: '${f}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return R(g)},select(g,...f){return je(g,f)},selectFrom(g){return je(g)},selectFromSub(g,f){function d(k){return()=>{throw Error(`[query-builder] selectFromSub(...).${k}() is not supported. Apply ${k}() to the underlying subquery BEFORE passing it to selectFromSub, or use the regular selectFrom(...) builder. This previously silently returned without `+"affecting the SQL, producing wrong results \u2014 see stacksjs/stacks#1862 #11.")}}K(String(f),"selectFromSub(alias)");let y=typeof g.__rawState==="function"?g.__rawState():null,I=g.toSQL(),b=y?.sql??(typeof I==="string"?I:I?.sql??String(I)),X=y?.params??(Array.isArray(I?.values)?I.values:[]),W=`SELECT * FROM (${b}) AS ${String(f)}`,j=(k,_,O,L)=>{let V=[...k],J=(z,Y,ne)=>{K(z,"selectFromSub where(column)");let F=De(Y,"selectFromSub where(operator)");if(F==="in"||F==="not in"){let re=Array.isArray(ne)?ne:[ne],te=s(re.length,V.length+1);return V.push(...re),`${z} ${F.toUpperCase()} (${te})`}let G=t(V.length+1);return V.push(ne),`${z} ${F} ${G}`},U;if(typeof _==="string"&&O!==void 0)U=J(_,O,L);else if(Array.isArray(_)&&_.length===3)U=J(_[0],_[1],_[2]);else if(_&&typeof _==="object"){let z=Object.entries(_).map(([Y,ne])=>J(Y,"=",ne));U=z.length>1?`(${z.join(" AND ")})`:z[0]}else return{clause:null,params:k};return{clause:U,params:V}};function v(k,_,O,L=""){let V=E(_),J=V?`${k} WHERE ${V}${L}`:`${k}${L}`,U=()=>O.length>0?A(J,O):A(J),z=(F,G,re,te)=>{let ye=j(O,G,re,te);return ye.clause===null?v(k,_,O,L):v(k,[..._,{conn:F,sql:ye.clause}],ye.params,L)},Y=(F,G)=>{let re=[],te=[...O],ye=(Pe)=>(Fe,Tt,fe)=>{let qe=j(te,Fe,Tt,fe);if(qe.clause!==null)re.push({conn:Pe,sql:qe.clause}),te=qe.params;return we},we={where:ye("AND"),andWhere:ye("AND"),orWhere:ye("OR")};G(we);let xe=E(re);if(!xe)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return v(k,[..._,{conn:F,sql:`(${xe})`}],te,L)},ne={distinct(){return v(k.replace(/^SELECT\s+/i,"SELECT DISTINCT "),_,O,L)},distinctOn(...F){let G=F.map(String).join(", ");return v(k.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${G}) `),_,O,L)},selectRaw(F,...G){let re=Ze(F,"selectFromSub.selectRaw(fragment)",G),te=k.indexOf(" FROM "),ye=te!==-1?`${k.slice(0,te)}, ${re}${k.slice(te)}`:`${k}, ${re}`;return v(ye,_,O,L)},$call(F){return F(this)??this},where(F,G,re){return z("AND",F,G,re)},andWhere(F,G,re){return z("AND",F,G,re)},orWhere(F,G,re){return z("OR",F,G,re)},whereGroup(F){return Y("AND",F)},orWhereGroup(F){return Y("OR",F)},orderBy(F,G="asc"){K(String(F),"selectFromSub.orderBy(column)");let re=G==="asc"?"ASC":"DESC",te=he.ORDER_BY.test(L)?`${L}, ${F} ${re}`:`${L} ORDER BY ${F} ${re}`;return v(k,_,O,te)},limit(F){if(!Number.isInteger(F)||F<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${F}`);let G=he.LIMIT.test(L)?L.replace(he.LIMIT,` LIMIT ${F}`):`${L} LIMIT ${F}`;return v(k,_,O,G)},offset(F){if(!Number.isInteger(F)||F<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${F}`);let G=he.OFFSET.test(L)?L.replace(he.OFFSET,` OFFSET ${F}`):`${L} OFFSET ${F}`;return v(k,_,O,G)},toSQL(){return Ce(U(),J)},async execute(){return se(U(),"select")},async executeTakeFirst(){let F=await se(U(),"select");return Array.isArray(F)?F[0]:F},async executeTakeFirstOrThrow(){let F=await se(U(),"select"),G=Array.isArray(F)?F[0]:F;if(!G)throw Error("Record not found");return G},async get(){return se(U(),"select")},async first(){let F=await se(U(),"select");return Array.isArray(F)?F[0]:F},async firstOrFail(){let F=await se(U(),"select"),G=Array.isArray(F)?F[0]:F;if(!G)throw Error("No rows found");return G},async count(){let F=O.length>0?A(`SELECT COUNT(*) as c FROM (${J}) as sub`,O):A(`SELECT COUNT(*) as c FROM (${J}) as sub`),G=await se(F,"select");return Number(G?.[0]?.c??0)},async exists(){let F=O.length>0?A(`SELECT EXISTS(${J}) as e`,O):A(`SELECT EXISTS(${J}) as e`),G=await se(F,"select");return Boolean(G?.[0]?.e)},async doesntExist(){return!await ne.exists()},values(){return U().values()},raw(){return U().raw()},cancel(){try{U().cancel()}catch{}},whereRaw:d("whereRaw"),whereColumn:d("whereColumn"),orWhereColumn:d("orWhereColumn"),whereIn:d("whereIn"),orWhereIn:d("orWhereIn"),whereNotIn:d("whereNotIn"),orWhereNotIn:d("orWhereNotIn"),whereLike:d("whereLike"),whereILike:d("whereILike"),orWhereLike:d("orWhereLike"),orWhereILike:d("orWhereILike"),whereNotLike:d("whereNotLike"),whereNotILike:d("whereNotILike"),orWhereNotLike:d("orWhereNotLike"),orWhereNotILike:d("orWhereNotILike"),whereAny:d("whereAny"),whereAll:d("whereAll"),whereNone:d("whereNone"),whereNested:d("whereNested"),orWhereNested:d("orWhereNested"),whereDate:d("whereDate"),whereBetween:d("whereBetween"),whereNotBetween:d("whereNotBetween"),whereJsonContains:d("whereJsonContains"),whereJsonPath:d("whereJsonPath"),whereNull:d("whereNull"),orWhereNull:d("orWhereNull"),whereNotNull:d("whereNotNull"),orWhereNotNull:d("orWhereNotNull"),whereExists:d("whereExists"),orWhereExists:d("orWhereExists"),orWhereBetween:d("orWhereBetween"),orWhereRaw:d("orWhereRaw"),whereJsonDoesntContain:d("whereJsonDoesntContain"),whereJsonContainsKey:d("whereJsonContainsKey"),whereJsonDoesntContainKey:d("whereJsonDoesntContainKey"),whereJsonLength:d("whereJsonLength"),join:d("join"),joinSub:d("joinSub"),innerJoin:d("innerJoin"),leftJoin:d("leftJoin"),leftJoinSub:d("leftJoinSub"),rightJoin:d("rightJoin"),crossJoin:d("crossJoin"),crossJoinSub:d("crossJoinSub"),groupBy:d("groupBy"),groupByRaw:d("groupByRaw"),having:d("having"),havingRaw:d("havingRaw"),addSelect:d("addSelect"),select:d("select"),selectAll:d("selectAll"),orderByDesc:d("orderByDesc"),inRandomOrder:d("inRandomOrder"),reorder:d("reorder"),orderByRaw:d("orderByRaw"),union:d("union"),unionAll:d("unionAll"),forPage:d("forPage"),selectAllRelations:d("selectAllRelations"),with:d("with"),value:d("value"),pluck:d("pluck"),cursorPaginate:d("cursorPaginate"),paginate:d("paginate"),simplePaginate:d("simplePaginate"),chunk:d("chunk"),chunkById:d("chunkById"),eachById:d("eachById"),avg:d("avg"),sum:d("sum"),max:d("max"),min:d("min"),find:d("find"),findOrFail:d("findOrFail"),findMany:d("findMany"),latest:d("latest"),oldest:d("oldest"),lazy:d("lazy"),lazyById:d("lazyById"),pipe:(F)=>F(ne),when:d("when"),tap:()=>ne,dump:()=>ne,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>U().simple(),toText:()=>J,toParams:()=>[...O],withTimeout:()=>ne,abort:()=>ne,lockForUpdate:()=>ne,sharedLock:()=>ne,withCTE:()=>ne,withRecursive:()=>ne,cache:()=>ne,clone:()=>ne,withTrashed:()=>ne,onlyTrashed:()=>ne,scope:()=>ne,get rows(){return[]},get row(){return}};return ne}return v(W,[],X)},insertInto(g){let f,d="",y=[],I=[],b=!1,X=()=>j?[]:{changes:0,lastInsertRowid:0},W=()=>{let L=async()=>{return},V=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>W(),andWhere:()=>W(),orWhere:()=>W(),orderBy:()=>W(),limit:()=>W(),offset:()=>W(),toSQL:()=>Ce(null,""),execute:async()=>[],get:async()=>[],first:L,executeTakeFirst:L,firstOrFail:V,executeTakeFirstOrThrow:V}},j=e.dialect==="postgres",v=(L)=>{let J=L.flat(2).map(String).filter(Boolean),U=J.length>0&&!J.includes("*")?J.map((ne)=>k(ne)).join(", "):"*",z=async()=>{let ne=await se(A(d,y),"insert"),F=Number(ne?.lastInsertRowid??0),G=Math.max(1,Number(ne?.affectedRows??1)),re=I.filter((we)=>we!==void 0&&we!==null),te=F>0?A(`SELECT ${U} FROM ${k(String(g))} WHERE ${k("id")} >= ? AND ${k("id")} < ? ORDER BY ${k("id")} ASC`,[F,F+G]):re.length>0?A(`SELECT ${U} FROM ${k(String(g))} WHERE ${k("id")} IN (${re.map(()=>"?").join(", ")}) ORDER BY ${k("id")} ASC`,re):null;if(!te)return[];let ye=await te.execute();return Array.isArray(ye)?ye:[]},Y=async()=>(await z())[0];return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>Ce(A(d,y),d),execute:z,get:z,first:Y,executeTakeFirst:Y,async firstOrFail(){let ne=await Y();if(!ne)throw Error("Insert with RETURNING returned no rows");return ne},async executeTakeFirstOrThrow(){let ne=await Y();if(!ne)throw Error("Insert with RETURNING returned no rows");return ne}}},k=j?(L)=>`"${String(L).replace(/"/g,'""')}"`:n(e.dialect)?(L)=>`\`${String(L).replace(/`/g,"``")}\``:(L)=>`"${String(L).replace(/"/g,'""')}"`,_=j?"postgres":n(e.dialect)?"mysql":"sqlite",O=j?(L)=>`$${L+1}`:(L)=>"?";return{values(L){let V=ke(String(g),Array.isArray(L)?L:[L]),J=V.length;if(I=V.map((te)=>te?.id),J===0)return b=!0,f=null,d="",y.length=0,this;b=!1;let U=V[0],z=Object.keys(U),Y=z.length,ne=J*Y;y.length=ne;let F=J===1&&Y>0&&typeof g==="string",G=F?le?.get(g):void 0,re=G?.quoteStyle===_&&G.columns.length===Y;if(re){for(let te=0;te<Y;te++)if(G.columns[te]!==z[te]){re=!1;break}}if(re){d=G.sql;for(let te=0;te<Y;te++)y[te]=U[z[te]]}else if(J===1)if(!j){let te=k(z[0]),ye="?";y[0]=U[z[0]];for(let we=1;we<Y;we++)te+=`,${k(z[we])}`,ye+=",?",y[we]=U[z[we]];d=`INSERT INTO ${k(g)}(${te})VALUES(${ye})`}else{let te=z.map((ye)=>k(ye)).join(",");d=`INSERT INTO ${k(g)}(${te})VALUES(`;for(let ye=0;ye<Y;ye++){if(ye>0)d+=",";d+=O(ye),y[ye]=U[z[ye]]}d+=")"}else{let te=z.map((we)=>k(we)).join(",");d=`INSERT INTO ${k(g)}(${te})VALUES`;let ye=0;for(let we=0;we<J;we++){let xe=V[we];if(we===0)d+="(";else d+="),(";for(let Pe=0;Pe<Y;Pe++){if(Pe>0)d+=",";d+=O(ye),y[ye++]=xe[z[Pe]]}}d+=")"}if(F&&!re&&d.length<=8192){if(le??=new Map,le.size>=32&&!le.has(g)){let te=le.keys().next().value;if(te!==void 0)le.delete(te)}le.set(g,{columns:z,quoteStyle:_,sql:d})}if(!R._prepareStatement)f=A(d,y);return this},returning(...L){if(b)return W();if(n(e.dialect))return v(L);let V=`${d} RETURNING ${L.join(", ")}`,J=A(V,y),U=async()=>{let z=await se(J,"insert");return Array.isArray(z)?z[0]:z};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>Ce(J,V),execute:()=>se(J,"insert"),get:()=>se(J,"insert"),first:U,executeTakeFirst:U,async firstOrFail(){let z=await U();if(!z)throw Error("Insert with RETURNING returned no rows");return z},async executeTakeFirstOrThrow(){let z=await U();if(!z)throw Error("Insert with RETURNING returned no rows");return z}}},toSQL(){if(b)return Ce(null,"");if(!f)f=A(d,y);return Ce(f,d)},execute(){if(b)return Promise.resolve(X());let L=pe();if(!(L&&(L.onQueryStart||L.onQueryEnd||L.onQueryError||L.startSpan||L.beforeCreate||L.afterCreate||dt(L)))){let J=R._prepareStatement;if(J){let U=J(d);return y.length>0?U.run(...y):U.run()}}if(!f)f=A(d,y);return se(f,"insert")},async executeTakeFirst(){if(b)return X();if(!f)f=A(d,y);return await se(f,"insert")},async executeTakeFirstOrThrow(){if(b)throw Error("Insert failed");if(!f)f=A(d,y);let L=await se(f,"insert");if(!L)throw Error("Insert failed");return L},returningAll(){return this.returning("*")}}},updateTable(g){let f,d=[],y=(W)=>{let j=String(W);if(n(e.dialect))return`\`${j.replace(/`/g,"``")}\``;return`"${j.replace(/"/g,'""')}"`},I=`UPDATE ${y(String(g))}`,b=!1,X=(W)=>{I=`${I} ${b?"AND":"WHERE"} ${W}`,b=!0};return{set(W){let j=ke(String(g),[W])[0],v=Object.keys(j),k=v.length,_=Array.from({length:k});for(let O=0;O<k;O++){let L=v[O],V=j[L];if(ut(V))ct(`set(${L})`);if(_e(V))_[O]=`${y(L)} = ${V.raw}`;else if(ze(V)){let J=Xe(V,d.length+1);_[O]=`${y(L)} = ${J.text}`,d.push(...J.parameters)}else _[O]=`${y(L)} = ${t(d.length+1)}`,d.push(V)}return I=`${I} SET ${_.join(", ")}`,f=A(I,d),this},where(W,j,v){if(j!==void 0&&(typeof W==="string"||_e(W)||ze(W))){let k=De(j,"updateTable.where"),_;if(typeof W==="string")_=y(W);else if(_e(W))_=W.raw;else{let V=Xe(W,d.length+1);_=V.text,d.push(...V.parameters)}if(k.toLowerCase()==="in"||k.toLowerCase()==="not in"){let V=Array.isArray(v)?v:[v],J=s(V.length,d.length+1);return X(`${_} ${k.toUpperCase()} (${J})`),d.push(...V),f=A(I,d),this}let O=Ve(_,k,v,"updateTable.where");if(O)return X(O),f=A(I,d),this;let L=d.length+1;return X(`${_} ${k} ${t(L)}`),d.push(v),f=A(I,d),this}if(Array.isArray(W)){let[k,_,O]=W,L=De(_,"updateTable.where");if(L.toLowerCase()==="in"||L.toLowerCase()==="not in"){let U=Array.isArray(O)?O:[O],z=s(U.length,d.length+1);return X(`${y(String(k))} ${L.toUpperCase()} (${z})`),d.push(...U),f=A(I,d),this}let V=Ve(y(String(k)),L,O,"updateTable.where");if(V)return X(V),f=A(I,d),this;let J=d.length+1;return X(`${y(String(k))} ${L} ${t(J)}`),d.push(O),f=A(I,d),this}if(ut(W))ct("updateTable.where(expr)");if(_e(W))return X(W.raw),f=A(I,d),this;if(ze(W)){let k=Xe(W,d.length+1);return X(k.text),d.push(...k.parameters),f=A(I,d),this}if(W&&typeof W==="object"){let k=Object.keys(W);if(k.length===0)throw TypeError("[query-builder] updateTable.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if updating every row is intended.");let _=k.map((O)=>St(y(O),W[O],d));return X(_.join(" AND ")),f=A(I,d),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${W===null?"null":typeof W}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(W){return X(`${y(String(W))} IS NULL`),f=A(I,d),this},whereNotNull(W){return X(`${y(String(W))} IS NOT NULL`),f=A(I,d),this},returning(...W){let j=this,v=()=>`${I} RETURNING ${W.join(", ")}`,k=()=>d.length>0?A(v(),d):A(v()),_=async()=>{let U=/\sWHERE\s/i.test(I),z=U?I.slice(I.search(/\sWHERE\s/i)+1):"",Y=d.slice(d.length-(z.match(/\?|\$\d+/g)?.length??0)),ne=y("id"),F=await(Y.length>0?A(`SELECT ${ne} FROM ${y(String(g))}${U?` ${z}`:""}`,Y):A(`SELECT ${ne} FROM ${y(String(g))}${U?` ${z}`:""}`)).execute().catch(()=>[]),G=(Array.isArray(F)?F:[]).map((ye)=>ye?.id).filter((ye)=>ye!==void 0&&ye!==null);if(await se(d.length>0?A(I,d):A(I),"update"),G.length===0)return[];let re=`SELECT ${W.join(", ")} FROM ${y(String(g))} WHERE ${ne} IN (${G.map(()=>"?").join(", ")})`,te=await A(re,G).execute();return Array.isArray(te)?te:[]},O=()=>n(e.dialect)?_():se(k(),"update"),L=async()=>{let U=await O();return Array.isArray(U)?U[0]:U},V=(U)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${U}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},J={where:(...U)=>(j.where(...U),J),andWhere:(...U)=>(j.where(...U),J),whereNull:(...U)=>(j.whereNull(...U),J),whereNotNull:(...U)=>(j.whereNotNull(...U),J),orWhere:V("orWhere"),orderBy:V("orderBy"),limit:V("limit"),offset:V("offset"),toSQL:()=>Ce(k(),v()),execute:O,get:O,first:L,executeTakeFirst:L,async firstOrFail(){let U=await L();if(!U)throw Error("Update with RETURNING returned no rows");return U},async executeTakeFirstOrThrow(){let U=await L();if(!U)throw Error("Update with RETURNING returned no rows");return U}};return J},toSQL(){if(!f)f=d.length>0?A(I,d):A(I);return Ce(f,I)},async execute(){let W=await se(f,"update");return ve(W)},async executeTakeFirst(){return{numUpdatedRows:ve(await se(f,"update"))}},async executeTakeFirstOrThrow(){let W=ve(await se(f,"update"));if(W===0)throw Error("No rows updated");return{numUpdatedRows:W}},returningAll(){return this.returning("*")}}},deleteFrom(g){let f=(k)=>{let _=String(k);if(n(e.dialect))return`\`${_.replace(/`/g,"``")}\``;return`"${_.replace(/"/g,'""')}"`},y=`DELETE FROM ${f(String(g))}`,I=null,b=[],X=null,W=!1,j=(k)=>{y+=` ${W?"AND":"WHERE"} ${k}`,W=!0},v=()=>{if(I===null)I=b.length>0?A(y,b):A(y);return I};return{where(k,_,O){if(X=k,typeof k==="string"&&_!==void 0){let L=De(_,"deleteFrom.where");if(L.toLowerCase()==="in"||L.toLowerCase()==="not in"){let U=Array.isArray(O)?O:[O],z=s(U.length,b.length+1);return j(`${f(k)} ${L.toUpperCase()} (${z})`),b.push(...U),I=null,this}let V=Ve(f(k),L,O,"deleteFrom.where");if(V)return j(V),I=null,this;let J=b.length+1;return j(`${f(k)} ${L} ${t(J)}`),b.push(O),I=null,this}if(Array.isArray(k)){let[L,V,J]=k,U=De(V,"deleteFrom.where");if(U.toLowerCase()==="in"||U.toLowerCase()==="not in"){let ne=Array.isArray(J)?J:[J],F=s(ne.length,b.length+1);return j(`${f(String(L))} ${U.toUpperCase()} (${F})`),b.push(...ne),I=null,this}let z=Ve(f(String(L)),U,J,"deleteFrom.where");if(z)return j(z),I=null,this;let Y=b.length+1;return j(`${f(String(L))} ${U} ${t(Y)}`),b.push(J),I=null,this}if(ut(k))ct("deleteFrom.where(expr)");if(_e(k))return j(k.raw),I=null,this;if(ze(k)){let L=Xe(k,b.length+1);return j(L.text),b.push(...L.parameters),I=null,this}if(k&&typeof k==="object"){let L=Object.keys(k);if(L.length===0)throw TypeError("[query-builder] deleteFrom.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if deleting every row is intended.");let V=L.map((J)=>St(f(J),k[J],b));return j(V.join(" AND ")),I=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${k===null?"null":typeof k}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(k){return j(`${f(String(k))} IS NULL`),I=null,this},whereNotNull(k){return j(`${f(String(k))} IS NOT NULL`),I=null,this},returning(...k){let _=this,O=()=>`${y} RETURNING ${k.join(", ")}`,L=()=>b.length>0?A(O(),b):A(O()),V=async()=>{await pe()?.beforeDelete?.({table:String(g),where:X});let Y=n(e.dialect)?await(async()=>{let ne=y.slice(y.search(/\sFROM\s/i)+1),F=`SELECT ${k.join(", ")} ${ne}`,G=await(b.length>0?A(F,b):A(F)).execute();return await se(b.length>0?A(y,b):A(y),"delete"),Array.isArray(G)?G:[]})():await se(L(),"delete");try{await pe()?.afterDelete?.({table:String(g),where:X,result:Y})}catch{}return Y},J=async()=>{let Y=await V();return Array.isArray(Y)?Y[0]:Y},U=(Y)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${Y}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},z={where:(...Y)=>(_.where(...Y),z),andWhere:(...Y)=>(_.where(...Y),z),whereNull:(...Y)=>(_.whereNull(...Y),z),whereNotNull:(...Y)=>(_.whereNotNull(...Y),z),orWhere:U("orWhere"),orderBy:U("orderBy"),limit:U("limit"),offset:U("offset"),toSQL:()=>Ce(L(),O()),execute:()=>V(),get:()=>V(),first:J,executeTakeFirst:J,async firstOrFail(){let Y=await J();if(!Y)throw Error("Delete with RETURNING returned no rows");return Y},async executeTakeFirstOrThrow(){let Y=await J();if(!Y)throw Error("Delete with RETURNING returned no rows");return Y}};return z},toSQL(){return Ce(v(),y)},async execute(){try{await pe()?.beforeDelete?.({table:String(g),where:X})}catch(_){throw _}let k=ve(await se(v(),"delete"));try{await pe()?.afterDelete?.({table:String(g),where:X,result:k})}catch{}return k},async executeTakeFirst(){return{numDeletedRows:ve(await se(v(),"delete"))}},async executeTakeFirstOrThrow(){let k=ve(await se(v(),"delete"));if(k===0)throw Error("No rows deleted");return{numDeletedRows:k}},returningAll(){return this.returning("*")}}},table(g){let f=this;return{insert(d){return f.insertInto(g).values(d)},update(d){return f.updateTable(g).set(d)},delete(){return f.deleteFrom(g)},select(...d){if(d.length===0)return f.selectFrom(g);return f.select(g,...d)}}},sql:R,raw(g,...f){if(typeof g==="string")return Jt(g,f);return R(g,...f)},simple(g,...f){return R(g,...f).simple()},async advisoryLock(g){if(e.dialect==="postgres"){let f=Se(g),d=A("SELECT pg_advisory_lock($1)",[f]);await se(d,"raw");return}if(n(e.dialect)){let f=`bqb:${String(g)}`,d=A("SELECT GET_LOCK(?, -1) AS ok",[f]);await se(d,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(g){if(e.dialect==="postgres"){let f=Se(g),d=A("SELECT pg_try_advisory_lock($1) as ok",[f]),y=await se(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let f=`bqb:${String(g)}`,d=A("SELECT GET_LOCK(?, 0) AS ok",[f]),y=await se(d,"raw");return Number(y?.[0]?.ok)===1}return!1},async advisoryUnlock(g){if(e.dialect==="postgres"){let f=Se(g),d=A("SELECT pg_advisory_unlock($1) as ok",[f]),y=await se(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let f=`bqb:${String(g)}`,d=A("SELECT RELEASE_LOCK(?) AS ok",[f]),y=await se(d,"raw");return Number(y?.[0]?.ok)===1}return!1},unsafe(g,f){return _t(g,f),R.unsafe(g,f)},deferInsert:R.deferInsert?.bind(R),flushDeferredInserts:R.flushDeferredInserts?.bind(R),file(g,f){return R.file(g,f)},async reserve(){let g=await r.reserve(),f=i({sql:g,meta:S,schema:H,hooks:w?.hooks});return f.release=()=>g.release(),f},async close(g){await r.close(g)},async listen(g,f){},async unlisten(g){},async notify(g,f){},async copyTo(g,f){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(g,f,d){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let g=A("SELECT 1");return await se(g,"select"),!0}catch{return!1}},async waitForReady(g){let f=Math.max(1,g?.attempts??10),d=Math.max(10,g?.delayMs??100);for(let y=0;y<f;y++){if(await this.ping())return;await new Promise((I)=>setTimeout(I,d))}throw Error("Database not ready after waiting")},async transaction(g,f){let y={...w?.txDefaults,...f},I=w?.sql??r,b=w?.inTransaction===!0,X=b&&typeof I?.savepoint==="function"?"savepoint":"begin",W=async(_)=>{y.logger?.({type:"start",attempt:_});let O=Date.now();return await I[X](async(L)=>{let V=i({sql:L,meta:S,schema:H,hooks:w?.hooks,inTransaction:!0});if(y?.isolation&&!b){let z=y.isolation,Y=z==="read committed"?"READ COMMITTED":z==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(e.dialect==="postgres")await L.unsafe(`SET TRANSACTION ISOLATION LEVEL ${Y}`);else if(n(e.dialect))await L.unsafe(`SET TRANSACTION ISOLATION LEVEL ${Y}`);else if(z!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${z}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(y?.readOnly)if(e.dialect==="postgres")await L.unsafe("SET TRANSACTION READ ONLY");else if(n(e.dialect))await L.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let J=await g(V),U=Date.now()-O;return y.logger?.({type:"commit",attempt:_,durationMs:U}),J})},j=Math.max(0,y?.retries??0),v=0,k;for(;;)try{k=await W(v+1);break}catch(_){let O=Yt(_)||zt(_,y.sqlStates);if(v<j&&O){v++,y?.onRetry?.(v,_);let L=an(v,y.backoff);if(L>0)await Xt(L);continue}try{y.onRollback?.(_)}catch{}try{y.afterRollback?.()}catch{}throw _}return await y.afterCommit?.(),k},async savepoint(g){if(w?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let f=R;if(!f||typeof f.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await f.savepoint(async(d)=>{let y=i({sql:d,meta:S,schema:H,hooks:w?.hooks,inTransaction:!0});return await g(y)})},async beginDistributed(g,f){return await(w?.sql??r).beginDistributed(g,async(I)=>{let b=i({sql:I,meta:S,schema:H,hooks:w?.hooks});return await f(b)})},async commitDistributed(g){await r.commitDistributed(g)},async rollbackDistributed(g){await r.rollbackDistributed(g)},setTransactionDefaults(g){w={...w,txDefaults:{...w?.txDefaults,...g}}},transactional(g,f){return(...d)=>this.transaction((y)=>g(y,...d),f)},async insertOrIgnore(g,f){let d=Array.isArray(f)?f:[f];if(!d.length)return;let{colsSql:y,valuesSql:I,params:b}=mt(d),X=Re(String(g)),W=n(e.dialect)?`INSERT IGNORE INTO ${X} (${y}) VALUES ${I}`:`INSERT INTO ${X} (${y}) VALUES ${I} ON CONFLICT DO NOTHING`;return A(W,b).execute()},async insertGetId(g,f,d="id"){let{colsSql:y,valuesSql:I,params:b}=mt([f]),X=Re(String(g));if(n(e.dialect)){await A(`INSERT INTO ${X} (${y}) VALUES ${I}`,b).execute();let[j]=await A("SELECT LAST_INSERT_ID() as id").execute();return j?.id}if(e.dialect==="sqlite"){let j=await A(`INSERT INTO ${X} (${y}) VALUES ${I}`,b).execute();if(j?.lastInsertRowid!=null)return j.lastInsertRowid;let[v]=await A("SELECT last_insert_rowid() as id").execute();return v?.id}let[W]=await A(`INSERT INTO ${X} (${y}) VALUES ${I} RETURNING ${Re(String(d))} as id`,b).execute();return W?.id},async updateOrInsert(g,f,d){let y=Re(String(g)),I=Object.keys(f),b=1,X=I.map((O)=>`${Re(O)} = ${t(b++)}`).join(" AND "),W=I.map((O)=>f[O]);if((await A(`SELECT 1 FROM ${y} WHERE ${X} LIMIT 1`,W).execute()).length){let O=Object.keys(d),L=1,V=O.map((z)=>`${Re(z)} = ${t(L++)}`).join(", "),J=I.map((z)=>`${Re(z)} = ${t(L++)}`).join(" AND "),U=[...O.map((z)=>d[z]),...I.map((z)=>f[z])];return await A(`UPDATE ${y} SET ${V} WHERE ${J}`,U).execute(),!0}let{colsSql:v,valuesSql:k,params:_}=mt([{...f,...d}]);return await A(`INSERT INTO ${y} (${v}) VALUES ${k}`,_).execute(),!0},async upsert(g,f,d,y){let I=d.map((V)=>String(V)),b=(y??[]).map((V)=>String(V)),X=f;if(!X.length)return;let{colsSql:W,valuesSql:j,params:v}=mt(X),k=Re(String(g)),_=`INSERT INTO ${k} (${W}) VALUES ${j}`;if(n(e.dialect)){if(b.length===0)return A(`INSERT IGNORE INTO ${k} (${W}) VALUES ${j}`,v).execute();let V=b.map((J)=>`${Re(J)} = VALUES(${Re(J)})`).join(", ");return A(`${_} ON DUPLICATE KEY UPDATE ${V}`,v).execute()}let O=I.map(Re).join(", ");if(b.length===0)return A(`${_} ON CONFLICT (${O}) DO NOTHING`,v).execute();let L=b.map((V)=>`${Re(V)} = EXCLUDED.${Re(V)}`).join(", ");return A(`${_} ON CONFLICT (${O}) DO UPDATE SET ${L}`,v).execute()},async save(g,f){let d=S?.primaryKeys[String(g)]??"id",y=f[d];if(y!=null)if(await this.selectFrom(g).find(y)){await this.updateTable(g).set(f).where({[d]:y}).execute();let b=await this.selectFrom(g).find(y);if(!b)throw Error("save() failed to retrieve updated row");return b}else return await this.create(g,f);return await this.create(g,f)},async remove(g,f){return await this.deleteFrom(g).where({id:f}).execute()},async find(g,f){return await this.selectFrom(g).find(f)},async findOrFail(g,f){return await this.selectFrom(g).findOrFail(f)},async findMany(g,f){return await this.selectFrom(g).findMany(f)},async latest(g,f){return await this.selectFrom(g).latest(f).first()},async oldest(g,f){return await this.selectFrom(g).oldest(f).first()},skip(g,f){return this.selectFrom(g).offset(f)},async rawQuery(g){let f=Date.now();try{pe()?.onQueryStart?.({sql:g,kind:"raw"});let d=await R.unsafe(g);return pe()?.onQueryEnd?.({sql:g,durationMs:Date.now()-f,kind:"raw"}),d}catch(d){throw pe()?.onQueryError?.({sql:g,error:d,durationMs:Date.now()-f,kind:"raw"}),d}},async create(g,f){let d=S?.primaryKeys[String(g)]??"id";try{await pe()?.beforeCreate?.({table:String(g),data:f})}catch(y){throw y}if(e.dialect==="postgres"){let y=R`INSERT INTO ${R(String(g))} ${R(f)} RETURNING ${R(String(d))} as id`,[I]=await y.execute();if(!I?.id)throw console.error(`create() failed to get insert ID for table ${String(g)}`),console.error("Inserted values:",f),Error(`create() failed to get insert ID for table ${String(g)}`);let b=await this.selectFrom(g).find(I.id);if(!b)throw console.error(`create() failed to retrieve inserted row for table ${String(g)} with id ${I.id}`),console.error("Inserted values:",f),Error(`create() failed to retrieve inserted row for table ${String(g)} with id ${I.id}`);try{await pe()?.afterCreate?.({table:String(g),data:f,result:b})}catch{}return b}else{let y=await this.insertGetId(g,f,d);if(y==null)throw Error(`create() failed to get insert ID for table ${String(g)}`);let I=await this.selectFrom(g).find(y);if(!I)throw console.error(`create() failed to retrieve inserted row for table ${String(g)} with id ${y}`),console.error("Inserted values:",f),Error(`create() failed to retrieve inserted row for table ${String(g)} with id ${y}`);try{await pe()?.afterCreate?.({table:String(g),data:f,result:I})}catch{}return I}},async createMany(g,f){if(!f?.length)return;let d=f[0],y=Object.keys(d),I=y.length,b=f.length,X=Array.from({length:b*I}),W=n(e.dialect)?(k)=>`\`${String(k).replace(/`/g,"``")}\``:(k)=>`"${String(k).replace(/"/g,'""')}"`,j=`INSERT INTO ${W(String(g))}(${y.map(W).join(",")})VALUES`,v=0;for(let k=0;k<b;k++){if(k>0)j+=",";j+="(";let _=f[k];for(let O=0;O<I;O++){if(O>0)j+=",";j+=t(v+1),X[v++]=_[y[O]]}j+=")"}return A(j,X).execute()},async insertMany(g,f){if(!f?.length)return;let d=f[0],y=Object.keys(d),I=y.length,b=f.length,X=b*I,W=Array(X),j=e.dialect==="postgres",v;if(!j){let O=Array(I);for(let L=0;L<I;L++)O[L]="?";v=`(${O.join(",")})`}else v="";let k=Array(b+2);k[0]=`INSERT INTO ${g}(${y.join(",")})VALUES`;let _=0;if(!j){for(let O=0;O<b;O++){let L=f[O];k[O+1]=v;for(let V=0;V<I;V++)W[_++]=L[y[V]]}return A(k[0]+k.slice(1,b+1).join(","),W).execute()}for(let O=0;O<b;O++){let L=f[O],V=Array(I);for(let J=0;J<I;J++)V[J]=`$${_+1}`,W[_++]=L[y[J]];k[O+1]=`(${V.join(",")})`}return A(k[0]+k.slice(1,b+1).join(","),W).execute()},async updateMany(g,f,d){let y=Object.keys(d),I=y.length;if(I===0)return 0;let b=[],X=Array.from({length:I});for(let j=0;j<I;j++)X[j]=`${y[j]}=${t(j+1)}`,b.push(d[y[j]]);let W=`UPDATE ${g} SET ${X.join(",")}`;if(Array.isArray(f)){let j=De(String(f[1]),"updateMany");W+=` WHERE ${f[0]} ${j} ${t(b.length+1)}`,b.push(f[2])}else if(_e(f))W+=` WHERE ${f.raw}`;else if(ze(f)){let j=Xe(f,b.length+1);W+=` WHERE ${j.text}`,b.push(...j.parameters)}else if(f&&typeof f==="object"&&Object.keys(f).length>0){let j=Object.keys(f).map((v)=>St(v,f[v],b));W+=` WHERE ${j.join(" AND ")}`}else if(f&&typeof f==="object")throw TypeError("[query-builder] updateMany(): an empty object is not a filter. Pass a condition, or use updateTable(table).set(data).execute() if updating every row is intended.");else throw TypeError(`[query-builder] updateMany(): expected a condition, got ${f===null?"null":typeof f}. Refusing to run an UPDATE with no WHERE \u2014 use updateTable(table).set(data).execute() if updating every row is intended.`);return A(W,b).execute()},async deleteMany(g,f){if(!Array.isArray(f)||f.length===0)return 0;let d=S?.primaryKeys[String(g)]??"id",y=f.length;if(e.dialect==="postgres"){let b=Array(y);for(let X=0;X<y;X++)b[X]=`$${X+1}`;return A(`DELETE FROM ${g} WHERE ${d} IN (${b.join(",")})`,f).execute()}let I=Array(y);for(let b=0;b<y;b++)I[b]="?";return A(`DELETE FROM ${g} WHERE ${d} IN (${I.join(",")})`,f).execute()},async firstOrCreate(g,f,d){let y=await this.selectFrom(g).where(f).first();if(y)return y;return await this.create(g,{...f,...d})},async updateOrCreate(g,f,d){let y=await this.selectFrom(g).where(f).first();if(y){await this.updateTable(g).set(d).where(f).execute();let I=S?.primaryKeys[String(g)]??"id",b=y[I],X=b!=null?await this.selectFrom(g).find(b):await this.selectFrom(g).where(f).first();if(!X)throw Error("updateOrCreate() failed to retrieve updated row");return X}return await this.create(g,{...f,...d})},async count(g,f){let d=f?R(String(f)):R`*`,y=R`SELECT COUNT(${d}) as c FROM ${R(String(g))}`,[I]=await y.execute();return Number(I?.c??0)},async sum(g,f){let d=R`SELECT SUM(${R(String(f))}) as s FROM ${R(String(g))}`,[y]=await d.execute();return Number(y?.s??0)},async avg(g,f){let d=R`SELECT AVG(${R(String(f))}) as a FROM ${R(String(g))}`,[y]=await d.execute();return Number(y?.a??0)},async min(g,f){let d=R`SELECT MIN(${R(String(f))}) as m FROM ${R(String(g))}`,[y]=await d.execute();return y?.m},async max(g,f){let d=R`SELECT MAX(${R(String(f))}) as m FROM ${R(String(g))}`,[y]=await d.execute();return y?.m},getRelationships(g){if(!S?.relations)return{};let f=S.relations[g];if(!f)return{};let d={};for(let[y,I]of Object.entries(f))if(I&&typeof I==="object"&&Object.keys(I).length>0)d[y]=I;return d},hasRelationship(g,f){if(!S?.relations)return!1;let d=S.relations[g];if(!d)return!1;return Object.values(d).some((y)=>y&&typeof y==="object"&&(f in y))},getRelationshipType(g,f){if(!S?.relations)return null;let d=S.relations[g];if(!d)return null;for(let[y,I]of Object.entries(d))if(I&&typeof I==="object"&&f in I)return y;return null},getRelationshipTarget(g,f){if(!S?.relations)return null;let d=S.relations[g];if(!d)return null;for(let[y,I]of Object.entries(d))if(I&&typeof I==="object"&&f in I){let b=I[f];if(typeof b==="string")return S.modelToTable[b]||b;else if(b&&typeof b==="object"){if("model"in b)return S.modelToTable[b.model]||b.model;if("target"in b)return S.modelToTable[b.target]||b.target}}return null}}}function Ne(){wt.clear()}function Me(w){wt.setMaxSize(w)}
3
+ export{x,Kn,nn,c,At,Nt,i,Ne,Me};