bun-query-builder 0.3.8 → 0.3.9
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 +2 -2
- package/dist/{chunk-3b13fc8j.js → chunk-284e3ka8.js} +2 -2
- package/dist/{chunk-bpwg9p8b.js → chunk-3hwsz4q7.js} +1 -1
- package/dist/{chunk-82w0fmx3.js → chunk-56n17myf.js} +1 -1
- package/dist/chunk-8zpn75gg.js +2 -0
- package/dist/{chunk-rzfnhh9f.js → chunk-dj2eazhq.js} +1 -1
- package/dist/{chunk-vyqr0w2z.js → chunk-ygwkzhkh.js} +1 -1
- package/dist/db.d.ts +1 -0
- package/dist/src/index.js +1 -1
- package/dist/src/runtime.js +1 -1
- package/dist/types.d.ts +1 -0
- package/package.json +1 -1
- package/dist/chunk-g7qvmctn.js +0 -2
package/dist/bin/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import"../chunk-
|
|
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}
|
|
4
4
|
|
|
5
5
|
Stack trace:
|
|
6
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(`
|
|
@@ -29,7 +29,7 @@ Received ${i}, cleaning up...`),e)try{await e()}catch(s){console.error("Error du
|
|
|
29
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?`
|
|
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.
|
|
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'
|
|
33
33
|
|
|
34
34
|
${s.map((n)=>n.source).join(`
|
|
35
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();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{n,e,P,t,B,Ke,st,r,T,m}from"./chunk-
|
|
2
|
+
import{n,e,P,t,B,Ke,st,r,T,m}from"./chunk-3hwsz4q7.js";import{i,Re,Ae}from"./chunk-ygwkzhkh.js";import{N,Pe,Be,O}from"./chunk-dj2eazhq.js";import{u}from"./chunk-9wck98bv.js";var Ur=import.meta.require;async function Z(s={}){let a=s.iterations||1000,l=s.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${a}`),console.log(`-- Operations: ${l.join(", ")}`),console.log();let c=i();console.log("-- Setting up test table...");try{await r.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await r.unsafe(`
|
|
3
3
|
CREATE TABLE bench_users (
|
|
4
4
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
5
|
name TEXT NOT NULL,
|
|
@@ -349,7 +349,7 @@ export default class ${f} extends Seeder {
|
|
|
349
349
|
return 100
|
|
350
350
|
}
|
|
351
351
|
}
|
|
352
|
-
`;Gi(p,E),console.log(`-- \u2713 Created seeder: ${p}`)}async function De(s={}){let a=mn(tn.cwd()),l=s.modelsDir||Lt(a,"app/Models"),c=s.seedersDir||Lt(a,"database/seeders"),f=s.verbose??!0;try{let{resetDatabase:b,generateMigration:p,executeMigration:E}=await import("./chunk-
|
|
352
|
+
`;Gi(p,E),console.log(`-- \u2713 Created seeder: ${p}`)}async function De(s={}){let a=mn(tn.cwd()),l=s.modelsDir||Lt(a,"app/Models"),c=s.seedersDir||Lt(a,"database/seeders"),f=s.verbose??!0;try{let{resetDatabase:b,generateMigration:p,executeMigration:E}=await import("./chunk-8zpn75gg.js");if(f)console.log("-- Refreshing database...");if(await b(l),f)console.log("-- Running migrations...");if(await p(l,{full:!0}),await E(),f)console.log("-- Running seeders...");if(await M({seedersDir:c,verbose:f}),f)console.log("-- \u2713 Database refreshed successfully")}catch(b){throw console.error("-- \u2717 Database refresh failed:",b),b}}function Ee(s,a,l={}){let c=d({modelsDir:s}),f=ke(c);if(e.debug)e.debug.captureText=!0;let b=i({schema:f}),p=b.selectFrom(a).limit(Number(l.limit||10)).toText?.()??"";return console.log(p||"[query]"),{sql:p,qb:b,schema:f}}async function $e(s,a={}){let l=i(),c=a.params?JSON.parse(a.params):void 0,f=await l.unsafe(s,c);return console.log(JSON.stringify(f)),f}import{existsSync as zi}from"fs";import{dirname as Dr,join as Rr}from"path";import Sr from"process";function Hi(s){let a=s;while(a!==Dr(a)){if(zi(Rr(a,"package.json")))return a;a=Dr(a)}return Sr.cwd()}async function Q(s){if(!s)s=Rr(Hi(Sr.cwd()),"app/Models");let a=e.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${s}`),console.log(`-- Dialect: ${a}`),console.log();let l=[];try{let c=await d({modelsDir:s}),f=G(c,{dialect:a}),b=i(),p=[];if(a==="sqlite")p=(await b.unsafe(`
|
|
353
353
|
SELECT name FROM sqlite_master
|
|
354
354
|
WHERE type = 'table'
|
|
355
355
|
AND name NOT LIKE 'sqlite_%'
|
|
@@ -61,7 +61,7 @@ export type ConfigOf = Config
|
|
|
61
61
|
`;return c}}function qo(i,o,c={}){return ps(i,o,c,new WeakMap)}function ps(i,o,c,f){let{arrayMergeMode:u="replace",skipNullish:g=!1,customMerger:h}=c;if(o===null||o===void 0)return g?i:o;if(h){let d=h(i,o);if(d!==void 0)return d}if(Array.isArray(o)||Array.isArray(i))return ys(i,o,u,f);if(!re(o)||!re(i))return o;return Yo(i,o,c,f)}function ys(i,o,c,f){if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(i)&&!Array.isArray(o))return o;if(Array.isArray(o)&&Array.isArray(i))switch(c){case"replace":return o;case"concat":return Ho(i,o);case"smart":return zo(i,o,f);default:return o}return o}function Ho(i,o){let c=[...o];for(let f of i)if(!c.some((u)=>vr(u,f)))c.push(f);return c}function zo(i,o,c){if(o.length===0)return i;if(i.length===0)return o;if(re(o[0])&&re(i[0]))return Go(i,o,c);if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}function Go(i,o,c){let f=[...o];for(let u of i){if(!re(u)){f.push(u);continue}let g=["id","name","key","path","type"],h=!1;for(let d of g)if(d in u){if(f.find((y)=>re(y)&&(d in y)&&y[d]===u[d])){h=!0;break}}if(!h)f.push(u)}return f}function Yo(i,o,c,f){let u=o;if(re(u)&&f.has(u))return f.get(u);let g={...i};if(re(u))f.set(u,g);for(let h in u){if(!Object.prototype.hasOwnProperty.call(u,h))continue;let d=u[h],p=g[h];if(c.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){g[h]=d;continue}if(re(d)&&re(p))g[h]=ps(p,d,c,f);else if(Array.isArray(d)||Array.isArray(p))g[h]=ys(p,d,c.arrayMergeMode||"smart",f);else g[h]=d}return g}function ws(i,o,c="replace"){return qo(i,o,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function vr(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!vr(i[c],o[c]))return!1;return!0}if(re(i)&&re(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!vr(i[u],o[u]))return!1}return!0}return!1}function re(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class bs{extensions=Bn;async loadFromPath(i,o,c={}){let{arrayStrategy:f="replace",useCache:u=!0,cacheTtl:g,trackPerformance:h=!0,verbose:d=!1}=c;if(u){let y=bt.getWithFileCheck("file",i);if(y){if(d)console.log(`Configuration loaded from cache: ${i}`);return y}}let p=async()=>{if(!gt(i))return null;try{let y=`?t=${Date.now()}`,w=await import(i+y),S=w.default||w,E="default"in w,v=Object.keys(w).length>0;if(!E&&!v)throw new Ot(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof S!=="object"||S===null||Array.isArray(S))throw new Ot(i,Error("Configuration must export a valid object"),"unknown");let A={config:ws(o,S,f),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)bt.setWithFileCheck("file",A,i,g);return A}catch(y){throw y instanceof Error?ye.configLoad(i,y):ye.configLoad(i,Error(String(y)))}};if(h)return Er.track("loadFromPath",p,{path:i});return p()}async tryLoadFromPaths(i,o,c={}){for(let f of i)try{let u=await this.loadFromPath(f,o,c);if(u)return u}catch(u){if(u instanceof Error&&u.name==="ConfigLoadError")throw u;if(c.verbose)console.warn(`Failed to load config from ${f}:`,u)}return null}generateConfigPaths(i,o,c){return Ws({name:i,directory:o,alias:c})}generateNamePatterns(i,o){return jn({name:i,alias:o})}checkFileAccess(i){return Uo(async()=>gt(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,o,c){let f=[];if(!gt(i))return f;if(o||c){let u=this.generateNamePatterns(o||"",c);for(let g of u)for(let h of this.extensions){let d=In(i,`${g}${h}`);if(await this.checkFileAccess(d))f.push(d)}}else try{let{readdirSync:u}=await import("fs"),g=u(i);for(let h of g)if(this.looksLikeConfigFile(h)){let d=In(i,h);if(await this.checkFileAccess(d))f.push(d)}}catch{return[]}return f}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((c)=>c.test(i))}async validateConfigFile(i){let o=[];try{if(!gt(i))return o.push("Configuration file does not exist"),o;let c=await import(i),f=c.default||c;if(f===void 0)o.push("Configuration file must export a default value or named exports");else if(typeof f!=="object"||f===null)o.push("Configuration must be an object");else if(Array.isArray(f))o.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),g=u(i,"utf8");JSON.parse(g)}catch(u){o.push(`Invalid JSON syntax: ${u}`)}}catch(c){o.push(`Failed to load configuration file: ${c}`)}return o}async getFileModificationTime(i){try{let{statSync:o}=await import("fs");return o(i).mtime}catch{return null}}async preloadConfigurations(i,o={}){let c=new Map;return await Promise.allSettled(i.map(async(f)=>{try{let u=await this.loadFromPath(f,{},o);if(u)c.set(f,u.config)}catch(u){if(o.verbose)console.warn(`Failed to preload ${f}:`,u)}})),c}}var Zo=/^https?:\/\//;class Ss{async validateConfiguration(i,o,c={}){let{stopOnFirstError:f=!1,validateRequired:u=!0,validateTypes:g=!0,customRules:h=[],trackPerformance:d=!0,verbose:p=!1}=c,y=async()=>{let w=[],S=[],E={stopOnFirstError:f,validateRequired:u,validateTypes:g,customRules:h,trackPerformance:d,verbose:p};try{if(typeof o==="string")return await this.validateWithSchemaFile(i,o,E);else if(Array.isArray(o))return this.validateWithRules(i,[...o,...h],E);else return this.validateWithJSONSchema(i,o,E)}catch(v){return w.push({path:"",message:`Validation failed: ${v}`,rule:"system"}),{isValid:!1,errors:w,warnings:S}}};if(d)return await Er.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,o,c){try{if(!Jo(o))throw new Pt(o,[{path:"",message:"Schema file does not exist"}]);let f=await import(o),u=f.default||f;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(f){throw new Pt(o,[{path:"",message:`Failed to load schema: ${f}`}])}}validateWithJSONSchema(i,o,c){let f=[],u=[];return this.validateObjectAgainstSchema(i,o,"",f,u,c),{isValid:f.length===0,errors:f,warnings:u}}validateObjectAgainstSchema(i,o,c,f,u,g){if(g.validateTypes&&o.type){let h=Array.isArray(i)?"array":typeof i,d=Array.isArray(o.type)?o.type:[o.type];if(!d.includes(h)){if(f.push({path:c,message:`Expected type ${d.join(" or ")}, got ${h}`,expected:d.join(" or "),actual:h,rule:"type"}),g.stopOnFirstError)return}}if(o.enum&&!o.enum.includes(i)){if(f.push({path:c,message:`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"}),g.stopOnFirstError)return}if(typeof i==="string"){if(o.minLength!==void 0&&i.length<o.minLength)f.push({path:c,message:`String length must be at least ${o.minLength}`,expected:`>= ${o.minLength}`,actual:i.length,rule:"minLength"});if(o.maxLength!==void 0&&i.length>o.maxLength)f.push({path:c,message:`String length must not exceed ${o.maxLength}`,expected:`<= ${o.maxLength}`,actual:i.length,rule:"maxLength"});if(o.pattern){if(!new RegExp(o.pattern).test(i))f.push({path:c,message:`String does not match pattern ${o.pattern}`,expected:o.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(o.minimum!==void 0&&i<o.minimum)f.push({path:c,message:`Value must be at least ${o.minimum}`,expected:`>= ${o.minimum}`,actual:i,rule:"minimum"});if(o.maximum!==void 0&&i>o.maximum)f.push({path:c,message:`Value must not exceed ${o.maximum}`,expected:`<= ${o.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&o.items)for(let h=0;h<i.length;h++){let d=c?`${c}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema(i[h],o.items,d,f,u,g),g.stopOnFirstError&&f.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let h=i;if(g.validateRequired&&o.required){for(let d of o.required)if(!(d in h)){if(f.push({path:c?`${c}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),g.stopOnFirstError)return}}if(o.properties){for(let[d,p]of Object.entries(o.properties))if(d in h){let y=c?`${c}.${d}`:d;if(this.validateObjectAgainstSchema(h[d],p,y,f,u,g),g.stopOnFirstError&&f.length>0)return}}if(o.additionalProperties===!1){let d=new Set(Object.keys(o.properties||{}));for(let p of Object.keys(h))if(!d.has(p))u.push({path:c?`${c}.${p}`:p,message:`Additional property '${p}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,o,c){let f=[],u=[];for(let g of o)try{let h=this.getValueByPath(i,g.path),d=this.validateWithRule(h,g,g.path);if(f.push(...d),c.stopOnFirstError&&f.length>0)break}catch(h){f.push({path:g.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:f.length===0,errors:f,warnings:u}}validateWithRule(i,o,c){let f=[];if(o.required&&(i===void 0||i===null))return f.push({path:c,message:o.message||`Property '${c}' is required`,expected:"required",rule:"required"}),f;if(i===void 0||i===null)return f;if(o.type){let u=Array.isArray(i)?"array":typeof i;if(u!==o.type)f.push({path:c,message:o.message||`Expected type ${o.type}, got ${u}`,expected:o.type,actual:u,rule:"type"})}if(o.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<o.min)f.push({path:c,message:o.message||`Value must be at least ${o.min}`,expected:`>= ${o.min}`,actual:u,rule:"min"})}if(o.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>o.max)f.push({path:c,message:o.message||`Value must not exceed ${o.max}`,expected:`<= ${o.max}`,actual:u,rule:"max"})}if(o.pattern&&typeof i==="string"){if(!o.pattern.test(i))f.push({path:c,message:o.message||`Value does not match pattern ${o.pattern}`,expected:o.pattern.toString(),actual:i,rule:"pattern"})}if(o.enum&&!o.enum.includes(i))f.push({path:c,message:o.message||`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"});if(o.validator){let u=o.validator(i);if(u)f.push({path:c,message:o.message||u,rule:"custom"})}return f}getValueByPath(i,o){if(!o)return i;let c=o.split("."),f=i;for(let u of c)if(f&&typeof f==="object"&&u in f)f=f[u];else return;return f}generateRulesFromInterface(i){let o=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let f of c){let[,u,g,h]=f;o.push({path:u,required:!g,type:this.mapTypeScriptType(h)})}return o}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Zo},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ie=new It("bunfig",{showTags:!0});function Xo(i){if(!i)return"";let o=Array.isArray(i)?i.filter(Boolean):[i];if(o.length===0)return"";if(o.length===1)return` or alias "${o[0]}"`;return` or aliases ${o.map((c)=>`"${c}"`).join(", ")}`}class vs{fileLoader=new bs;envProcessor=new Or;validator=new Ss;async loadConfig(i){let o=Date.now(),{cache:c,performance:f,schema:u,validate:g,...h}=i;try{if(c?.enabled){let p=this.checkCache(h.name||"",h);if(p)return p}let d;try{d=await this.loadConfigurationStrategies(h,!0,c)}catch(p){if(h.configFile)throw p;let y=h.__strictErrorHandling;if(p instanceof Error&&p.name==="ConfigNotFoundError"){if(y)throw p;d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(p instanceof Error&&p.name==="ConfigLoadError"){let w=p.message.includes("EACCES")||p.message.includes("EPERM")||p.message.includes("permission denied"),S=!w&&(p.message.includes("syntax")||p.message.includes("Expected")||p.message.includes("Unexpected")||p.message.includes("BuildMessage")||p.message.includes("errors building")),E=p.message.includes("Configuration must export a valid object")||p.message.includes("Configuration file is empty and exports nothing");if(y&&(E||w))throw p;if(S&&(!y||!E))d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${p.message}`]};else throw p}else d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${p instanceof Error?p.message:String(p)}`]}}if(u||g)await this.validateConfiguration(d.config,u,g,h.name);if(c?.enabled&&d)this.cacheResult(h.name||"",d,c,h);if(f?.enabled){let p={operation:"loadConfig",duration:Date.now()-o,configName:h.name,timestamp:new Date};if(f.onMetrics)f.onMetrics(p);if(f.slowThreshold&&p.duration>f.slowThreshold)ie.warn(`Slow configuration loading detected: ${p.duration}ms for ${h.name}`);d.metrics=p}return d}catch(d){if(d instanceof Error&&d.name==="ConfigNotFoundError")throw d;let p=Date.now()-o;throw ie.error(`Configuration loading failed after ${p}ms:`,[d instanceof Error?d:Error(String(d))]),d}}async loadConfigurationStrategies(i,o=!1,c){let{name:f="",alias:u,configFile:g,cwd:h,configDir:d,defaultConfig:p,checkEnv:y=!0,arrayStrategy:w="replace",verbose:S=!1}=i,E=h||Nt.cwd(),v=[];if(g){let K=ce(E,g);v.push(K);let ne=y?Ne(f,p,S):p,Z=await this.fileLoader.tryLoadFromPaths([K],ne,{arrayStrategy:w,verbose:S,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(!Z)throw ye.configNotFound(f||g,v,u);if(S)ie.success(`Configuration loaded from explicit path: ${K}`);return this.finalizeResult(Z,v,y,f,S)}let x=await this.loadLocalConfiguration(f,u,E,d,p,w,S,y,c);if(x)return v.push(...this.getLocalSearchPaths(f,u,E,d)),this.finalizeResult(x,v,y,f,S);let C=await this.loadHomeConfiguration(f,u,p,w,S,y);if(C)return v.push(...this.getHomeSearchPaths(f,u)),this.finalizeResult(C,v,y,f,S);let A=await this.loadPackageJsonConfiguration(f,u,E,p,w,S,y);if(A)return v.push(ce(E,"package.json")),this.finalizeResult(A,v,y,f,S);if(v.push(...this.getAllSearchPaths(f,u,E,d)),o)throw ye.configNotFound(f,v,u);return{...await this.applyEnvironmentVariables(f,p,y,S),warnings:[`No configuration file found for "${f}"${Xo(u)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,o,c,f,u,g,h,d,p){let y=d?Ne(i,u,h):u,w=this.getLocalDirectories(c,f);for(let S of w){if(h)ie.info(`Searching for configuration in: ${S}`);let E=this.fileLoader.generateConfigPaths(i,S,o),v=await this.fileLoader.tryLoadFromPaths(E,y,{arrayStrategy:g,verbose:h,cacheTtl:p?.ttl,useCache:!p?.ttl||p.ttl>100});if(v){if(h)ie.success(`Configuration loaded from: ${v.source.path}`);return v}}return null}async loadHomeConfiguration(i,o,c,f,u,g){if(!i)return null;let h=g?Ne(i,c,u):c,d=[ce(be(),".config",i),ce(be(),".config"),be()];for(let p of d){if(u)ie.info(`Checking home directory: ${p}`);let y=this.fileLoader.generateConfigPaths(i,p,o),w=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:u});if(w){if(u)ie.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(i,o,c,f,u,g,h){let d=h?Ne(i,f,g):f;try{let p=ce(c,"package.json");if(!Us(p))return null;let y={};try{y=JSON.parse(qs(p,"utf8"))}catch(E){if(g)ie.warn("Failed to parse package.json:",[E instanceof Error?E:Error(String(E))]);return null}let w=y[i],S=i;if(!w&&o){let E=Array.isArray(o)?o:[o];for(let v of E){if(!v)continue;if(y[v]){w=y[v],S=v;break}}}if(w&&typeof w==="object"&&!Array.isArray(w)){if(g)ie.success(`Configuration loaded from package.json: ${S}`);return{config:ws(d,w,u),source:{type:"package.json",path:p,priority:30,timestamp:new Date}}}}catch(p){if(g)ie.warn("Failed to load package.json:",[p instanceof Error?p:Error(String(p))])}return null}async applyEnvironmentVariables(i,o,c,f){if(!c||!i||typeof o!=="object"||o===null||Array.isArray(o))return{config:o,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ne(i,o,f),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,o,c,f,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,o,c,f){let u=[];if(c){let g=c(i);if(g)u.push(...g)}if(o){let g=await this.validator.validateConfiguration(i,o);if(!g.isValid)u.push(...g.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(u.length>0)throw ye.configValidation(f||"unknown",u,f)}checkCache(i,o){let c=this.generateCacheKey(i,o);return bt.get(c)||null}cacheResult(i,o,c,f){let u=this.generateCacheKey(i,f);bt.set(u,o,void 0,c.ttl)}generateCacheKey(i,o){let c=[i];if(o.alias){let f=Array.isArray(o.alias)?o.alias.join(","):o.alias;c.push(`alias:${f}`)}if(o.cwd)c.push(`cwd:${o.cwd}`);if(o.configFile)c.push(`configFile:${o.configFile}`);if(o.configDir)c.push(`configDir:${o.configDir}`);if("checkEnv"in o)c.push(`checkEnv:${o.checkEnv}`);return c.join("|")}getLocalDirectories(i,o){return Qs({cwd:i,configDir:o})}getAllSearchPaths(i,o,c,f){let u=[];return u.push(...this.getLocalSearchPaths(i,o,c,f)),u.push(...this.getHomeSearchPaths(i,o)),u.push(ce(c,"package.json")),u}getLocalSearchPaths(i,o,c,f){let u=this.getLocalDirectories(c,f),g=[];for(let h of u)g.push(...this.fileLoader.generateConfigPaths(i,h,o));return g}getHomeSearchPaths(i,o){if(!i)return[];let c=[ce(be(),".config",i),ce(be(),".config"),be()],f=[];for(let u of c)f.push(...this.fileLoader.generateConfigPaths(i,u,o));return f}async loadConfigWithResult(i){return this.loadConfig(i)}}var lr=new vs;async function Es(i){let o="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let f;if(c)f=await lr.loadConfig(i);else f=await lr.loadConfig({...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}});return f?.config??o}catch(f){if(i.configFile)throw f;let u=f instanceof Error?f.name:"UnknownError",g=f instanceof Error?f.message:String(f);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||g.includes("config"))&&i.verbose)ie.warn("Unexpected error loading config, using defaults:",[f instanceof Error?f:Error(String(f))]);let d=c?{...i,defaultConfig:o}:{...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await lr.applyEnvironmentVariables(d.name||"",o,!0,d.verbose||!1))?.config??o;return o}}function Ne(i,o,c=!1){let f=new Or,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function g(h,d=[]){let p={...h};for(let[y,w]of Object.entries(h)){let S=[...d,y],E=[`${u}_${S.join("_").toUpperCase()}`,`${u}_${S.map((C)=>C.toUpperCase()).join("")}`,`${u}_${S.map((C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],v,x;for(let C of E)if(v=Nt.env[C],v!==void 0){x=C;break}if(v!==void 0&&x)if(typeof w==="boolean")p[y]=["true","1","yes"].includes(v.toLowerCase());else if(typeof w==="number"){let C=Number(v);if(!Number.isNaN(C))p[y]=C}else if(Array.isArray(w))try{p[y]=JSON.parse(v)}catch{p[y]=v.split(",").map((C)=>C.trim())}else p[y]=v;else if(w&&typeof w==="object"&&!Array.isArray(w))p[y]=g(w,S)}return p}return g(o)}var il=ce(Nt.cwd(),"config"),ol=ce(Nt.cwd(),"src/generated");function n(i=e.dialect){return i==="mysql"||i==="singlestore"||i==="vitess"}var nt={verbose:!0,snapshotDir:".qb",migrationDir:"database/migrations",dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},vitess:{sharded:!0},timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},pagination:{defaultPerPage:25,cursorColumn:"id"},aliasing:{relationColumnAliasFormat:"table_column"},relations:{foreignKeyFormat:"singularParent_id",maxDepth:10,maxEagerLoad:50,detectCycles:!0},transactionDefaults:{retries:2,isolation:"read committed",sqlStates:["40001","40P01"],backoff:{baseMs:50,factor:2,maxMs:2000,jitter:!0}},sql:{randomFunction:"RANDOM()",sharedLockSyntax:"FOR SHARE",jsonContainsMode:"operator"},features:{distinctOn:!0},debug:{captureText:!0},hooks:{},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0}},Ts=new Set(["__proto__","constructor","prototype"]);function Cs(i){if(i===null||typeof i!=="object"||Array.isArray(i))return!1;let o=Object.getPrototypeOf(i);return o===Object.prototype||o===null}function Pr(i,o,c=new Set){let f={...i};c.add(o);for(let u of Object.keys(o)){if(Ts.has(u))continue;let g=o[u];if(Cs(g)&&!c.has(g)){let h=f[u];f[u]=Pr(Cs(h)?h:{},g,c)}else f[u]=g}return c.delete(o),f}var ea=Symbol.for("bun-query-builder.config"),e=globalThis[ea]??=Pr({},nt),ta=Symbol.for("bun-query-builder.config-state"),_t=globalThis[ta]??={explicit:new Set,fileLoaded:!1};function P(i){if(i)return rt(i);let o=$s.env.DB_DIALECT||$s.env.DB_CONNECTION;if(o)return rt(o);return e.dialect||"postgres"}function rt(i){let o=i.trim().toLowerCase();if(o==="turso"||o==="libsql")return"sqlite";return o}function t(i){if(e.dialect==="postgres")return`$${i}`;return"?"}function s(i,o=1){if(i<=0)return"";if(e.dialect==="postgres"){let c=`$${o}`;for(let f=1;f<i;f++)c+=`, $${o+f}`;return c}return i===1?"?":`?${", ?".repeat(i-1)}`}async function B(){if(!_t.fileLoaded){_t.fileLoaded=!0;let i=await Es({name:"query-builder",alias:"qb",defaultConfig:nt}),o={};for(let[c,f]of Object.entries(i??{}))if(!_t.explicit.has(c))o[c]=f;As(o)}return e}var Ue=null,xs=new Set;function As(i){let o=Pr(e,i),c=e;for(let f of Object.keys(o)){if(Ts.has(f))continue;c[f]=o[f]}}function _e(i){if(i.dialect&&Ue&&i.dialect!==Ue){let o=`${Ue}->${i.dialect}`;if(!xs.has(o))xs.add(o),console.warn(`[query-builder] Configuring dialect '${i.dialect}' overrides the previously configured dialect '${Ue}'. Config is process-wide (setConfig, db.configure and query-builder.config.ts all write it); in-flight queries from the previous configuration may break. `+"Run conflicting connections in separate processes \u2014 see stacksjs/stacks#1862 #18.")}if(i.dialect)Ue=i.dialect;for(let o of Object.keys(i))_t.explicit.add(o);As(i)}function dn(i){return i}function it(i){return typeof i==="string"&&/^(?:libsql|https?|wss?):\/\//i.test(i.trim())}function fn(i){let o;try{o=new URL(i.trim())}catch{throw new a("Invalid libSQL URL: expected libsql://, https://, http://, ws:// or wss://",{code:"LIBSQL_INVALID_URL"})}let c=o.protocol.replace(/:$/,"").toLowerCase(),f=o.searchParams.get("tls"),u=f==="0"||f==="false",g=o.searchParams.get("authToken")??void 0,h;switch(c){case"libsql":h=u?"http":"https";break;case"https":case"wss":h="https";break;case"http":case"ws":h="http";break;default:throw new a(`Unsupported libSQL URL scheme '${c}:'`,{code:"LIBSQL_INVALID_URL"})}if(o.username||o.password)throw new a("libSQL URLs must not embed credentials; pass the token as authToken",{code:"LIBSQL_INVALID_URL"});let d=o.pathname.replace(/\/+$/,"");return{baseUrl:`${h}://${o.host}${d}`,authToken:g||void 0}}var ra=[[/^UNIQUE constraint failed/i,"SQLITE_CONSTRAINT_UNIQUE",2067],[/^NOT NULL constraint failed/i,"SQLITE_CONSTRAINT_NOTNULL",1299],[/^FOREIGN KEY constraint failed/i,"SQLITE_CONSTRAINT_FOREIGNKEY",787],[/^CHECK constraint failed/i,"SQLITE_CONSTRAINT_CHECK",275]],Ls={SQLITE_ERROR:1,SQLITE_INTERNAL:2,SQLITE_PERM:3,SQLITE_ABORT:4,SQLITE_BUSY:5,SQLITE_LOCKED:6,SQLITE_NOMEM:7,SQLITE_READONLY:8,SQLITE_INTERRUPT:9,SQLITE_IOERR:10,SQLITE_CORRUPT:11,SQLITE_FULL:13,SQLITE_CANTOPEN:14,SQLITE_SCHEMA:17,SQLITE_TOOBIG:18,SQLITE_CONSTRAINT:19,SQLITE_MISMATCH:20,SQLITE_MISUSE:21,SQLITE_RANGE:25};class a extends Error{code;errno;libsqlCode;status;constructor(i,o){super(i,o.cause===void 0?void 0:{cause:o.cause});this.name="LibSQLError",this.code=o.code,this.errno=o.errno,this.libsqlCode=o.libsqlCode,this.status=o.status}}function Ie(i){let c=String(i.message??"libSQL statement failed").replace(/^SQLite error:\s*/i,""),f=i.code??void 0;for(let[u,g,h]of ra)if(u.test(c))return new a(c,{code:g,errno:h,libsqlCode:f});if(f&&f in Ls)return new a(c,{code:f,errno:Ls[f],libsqlCode:f});if(f==="SQL_PARSE_ERROR"||f==="SQL_INPUT_ERROR")return new a(c,{code:"SQLITE_ERROR",errno:1,libsqlCode:f});return new a(c,{code:f??"LIBSQL_ERROR",libsqlCode:f})}var na=-(2n**63n),sa=2n**63n-1n;function Nr(i){return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function jt(i){if(i===null||i===void 0)return{type:"null"};switch(typeof i){case"string":return{type:"text",value:i};case"boolean":return{type:"integer",value:i?"1":"0"};case"number":if(!Number.isFinite(i))throw RangeError(`Cannot bind ${i} to a libSQL statement: only finite numbers are allowed`);return Number.isSafeInteger(i)?{type:"integer",value:String(i===0?0:i)}:{type:"float",value:i};case"bigint":if(i<na||i>sa)throw RangeError(`Cannot bind ${i} to a libSQL statement: it does not fit in a 64-bit integer`);return{type:"integer",value:i.toString()}}if(i instanceof Date){if(Number.isNaN(i.getTime()))throw RangeError("Cannot bind an invalid Date to a libSQL statement");return{type:"text",value:i.toISOString()}}if(i instanceof Uint8Array)return{type:"blob",base64:Nr(i)};if(i instanceof ArrayBuffer)return{type:"blob",base64:Nr(new Uint8Array(i))};if(ArrayBuffer.isView(i))return{type:"blob",base64:Nr(new Uint8Array(i.buffer,i.byteOffset,i.byteLength))};throw TypeError(`Cannot bind a value of type ${Object.prototype.toString.call(i).slice(8,-1)} to a libSQL statement; serialize it first (e.g. JSON.stringify)`)}function qt(i,o="bigint"){switch(i.type){case"null":return null;case"integer":{let c=Number(i.value);if(Number.isSafeInteger(c))return c;return o==="string"?i.value:BigInt(i.value)}case"float":return typeof i.value==="number"?i.value:Number(i.value);case"text":return i.value;case"blob":{let c=Buffer.from(i.base64??"","base64");return new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}default:throw new a(`Unknown libSQL value type '${i.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"})}}function mn(i,o="bigint"){let c=i.cols.map((d,p)=>d.name??String(p)),f=i.rows.map((d)=>{let p={};for(let y=0;y<c.length;y++)p[c[y]]=qt(d[y]??{type:"null"},o);return p}),u=Number(i.affected_row_count??0),g=i.last_insert_rowid==null?null:qt({type:"integer",value:i.last_insert_rowid},o),h=(d)=>({value:d,enumerable:!1,writable:!0,configurable:!0});return Object.defineProperties(f,{changes:h(u),count:h(u>0?u:f.length),lastInsertRowid:h(g),columns:h(c)}),f}function Le(i,o=[]){if(!Array.isArray(o)){let f=Object.entries(o).map(([u,g])=>({name:/^[:@$]/.test(u)?u:`:${u}`,value:jt(g)}));return{sql:i,named_args:f,want_rows:!0}}let c=Mt(i,[...o]);return{sql:c.sql,args:c.params.map(jt),want_rows:!0}}var ia=/^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i,oa=/^\s*PRAGMA\s+(?:main\.)?foreign_keys\s*(?:=\s*|\(\s*)['"]?(\w+)['"]?\s*\)?\s*;?\s*$/i;function aa(i){let o=oa.exec(i);return o?o[1].toUpperCase():null}class Os{baseUrl;authToken;timeoutMs;fetchImpl;constructor(i){let o=fn(i.url);this.baseUrl=o.baseUrl,this.authToken=i.authToken||o.authToken,this.timeoutMs=i.timeoutMs,this.fetchImpl=i.fetch??fetch}async pipeline(i,o,c){let f={"content-type":"application/json"};if(this.authToken)f.authorization=`Bearer ${this.authToken}`;let u;try{u=await this.fetchImpl(`${i}/v3/pipeline`,{method:"POST",headers:f,body:JSON.stringify({baton:o,requests:c}),signal:this.timeoutMs?AbortSignal.timeout(this.timeoutMs):void 0})}catch(h){let d=h instanceof Error?h.message:String(h);throw new a(`Could not reach the libSQL server at ${this.baseUrl}: ${d}`,{code:"LIBSQL_CONNECTION_FAILED",cause:h})}if(!u.ok){let h=await ca(u),d=h?` (${h})`:"";if(u.status===401||u.status===403)throw new a(`The libSQL server at ${this.baseUrl} rejected the request: HTTP ${u.status}${d}. `+(this.authToken?"The auth token was refused - check that it belongs to this database and has not expired.":"No auth token was sent - set one (TURSO_AUTH_TOKEN in Stacks)."),{code:"LIBSQL_UNAUTHORIZED",status:u.status});if(u.status===404)throw new a(`The libSQL server at ${this.baseUrl} has no Hrana v3 pipeline endpoint (HTTP 404). Check the URL, and that the server is sqld 0.21+ or Turso.`,{code:"LIBSQL_NOT_FOUND",status:404});throw new a(`The libSQL server at ${this.baseUrl} answered HTTP ${u.status}${d}`,{code:"LIBSQL_HTTP_ERROR",status:u.status})}let g=await u.json();if(!g||!Array.isArray(g.results))throw new a(`The libSQL server at ${this.baseUrl} sent a reply that is not a Hrana pipeline response`,{code:"LIBSQL_PROTOCOL_ERROR"});return g}}async function ca(i){try{let o=(await i.text()).trim();if(!o)return"";try{let c=JSON.parse(o),f=c.error??c.message;if(typeof f==="string")return f}catch{}return o.slice(0,300)}catch{return""}}class Ps{http;prelude;baton=null;baseUrl;tail=Promise.resolve();opened=!1;closed=!1;constructor(i,o){this.http=i;this.prelude=o;this.baseUrl=i.baseUrl}send(i,o={}){let c=async()=>{if(this.closed)throw new a("This libSQL stream is closed",{code:"LIBSQL_STREAM_CLOSED"});let u=this.opened?[]:this.prelude();this.opened=!0;let g=[...u,...i];if(o.close)g.push({type:"close"});let h;try{h=await this.http.pipeline(this.baseUrl,this.baton,g)}catch(d){throw this.closed=!0,d}if(this.baton=h.baton,h.base_url)this.baseUrl=h.base_url.replace(/\/+$/,"");if(o.close||h.baton===null)this.closed=!0;for(let d=0;d<u.length;d++){let p=h.results[d];if(p?.type==="error")throw Ie(p.error)}return h.results.slice(u.length,u.length+i.length)},f=this.tail.then(c,c);return this.tail=f.catch(()=>{}),f}async close(){if(this.closed)return;if(!this.opened){this.closed=!0;return}await this.send([],{close:!0})}}function He(i){if(!i)throw new a("The libSQL server sent fewer results than requests",{code:"LIBSQL_PROTOCOL_ERROR"});if(i.type==="error")throw Ie(i.error);if(i.response.type!=="execute")throw new a(`Expected an execute result, got '${i.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});return i.response.result}function ks(i){if(i?.type==="ok"&&i.response.type==="get_autocommit")return i.response.is_autocommit;return!1}class Ns{http;largeIntegers;foreignKeys=null;pinned=null;closed=!1;constructor(i){this.http=new Os(i),this.largeIntegers=i.largeIntegers??"bigint"}prelude=()=>this.foreignKeys?[{type:"execute",stmt:{sql:`PRAGMA foreign_keys = ${this.foreignKeys}`,want_rows:!1}}]:[];openStream(){return this.assertOpen(),new Ps(this.http,this.prelude)}assertOpen(){if(this.closed)throw new a("Cannot use a closed libSQL connection",{code:"LIBSQL_CLOSED"})}rows(i){return mn(i,this.largeIntegers)}notePragma(i){let o=aa(i);if(o)this.foreignKeys=o==="OFF"||o==="0"||o==="FALSE"||o==="NO"?"OFF":"ON"}async execute(i){this.assertOpen();let o=ia.test(i.sql);if(this.pinned){let g=this.pinned,h=[{type:"execute",stmt:i}];if(o)h.push({type:"get_autocommit"});let d;try{d=await g.send(h)}catch(y){if(this.pinned===g)this.pinned=null;throw y}if(o&&ks(d[1])){if(this.pinned===g)this.pinned=null;await g.close().catch(()=>{})}let p=this.rows(He(d[0]));return this.notePragma(i.sql),p}if(o){let g=this.openStream(),h;try{h=await g.send([{type:"execute",stmt:i},{type:"get_autocommit"}])}catch(p){throw await g.close().catch(()=>{}),p}if(h[0]?.type!=="error"&&!ks(h[1]))this.pinned=g;else await g.close().catch(()=>{});return this.rows(He(h[0]))}let c=this.openStream(),[f]=await c.send([{type:"execute",stmt:i}],{close:!0}),u=this.rows(He(f));return this.notePragma(i.sql),u}async close(){this.closed=!0;let i=this.pinned;this.pinned=null,await i?.close().catch(()=>{})}}function Fs(i,o){return{async execute(c){let[f]=await o.send([{type:"execute",stmt:c}]),u=i.rows(He(f));return i.notePragma(c.sql),u},async sequence(c){let f=[];for(let u of c)f.push(await this.execute(u));return f}}}function la(i){return{execute:(o)=>i.execute(o),async sequence(o){if(i.pinned){let f=[];for(let u of o)f.push(await i.execute(u));return f}let c=i.openStream();try{let f=[];for(let u of o)f.push(await Fs(i,c).execute(u));return f}finally{await c.close().catch(()=>{})}}}}function Rs(i){return{__raw:!0,value:i,toString:()=>i}}function fa(i,o){let c=i[0],f=[];for(let u=0;u<o.length;u++){let g=o[u],h=Ir(g);if(h&&typeof h.sql==="string"&&Array.isArray(h.values))c+=h.sql+(i[u+1]||""),f.push(...h.values);else if(h&&(h.__raw||h.raw)){let d=h.raw,p=h.__raw?h.value:typeof d==="string"?d:d();c+=p+(i[u+1]||"")}else if(Array.isArray(g))c+=g.map(()=>"?").join(", ")+(i[u+1]||""),f.push(...g);else c+=`?${i[u+1]||""}`,f.push(g)}return{sql:c,params:f}}function Fr(i,o,c,f){let u=()=>{try{return i.target.execute(Le(o,c))}catch(h){return Promise.reject(h)}},g={sql:o,values:c,execute:u,raw:()=>o,toString:()=>o,cancel:()=>{}};if(f)g.then=(h,d)=>u().then(h,d);return g}function Dr(i){function o(c,...f){if(Array.isArray(c)&&"raw"in c){let{sql:u,params:g}=fa(c,f);return Fr(i,u,g,!1)}if(typeof c==="string")return Rs(c);return Fr(i,"",[],!1)}return o.raw=(c)=>Rs(c),o.unsafe=(c,f=[])=>Fr(i,c,f??[],!0),o.query=(c,f)=>{try{return i.target.execute(Le(c,f??[]))}catch(u){return Promise.reject(u)}},o.file=async(c)=>{let{readFileSync:f}=await import("fs"),u=_r(f(c,"utf-8")).map((g)=>g.trim()).filter((g)=>g&&!g.startsWith("--"));return await i.target.sequence(u.map((g)=>Le(g))),[]},o.batch=async(c)=>{if(i.session.assertOpen(),c.length===0)return[];let f=i.stream!==null,u=c.map((E)=>Le(E.sql,E.args??[])),g=[];if(!f)g.push({stmt:{sql:"BEGIN"}});for(let E of u)g.push({stmt:E,condition:g.length?{type:"ok",step:g.length-1}:null});if(!f){let E=g.length-1;g.push({stmt:{sql:"COMMIT"},condition:{type:"ok",step:E}}),g.push({stmt:{sql:"ROLLBACK"},condition:{type:"not",cond:{type:"ok",step:E+1}}})}let h=i.stream??i.session.openStream(),d;try{d=await h.send([{type:"batch",batch:{steps:g}}],{close:!f})}finally{if(!f)await h.close().catch(()=>{})}let p=d[0];if(!p)throw new a("The libSQL server sent no batch result",{code:"LIBSQL_PROTOCOL_ERROR"});if(p.type==="error")throw Ie(p.error);if(p.response.type!=="batch")throw new a(`Expected a batch result, got '${p.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});let{step_results:y,step_errors:w}=p.response.result,S=f?0:1;for(let E=0;E<w.length;E++){let v=w[E];if(v)throw Ie(v)}return u.map((E,v)=>{let x=y[v+S];if(!x)throw new a(`Batch statement ${v+1} did not run`,{code:"LIBSQL_BATCH_SKIPPED"});return i.session.rows(x)})},o.begin=async(c,f)=>{let u=typeof c==="function"?c:f;if(typeof u!=="function")throw TypeError("[query-builder] libsql begin(): a transaction callback is required");if(i.session.assertOpen(),i.stream){let w=`qb_sp_${i.depth}`,S=i.target;await S.execute({sql:`SAVEPOINT ${w}`});let E=Dr({...i,depth:i.depth+1});try{let v=await u(E);return await S.execute({sql:`RELEASE SAVEPOINT ${w}`}),v}catch(v){try{await S.execute({sql:`ROLLBACK TO SAVEPOINT ${w}`}),await S.execute({sql:`RELEASE SAVEPOINT ${w}`})}catch{}throw v}}let g=i.session.openStream(),h=Fs(i.session,g);try{await h.execute({sql:"BEGIN"})}catch(w){throw await g.close().catch(()=>{}),w}let d=Dr({session:i.session,target:h,stream:g,depth:1}),p;try{p=await u(d)}catch(w){try{await g.send([{type:"execute",stmt:{sql:"ROLLBACK"}}],{close:!0})}catch{await g.close().catch(()=>{})}throw w}let[y]=await g.send([{type:"execute",stmt:{sql:"COMMIT"}}],{close:!0});return He(y),p},o.savepoint=o.begin,o.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on libSQL. Use begin()/transaction().")},o.close=async()=>{if(i.stream)return;await i.session.close()},o.libsql={url:i.session.http.baseUrl,transaction:i.stream!==null},o}function Wt(i){let o=new Ns(i);return Dr({session:o,target:la(o),stream:null,depth:0})}function Wn(i){return(typeof i==="function"||typeof i==="object"&&i!==null)&&typeof i.libsql==="object"&&i.libsql!==null}var Ut=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"];function Vt(){let i=e.sqlite?.pragmas;return Array.isArray(i)?i:Ut}function k(i){for(let o of Vt())try{i.run(o)}catch{}}function ze(i){return`"${i.replaceAll('"','""')}"`}class Mr{database;pending=[];bytes=0;timer;closed=!1;failure;constructor(i){this.database=i}get hasPending(){return this.pending.length>0}append=(i,o)=>{if(this.failure)return Promise.reject(this.failure);if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));let c=Object.keys(o),f=c.map((h)=>{let d=o[h];if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength).slice();return d??null}),u=JSON.stringify([i,c]),g=512+u.length*2+f.reduce((h,d)=>h+(typeof d==="string"?d.length*2:ArrayBuffer.isView(d)?d.byteLength:16),0);if(this.hasPending&&(this.pending.length>=32||this.bytes+g>262144))this.flush();return new Promise((h,d)=>{let p={table:i,columns:c,values:f,shape:u,uncached:g>262144,resolve:h,reject:d};if(this.database.inTransaction||g>262144){this.writeOne(p);return}this.pending.push(p),this.bytes+=g,this.timer??=setImmediate(()=>this.flush())})};flush(){if(this.timer!==void 0)clearImmediate(this.timer),this.timer=void 0;let i=this.pending;this.pending=[],this.bytes=0;for(let o=0;o<i.length;){if(this.failure){for(let u of i.slice(o))u.reject(this.failure);return}let c=o+1;while(c<i.length&&i[c].shape===i[o].shape)c++;let f=i.slice(o,c);if(o=c,f.length===1||!f[0].columns.length||this.database.inTransaction){for(let u of f)this.writeOne(u);continue}try{this.database.transaction(()=>{let u=f[0],g=`(${u.columns.map(()=>"?").join(",")})`,h=`INSERT INTO ${ze(u.table)} (${u.columns.map(ze).join(",")}) VALUES ${f.map(()=>g).join(",")}`;this.database.query(h).run(...f.flatMap((d)=>d.values))})();for(let u of f)u.resolve()}catch(u){if(this.database.inTransaction){this.invalidate(u);for(let g of[...f,...i.slice(o)])g.reject(u);return}for(let g of f)this.writeOne(g)}}}writeOne(i){let o=!1;try{this.assertUsable(),o=this.database.inTransaction;let c=i.columns.length?`INSERT INTO ${ze(i.table)} (${i.columns.map(ze).join(",")}) VALUES (${i.columns.map(()=>"?").join(",")})`:`INSERT INTO ${ze(i.table)} DEFAULT VALUES`,f=()=>{if(!i.uncached)return this.database.query(c).run(...i.values);let u=this.database.prepare(c);try{return u.run(...i.values)}finally{u.finalize()}};if(o)f();else this.database.transaction(f)();i.resolve()}catch(c){if(!this.failure&&!o&&this.database.inTransaction)this.invalidate(c);i.reject(c)}}assertUsable(){if(this.failure)throw this.failure}invalidate(i){this.failure=Error("SQLite connection is unusable after deferred insert rollback failed",{cause:i});try{this.database.close()}catch{}}close(){this.closed=!0,this.flush()}}function Br(i){return i}function Ir(i){return i!==null&&typeof i==="object"?i:null}function Mt(i,o){if(o.length===0||!/\$\d/.test(i))return{sql:i,params:o};let c=[],f="",u=0;for(let g=0;g<i.length;g++){let h=i[g];if(h==="'"||h==='"'||h==="`"){let d=da(i,g,h);f+=i.slice(g,d),g=d-1;continue}if(h==="-"&&i[g+1]==="-"){let d=i.indexOf(`
|
|
62
62
|
`,g),p=d===-1?i.length:d;f+=i.slice(g,p),g=p-1;continue}if(h==="/"&&i[g+1]==="*"){let d=i.indexOf("*/",g+2),p=d===-1?i.length:d+2;f+=i.slice(g,p),g=p-1;continue}if(h==="$"){let d=/^\d+/.exec(i.slice(g+1))?.[0];if(d){let p=Number(d);if(u=Math.max(u,p),p>=1&&p<=o.length){c.push(o[p-1]),f+="?",g+=d.length;continue}}}f+=h}if(u>o.length)throw Error(`SQL references $${u} but only ${o.length} value${o.length===1?" was":"s were"} provided`);if(c.length===0)return{sql:i,params:o};return{sql:f,params:c}}function da(i,o,c){for(let f=o+1;f<i.length;f++){if(i[f]!==c)continue;if(i[f+1]===c){f++;continue}return f+1}return i.length}var jr=/^\s*(?:SELECT|WITH|INSERT|UPDATE|DELETE|REPLACE)\b/i;class Bs{db;deferredInserts;closed=!1;constructor(i){if(i!==":memory:"&&!i.startsWith(":")){let o=ga(i);if(o&&o!==".")ha(o,{recursive:!0})}this.db=new ua(i),k(this.db)}deferInsert=(i,o)=>{if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));if(!this.deferredInserts){let c=this.deferredInserts=new Mr(this.db),f=this.query.bind(this),u=this.run.bind(this),g=(h)=>{if(c.hasPending&&!jr.test(h))c.flush();c.assertUsable()};this.query=(h,d)=>(g(h),f(h,d)),this.run=(h,d)=>(g(h),u(h,d))}return this.deferredInserts.append(i,o)};flushDeferredInserts(){this.deferredInserts?.flush()}query(i,o=[]){let c=Mt(i,o),f=c.params.length>0||jr.test(c.sql),u=f?this.db.query(c.sql):this.db.prepare(c.sql);return(f&&c.params.length===0&&u.paramsCount>0?this.db.prepare(c.sql):u).all(...c.params)}run(i,o=[]){let c=Mt(i,o),f=c.params.length>0||jr.test(c.sql),u=f?this.db.query(c.sql):this.db.prepare(c.sql);return(f&&c.params.length===0&&u.paramsCount>0?this.db.prepare(c.sql):u).run(...c.params)}close(){this.closed=!0,this.deferredInserts?.close(),this.db.close()}get database(){return this.db}}function Is(i){return{__raw:!0,value:i,toString:()=>i}}function _s(i){let o=i.trimStart();for(;;)if(o.startsWith("--")){let c=o.indexOf(`
|
|
63
63
|
`);o=c===-1?"":o.slice(c+1).trimStart()}else if(o.startsWith("/*")){let c=o.indexOf("*/");o=c===-1?"":o.slice(c+2).trimStart()}else return o}function _r(i){let o=[],c="",f=!1,u=!1,g=!1,h=!1;for(let p=0;p<i.length;p++){let y=i[p],w=i[p+1];if(!f&&!u&&!h&&y==="-"&&w==="-"){g=!0,c+=y;continue}if(g&&(y===`
|
|
64
|
-
`||y==="\r")){g=!1,c+=y;continue}if(!f&&!u&&!g&&y==="/"&&w==="*"){h=!0,c+=y;continue}if(h&&y==="*"&&w==="/"){h=!1,c+=y+w,p++;continue}if(g||h){c+=y;continue}if(y==="'"&&!u){if(f&&w==="'"){c+=y+w,p++;continue}f=!f,c+=y;continue}if(y==='"'&&!f){u=!u,c+=y;continue}if(y===";"&&!f&&!u){let S=_s(c.trim());if(S)o.push(S);c="";continue}c+=y}let d=_s(c.trim());if(d)o.push(d);return o}function Ms(i){let o=new Bs(i);function c(h,d){let p=h.trim().toUpperCase();if(p.startsWith("SELECT")||p.startsWith("PRAGMA")||/\bRETURNING\b/.test(p))return o.query(h,Br(d));return o.run(h,Br(d))}function f(h,...d){let p=h[0],y=[];for(let S=0;S<d.length;S++){let E=d[S],v=Ir(E);if(v&&typeof v.sql==="string"&&Array.isArray(v.values))p+=v.sql+(h[S+1]||""),y.push(...v.values);else if(v&&(v.__raw||v.raw)){let x=v.raw,C=v.__raw?v.value:typeof x==="string"?x:x();p+=C+(h[S+1]||"")}else if(Array.isArray(E)){let x=E.map(()=>"?").join(", ");p+=x+(h[S+1]||""),y.push(...E)}else p+=`?${h[S+1]||""}`,y.push(E)}let w=()=>c(p,y);return{sql:p,values:y,executeSync:w,execute:()=>{try{return Promise.resolve(w())}catch(S){return Promise.reject(S)}},raw:()=>p,toString:()=>p,cancel:()=>{}}}function u(h,...d){if(Array.isArray(h)&&"raw"in h)return f(h,...d);if(typeof h==="string")return Is(h);return f([""])}u.raw=(h)=>Is(h),u.unsafe=(h,d=[])=>{let p=()=>c(h,d),y=()=>{try{return Promise.resolve(p())}catch(w){return Promise.reject(w)}};return{sql:h,values:d,execute:y,executeSync:p,then:(w,S)=>y().then(w,S),raw:()=>h,toString:()=>h,cancel:()=>{}}},u.deferInsert=o.deferInsert,u.flushDeferredInserts=()=>o.flushDeferredInserts(),u.close=()=>(o.close(),Promise.resolve()),u.query=(h,d)=>{try{let p=o.query(h,Br(d||[]));return Promise.resolve(p)}catch(p){return Promise.reject(p)}},u.file=async(h,d)=>{try{let{readFileSync:p}=await import("fs"),y=p(h,"utf-8"),w=_r(y);for(let S of w){let E=S.trim();if(!E||E.startsWith("--"))continue;let v=E.toUpperCase();if(v.startsWith("SELECT")||v.startsWith("PRAGMA"))o.query(S);else o.run(S)}return Promise.resolve([])}catch(p){return Promise.reject(p)}};let g=0;return u.begin=async(h,d)=>{let p=typeof h==="function"?h:d;if(typeof p!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let y=g>0,w=`qb_sp_${g}`;if(y)o.run(`SAVEPOINT ${w}`);else o.run("BEGIN");g++;try{let S=await p(u);if(g--,y)o.run(`RELEASE SAVEPOINT ${w}`);else o.run("COMMIT");return S}catch(S){g--;try{if(y)o.run(`ROLLBACK TO SAVEPOINT ${w}`),o.run(`RELEASE SAVEPOINT ${w}`);else o.run("ROLLBACK")}catch{}throw S}},u.savepoint=u.begin,u.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},u._wrapper=o,u}function ma(i){let o=i.replace(/^(?:sqlite|sqlite3|file):/i,"");if(o===i)return i;return(o.startsWith("///")?o.slice(2):o.startsWith("//")?o.slice(2):o)||":memory:"}function Ke(i=e.database){let o=Ge.env.DB_DATABASE||i?.database||"";return String(o).replace(/^['"]|['"]$/g,"")}function pa(i,o){if((i==="postgres"||i==="mysql"||i==="singlestore"||i==="vitess")&&Ge.env.DB_CONNECTION===i){let y=Ge.env,w=(y.DB_DATABASE||o.database||"").replace(/^['"]|['"]$/g,""),S=y.DB_USERNAME||o.username,E=y.DB_PASSWORD??o.password??"",v=y.DB_HOST||o.host||"localhost",x=y.DB_PORT||o.port,C=i==="postgres"?"postgres":"mysql",A=y.DB_SSL==="true"||y.DB_SSL==="1"||o.ssl?"?ssl=true":"";return`${C}://${S}:${E}@${v}${x?`:${x}`:""}/${w}${A}`}if(o.url)return i==="sqlite"?ma(o.url):o.url;let{database:c,username:f,password:u,host:g="localhost",port:h,ssl:d}=o,p=d||Ge.env.DB_SSL==="true"||Ge.env.DB_SSL==="1"?"?ssl=true":"";switch(i){case"postgres":return`postgres://${f}:${u}@${g}${h?`:${h}`:""}/${c}${p}`;case"mysql":case"singlestore":case"vitess":return`mysql://${f}:${u}@${g}${h?`:${h}`:""}/${c}${p}`;case"sqlite":if(c===":memory:")return":memory:";return c||":memory:";default:throw Error(`Unsupported dialect: ${i}`)}}function js(i){if(!i)return{};let o={},c=(f)=>Math.max(0,Math.round(f/1000));if(typeof i.max==="number"&&Number.isFinite(i.max))o.max=i.max;if(typeof i.idleTimeoutMs==="number"&&Number.isFinite(i.idleTimeoutMs))o.idleTimeout=c(i.idleTimeoutMs);if(typeof i.acquireTimeoutMs==="number"&&Number.isFinite(i.acquireTimeoutMs))o.connectionTimeout=c(i.acquireTimeoutMs);if(typeof i.maxLifetimeMs==="number"&&Number.isFinite(i.maxLifetimeMs))o.maxLifetime=c(i.maxLifetimeMs);return o}function _(i=e.database,o=e.dialect){if(o!=="sqlite"||!i)return null;let c=it(i.url)?i.url:it(i.database)?i.database:null;if(!c)return null;return{url:c,authToken:i.authToken||void 0}}function ya(){let i=e.dialect,o=_(e.database,i);if(o)return Wt(o);let c=pa(i,e.database);try{if(i==="sqlite")return Ms(c);let f=js(e.database.pool);return Object.keys(f).length>0?new Ds(c,f):new Ds(c)}catch(f){if(console.error(`[query-builder] Failed to create database connection for dialect '${i}': ${f.message}`),i==="sqlite")return Ms(":memory:");throw f}}var Pe=null,Kr=null;function wa(){let i=e.database;return JSON.stringify({dialect:e.dialect,database:i.database,username:i.username,password:i.password,host:i.host,port:i.port,url:i.url,authToken:i.authToken,pool:js(i.pool)})}function b(i=!1){let o=wa();if(i||Pe!==null&&Kr!==o||!Pe)Ks(),Pe=ya(),Kr=o;return Pe}function Ks(){let i=Pe;return i?.flushDeferredInserts?.(),Pe=null,Kr=null,i}async function ba(i){if(!i||typeof i.close!=="function")return;await i.close()}function hn(){ba(Ks()).catch((o)=>{console.error(`[query-builder] Failed to close database connection: ${o.message}`)})}async function st(i){try{return await i(b())}catch(o){if(o?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||o?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let c=b(!0);return await i(c)}throw o}}function Sa(){return new Proxy(function(){},{get(i,o){let c=b(),f=c[o];if(typeof f==="function")return f.bind(c);return f},apply(i,o,c){return b()(...c)}})}var r=Sa();function Fe(i){let o=String(i).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(o.endsWith("y")&&!/[aeou]y$/.test(o))return`${o.slice(0,-1)}ies`;if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return`${o}es`;return`${o}s`}function T(i){return typeof i?.table==="string"&&i.table.length>0?i.table:Fe(String(i?.name??""))}function gn(i){return i.endsWith("s")?i.slice(0,-1):i}function pn(i){if(i.endsWith("ies")&&i.length>3){let o=i.slice(0,-3),c=o[o.length-1];if(c&&!"aeiou".includes(c))return`${o}y`}if(i.endsWith("es")&&i.length>2){let o=i.slice(0,-2);if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return o}if(i.endsWith("s")&&!i.endsWith("ss")&&!i.endsWith("us")&&!i.endsWith("is"))return i.slice(0,-1);return i}function m(i){if(i==="none")return(o)=>o;if(i==="inflect")return pn;return gn}var Ht="1 = 0";function D(i){if(i.length===0)return"";let o=[];for(let c of i)if(c.conn==="OR"&&o.length>0)o[o.length-1].push(c);else o.push([c]);return o.map((c,f)=>{let u=c.map((h)=>h.sql).join(" OR "),g=c.length>1&&o.length>1?`(${u})`:u;return f===0?g:`${c[0].conn} ${g}`}).join(" ")}function l(i,o,c,f){if(o.length===0)return c?"1 = 1":"1 = 0";return`${i} ${c?"NOT IN":"IN"} (${f})`}function at(i,o){if(o!=="postgres")return i;return je(i,(c)=>`$${c}`).text}function X(i){return je(i,()=>{return}).count}function je(i,o){let c="",f=0,u=0,g=0;while(g<i.length){let h=i[g],d=-1;if(h==="'"||h==='"'||h==="`")d=va(i,g,h);else if(h==="-"&&i[g+1]==="-"){let p=i.indexOf(`
|
|
64
|
+
`||y==="\r")){g=!1,c+=y;continue}if(!f&&!u&&!g&&y==="/"&&w==="*"){h=!0,c+=y;continue}if(h&&y==="*"&&w==="/"){h=!1,c+=y+w,p++;continue}if(g||h){c+=y;continue}if(y==="'"&&!u){if(f&&w==="'"){c+=y+w,p++;continue}f=!f,c+=y;continue}if(y==='"'&&!f){u=!u,c+=y;continue}if(y===";"&&!f&&!u){let S=_s(c.trim());if(S)o.push(S);c="";continue}c+=y}let d=_s(c.trim());if(d)o.push(d);return o}function Ms(i){let o=new Bs(i);function c(h,d){let p=h.trim().toUpperCase();if(p.startsWith("SELECT")||p.startsWith("PRAGMA")||/\bRETURNING\b/.test(p))return o.query(h,Br(d));return o.run(h,Br(d))}function f(h,...d){let p=h[0],y=[];for(let S=0;S<d.length;S++){let E=d[S],v=Ir(E);if(v&&typeof v.sql==="string"&&Array.isArray(v.values))p+=v.sql+(h[S+1]||""),y.push(...v.values);else if(v&&(v.__raw||v.raw)){let x=v.raw,C=v.__raw?v.value:typeof x==="string"?x:x();p+=C+(h[S+1]||"")}else if(Array.isArray(E)){let x=E.map(()=>"?").join(", ");p+=x+(h[S+1]||""),y.push(...E)}else p+=`?${h[S+1]||""}`,y.push(E)}let w=()=>c(p,y);return{sql:p,values:y,executeSync:w,execute:()=>{try{return Promise.resolve(w())}catch(S){return Promise.reject(S)}},raw:()=>p,toString:()=>p,cancel:()=>{}}}function u(h,...d){if(Array.isArray(h)&&"raw"in h)return f(h,...d);if(typeof h==="string")return Is(h);return f([""])}u.raw=(h)=>Is(h),u.unsafe=(h,d=[])=>{let p=()=>c(h,d),y=()=>{try{return Promise.resolve(p())}catch(w){return Promise.reject(w)}};return{sql:h,values:d,execute:y,executeSync:p,then:(w,S)=>y().then(w,S),raw:()=>h,toString:()=>h,cancel:()=>{}}},u.deferInsert=o.deferInsert,u.flushDeferredInserts=()=>o.flushDeferredInserts(),u.close=()=>(o.close(),Promise.resolve()),u.query=(h,d)=>{try{let p=o.query(h,Br(d||[]));return Promise.resolve(p)}catch(p){return Promise.reject(p)}},u.file=async(h,d)=>{try{let{readFileSync:p}=await import("fs"),y=p(h,"utf-8"),w=_r(y);for(let S of w){let E=S.trim();if(!E||E.startsWith("--"))continue;let v=E.toUpperCase();if(v.startsWith("SELECT")||v.startsWith("PRAGMA"))o.query(S);else o.run(S)}return Promise.resolve([])}catch(p){return Promise.reject(p)}};let g=0;return u.begin=async(h,d)=>{let p=typeof h==="function"?h:d;if(typeof p!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let y=g>0,w=`qb_sp_${g}`;if(y)o.run(`SAVEPOINT ${w}`);else o.run("BEGIN");g++;try{let S=await p(u);if(g--,y)o.run(`RELEASE SAVEPOINT ${w}`);else o.run("COMMIT");return S}catch(S){g--;try{if(y)o.run(`ROLLBACK TO SAVEPOINT ${w}`),o.run(`RELEASE SAVEPOINT ${w}`);else o.run("ROLLBACK")}catch{}throw S}},u.savepoint=u.begin,u.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},u._wrapper=o,u}function ma(i){let o=i.replace(/^(?:sqlite|sqlite3|file):/i,"");if(o===i)return i;return(o.startsWith("///")?o.slice(2):o.startsWith("//")?o.slice(2):o)||":memory:"}function Ke(i=e.database){let o=Ge.env.DB_DATABASE||i?.database||"";return String(o).replace(/^['"]|['"]$/g,"")}function pa(i,o){if((i==="postgres"||i==="mysql"||i==="singlestore"||i==="vitess")&&Ge.env.DB_CONNECTION===i){let y=Ge.env,w=(y.DB_DATABASE||o.database||"").replace(/^['"]|['"]$/g,""),S=y.DB_USERNAME||o.username,E=y.DB_PASSWORD??o.password??"",v=y.DB_HOST||o.host||"localhost",x=y.DB_PORT||o.port,C=i==="postgres"?"postgres":"mysql",A=y.DB_SSL==="true"||y.DB_SSL==="1"||o.ssl?"?ssl=true":"";return`${C}://${S}:${E}@${v}${x?`:${x}`:""}/${w}${A}`}if(o.url)return i==="sqlite"?ma(o.url):o.url;let{database:c,username:f,password:u,host:g="localhost",port:h,ssl:d}=o,p=d||Ge.env.DB_SSL==="true"||Ge.env.DB_SSL==="1"?"?ssl=true":"";switch(i){case"postgres":return`postgres://${f}:${u}@${g}${h?`:${h}`:""}/${c}${p}`;case"mysql":case"singlestore":case"vitess":return`mysql://${f}:${u}@${g}${h?`:${h}`:""}/${c}${p}`;case"sqlite":if(c===":memory:")return":memory:";return c||":memory:";default:throw Error(`Unsupported dialect: ${i}`)}}function js(i){if(!i)return{};let o={},c=(f)=>Math.max(0,Math.round(f/1000));if(typeof i.max==="number"&&Number.isFinite(i.max))o.max=i.max;if(typeof i.idleTimeoutMs==="number"&&Number.isFinite(i.idleTimeoutMs))o.idleTimeout=c(i.idleTimeoutMs);if(typeof i.acquireTimeoutMs==="number"&&Number.isFinite(i.acquireTimeoutMs))o.connectionTimeout=c(i.acquireTimeoutMs);if(typeof i.maxLifetimeMs==="number"&&Number.isFinite(i.maxLifetimeMs))o.maxLifetime=c(i.maxLifetimeMs);if(typeof i.preparedStatements==="boolean")o.prepare=i.preparedStatements;return o}function _(i=e.database,o=e.dialect){if(o!=="sqlite"||!i)return null;let c=it(i.url)?i.url:it(i.database)?i.database:null;if(!c)return null;return{url:c,authToken:i.authToken||void 0}}function ya(){let i=e.dialect,o=_(e.database,i);if(o)return Wt(o);let c=pa(i,e.database);try{if(i==="sqlite")return Ms(c);let f=js(e.database.pool);return Object.keys(f).length>0?new Ds(c,f):new Ds(c)}catch(f){if(console.error(`[query-builder] Failed to create database connection for dialect '${i}': ${f.message}`),i==="sqlite")return Ms(":memory:");throw f}}var Pe=null,Kr=null;function wa(){let i=e.database;return JSON.stringify({dialect:e.dialect,database:i.database,username:i.username,password:i.password,host:i.host,port:i.port,url:i.url,authToken:i.authToken,pool:js(i.pool)})}function b(i=!1){let o=wa();if(i||Pe!==null&&Kr!==o||!Pe)Ks(),Pe=ya(),Kr=o;return Pe}function Ks(){let i=Pe;return i?.flushDeferredInserts?.(),Pe=null,Kr=null,i}async function ba(i){if(!i||typeof i.close!=="function")return;await i.close()}function hn(){ba(Ks()).catch((o)=>{console.error(`[query-builder] Failed to close database connection: ${o.message}`)})}async function st(i){try{return await i(b())}catch(o){if(o?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||o?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let c=b(!0);return await i(c)}throw o}}function Sa(){return new Proxy(function(){},{get(i,o){let c=b(),f=c[o];if(typeof f==="function")return f.bind(c);return f},apply(i,o,c){return b()(...c)}})}var r=Sa();function Fe(i){let o=String(i).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(o.endsWith("y")&&!/[aeou]y$/.test(o))return`${o.slice(0,-1)}ies`;if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return`${o}es`;return`${o}s`}function T(i){return typeof i?.table==="string"&&i.table.length>0?i.table:Fe(String(i?.name??""))}function gn(i){return i.endsWith("s")?i.slice(0,-1):i}function pn(i){if(i.endsWith("ies")&&i.length>3){let o=i.slice(0,-3),c=o[o.length-1];if(c&&!"aeiou".includes(c))return`${o}y`}if(i.endsWith("es")&&i.length>2){let o=i.slice(0,-2);if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return o}if(i.endsWith("s")&&!i.endsWith("ss")&&!i.endsWith("us")&&!i.endsWith("is"))return i.slice(0,-1);return i}function m(i){if(i==="none")return(o)=>o;if(i==="inflect")return pn;return gn}var Ht="1 = 0";function D(i){if(i.length===0)return"";let o=[];for(let c of i)if(c.conn==="OR"&&o.length>0)o[o.length-1].push(c);else o.push([c]);return o.map((c,f)=>{let u=c.map((h)=>h.sql).join(" OR "),g=c.length>1&&o.length>1?`(${u})`:u;return f===0?g:`${c[0].conn} ${g}`}).join(" ")}function l(i,o,c,f){if(o.length===0)return c?"1 = 1":"1 = 0";return`${i} ${c?"NOT IN":"IN"} (${f})`}function at(i,o){if(o!=="postgres")return i;return je(i,(c)=>`$${c}`).text}function X(i){return je(i,()=>{return}).count}function je(i,o){let c="",f=0,u=0,g=0;while(g<i.length){let h=i[g],d=-1;if(h==="'"||h==='"'||h==="`")d=va(i,g,h);else if(h==="-"&&i[g+1]==="-"){let p=i.indexOf(`
|
|
65
65
|
`,g+2);d=p===-1?i.length:p}else if(h==="/"&&i[g+1]==="*"){let p=1;d=g+2;while(d<i.length&&p>0)if(i[d]==="/"&&i[d+1]==="*")p++,d+=2;else if(i[d]==="*"&&i[d+1]==="/")p--,d+=2;else d++}else if(h==="$"){let p=i.slice(g).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(p){let y=i.indexOf(p,g+p.length);d=y===-1?i.length:y+p.length}}if(d!==-1){g=d;continue}if(h==="?"){f++;let p=o(f);if(p!==void 0)c+=i.slice(u,g)+p,u=g+1}g++}return{text:u===0?i:c+i.slice(u),count:f}}function va(i,o,c){let f=o+1;while(f<i.length){if(i[f]===c){if(i[f+1]===c){f+=2;continue}return f+1}f++}return i.length}function qe(i,o,c=Number.POSITIVE_INFINITY){let f=[],u=0,g=(h)=>h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||h===95;for(let h=0;h<i.length;h++){let d=i.charCodeAt(h);if(d===45&&i.charCodeAt(h+1)===45){let y=i.indexOf(`
|
|
66
66
|
`,h+2);if(y===-1)return f;h=y;continue}if(d===47&&i.charCodeAt(h+1)===42){let y=1,w=h+2;while(w<i.length&&y>0)if(i[w]==="/"&&i[w+1]==="*")y++,w+=2;else if(i[w]==="*"&&i[w+1]==="/")y--,w+=2;else w++;h=w-1;continue}if(d===39||d===34||d===96){let y=h+1;while(y<i.length){if(i.charCodeAt(y)===d){if(i.charCodeAt(y+1)===d){y+=2;continue}break}y++}h=y;continue}if(d===36){let y=/^\$(?:[A-Z_][A-Z0-9_]*)?\$/i.exec(i.slice(h));if(y){let w=i.indexOf(y[0],h+y[0].length);h=w===-1?i.length:w+y[0].length-1;continue}}if(d===40){u++;continue}if(d===41){u=Math.max(0,u-1);continue}if(u!==0)continue;if(h===0)continue;let p=d&-33;if(p<65||p>90)continue;if(g(i.charCodeAt(h-1)))continue;for(let{key:y,pattern:w}of o){w.lastIndex=h;let S=w.exec(i);if(!S)continue;if(f.push({key:y,start:h,length:S[0].length}),f.length>=c)return f;h+=S[0].length-1;break}}return f}
|
|
67
67
|
export{n,nt,e,P,rt,t,s,B,_e,dn,it,fn,a,Ie,jt,qt,mn,Le,Wt,Wn,Ut,Vt,k,Ke,_,b,hn,st,r,Fe,T,gn,pn,m,Ht,D,l,at,X,je,qe};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rn,sn,an,on,ln,Ft,cn,un}from"./chunk-
|
|
2
|
+
import{rn,sn,an,on,ln,Ft,cn,un}from"./chunk-dj2eazhq.js";import"./chunk-3hwsz4q7.js";import"./chunk-93ny6tvm.js";export{ln as clearModelRegistry,cn as defineModel,sn as getAllModels,rn as getModel,an as getModelRegistry,on as hasModel,un as registerBrowserModels,Ft as registerModel};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ht,w,R,Qe,A}from"./chunk-284e3ka8.js";import"./chunk-ygwkzhkh.js";import"./chunk-9wck98bv.js";import"./chunk-dj2eazhq.js";import"./chunk-3hwsz4q7.js";import"./chunk-93ny6tvm.js";export{R as executeMigration,Qe as executeMigrationWithReport,w as generateMigration,A as resetDatabase,ht as saveMigrationSnapshot};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{We}from"./chunk-93ny6tvm.js";import{n,e,k,_,b,Fe,m,D,l,at,X}from"./chunk-bpwg9p8b.js";function N(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function De(t){if(typeof t!=="string")return;switch(t.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function Pe(t){switch(t){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}import{Database as Te}from"bun:sqlite";function te(t){if(typeof t==="number")return{length:t};return t}function me(t){if(typeof t==="number")return{max:t};return t}function Le(t){return typeof t==="function"}function Ue(t){return t.replace(/[A-Z]/g,(r)=>r.toLowerCase())}function ke(t,r){if(!r||typeof r.fractionDigits!=="number")return t;return Number(t.toFixed(r.fractionDigits))}function z(t,r={}){if(!t)return r;return new Proxy(t,{get(o,s){if(s in r)return r[s];let i=o[s];if(i!==void 0)return i;let a=o[Ue(s)];if(Le(a))return a.bind(o);return}})}function Pt(t){let r=(f)=>{let g=Array.isArray(f)?f:[],R=Math.floor(Math.random()*g.length);return g[R]},o=()=>t.string,s=()=>t.number,i=()=>t.random,a=z(t.string,{alpha:(f)=>o()?.alpha?.(te(f)),alphanumeric:(f)=>o()?.alphanumeric?.(te(f)),numeric:(f)=>o()?.numeric?.(te(f)),sample:(f)=>o()?.sample?.(te(f)),hexadecimal:(f)=>o()?.hexadecimal?.(te(f))}),d=z(t.number,{int:(f)=>s()?.int?.(me(f)),float:(f)=>{let g=me(f);return ke(Number(s()?.float?.(g)??0),g)}}),u=z(t.helpers,{arrayElement:r,arrayElements:(f,g)=>{let R=[...Array.isArray(f)?f:[]],M=typeof g==="number"?g:Math.max(1,Math.floor(Math.random()*R.length));for(let x=R.length-1;x>0;x-=1){let A=Math.floor(Math.random()*(x+1));[R[x],R[A]]=[R[A],R[x]]}return R.slice(0,Math.min(M,R.length))},shuffle:(f)=>{let g=[...Array.isArray(f)?f:[]];for(let R=g.length-1;R>0;R-=1){let M=Math.floor(Math.random()*(R+1));[g[R],g[M]]=[g[M],g[R]]}return g},maybe:(f,g)=>{let R=typeof g?.probability==="number"?g.probability:0.5;return Math.random()<R?f():void 0},slugify:(f)=>String(f??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),T={string:a,number:d,helpers:u,datatype:{boolean:(f)=>{let g=typeof f==="number"?f:f?.probability;if(typeof g==="number")return Math.random()<g;return Boolean(i()?.boolean?.())},number:(f)=>Number(s()?.int?.(me(f))??0),float:(f)=>ke(Number(s()?.float?.(f)??0),f),uuid:()=>crypto.randomUUID(),string:(f)=>String(o()?.alphanumeric?.({length:f??10})??""),hexadecimal:(f)=>String(o()?.hexadecimal?.(te(f))??""),array:(f)=>Array.from({length:f??3},()=>o()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:o()?.alphanumeric?.({length:8})})},location:z(t.address),address:z(t.address),vehicle:z(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:z(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(f,g){if(g in T)return T[g];let R=f[g];if(R&&typeof R==="object")return z(R);return R}})}function Be(t){if(typeof t==="string")return{model:t};if(t&&typeof t==="object"&&typeof t.model==="string"){let r=t;return{model:r.model,foreignKey:r.foreignKey,onDelete:r.onDelete}}return null}function O(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(Be).filter((o)=>o!==null)}function Y(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var $e=/^[A-Z_][A-Z0-9_]*$/i;function H(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);if(t.length>64)throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' exceeds 64 chars`);if(!$e.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Se(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);let o=t.split(".");if(o.length>2||o.some((s)=>s.length===0||s.length>64||!$e.test(s)))throw TypeError(`[bun-query-builder] ${r}: invalid ORDER BY column '${t}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Me(t,r){if(r.length!==1)return r;let o=r[0];if(Array.isArray(o))return[...o];if(o===void 0&&X(t)===0)return[];return r}var ae=null,we=new Map;function qe(t,r){we.set(t,r),re.clear()}function Bt(){we.clear(),re.clear()}function j(t){if(!ae)try{ae=import.meta.require("./chunk-82w0fmx3.js").getModel}catch{ae=()=>{return}}return ae(t)??we.get(t)}var le=new Map,He=500;function Ke(t){let r=le.get(t);if(r!==void 0)return r;let o=at(t,"postgres");if(le.size>=He)le.clear();return le.set(t,o),o}function _t(t){if(t==null)return 0;if(typeof t.affectedRows==="number")return t.affectedRows;if(typeof t.count==="number")return t.count;if(Array.isArray(t))return t.length;return 0}function It(t){if(t==null||typeof t!=="object")return null;if("insertId"in t&&t.insertId!=null)return t.insertId;if("lastInsertRowid"in t&&t.lastInsertRowid!=null)return t.lastInsertRowid;return null}class pe{sqliteDb;dialect="sqlite";constructor(t){this.sqliteDb=t}all(t,r){return Promise.resolve(this.sqliteDb.query(t).all(...r))}get(t,r){return Promise.resolve(this.sqliteDb.query(t).get(...r)??void 0)}run(t,r){let o=this.sqliteDb.run(t,r);return Promise.resolve({changes:o.changes,lastInsertId:o.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class be{dialect;constructor(t){this.dialect=t}conn(){return b()}text(t){return this.dialect==="postgres"?Ke(t):t}async all(t,r){let o=await this.conn().unsafe(this.text(t),r);return Array.isArray(o)?o:[]}async get(t,r){let o=await this.conn().unsafe(this.text(t),r);if(Array.isArray(o))return o[0]??void 0;return o??void 0}async run(t,r){let o=await this.conn().unsafe(this.text(t),r);return{changes:_t(o),lastInsertId:It(o)}}async insert(t,r,o){if(this.dialect==="postgres"){let a=await this.conn().unsafe(`${Ke(t)} RETURNING ${o}`,r),d=Array.isArray(a)?a[0]:a;return{changes:1,lastInsertId:d?d[o]??null:null}}let s=await this.conn().unsafe(t,r),i=It(s);if(i==null&&this.dialect!=="sqlite"){let a=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);i=(Array.isArray(a)?a[0]:a)?.id??null}return{changes:_t(s)||1,lastInsertId:i}}}var Q=null,ce=!1,U=null,ne=null,ue=null,de=null;function Ln(t){if(t.database instanceof Te)Q=t.database,ce=!1;else Q=new Te(t.database||":memory:",{create:!0}),ce=!0,k(Q);U=null,ne=null}function Kn(){let t=ce,r=Q;if(Q=null,ce=!1,U=null,ne=null,ue=null,de=null,t&&r)try{r.close()}catch{}}var Re=!1;function S(){if(Q){if(!U||ne!==Q)U=new pe(Q),ne=Q,ue="sqlite",de=null;return U}let t=e.dialect,r=e.database?.database??null,o=`${r??""}|${_()?.url??""}`;if(U&&ne===null&&ue===t&&de===o)return U;if(ne=null,ue=t,de=o,t==="sqlite"&&_())U=new be(t);else if(t==="sqlite"){if(!r&&!Re)Re=!0,console.warn("[bun-query-builder] The model layer has no database configured, so it is using an in-memory SQLite database and nothing it writes will persist. Configure one with setConfig({ dialect, database }) or configureOrm({ database }), or name ':memory:' explicitly to silence this.");let s=new Te(r||":memory:",{create:!0});k(s),U=new pe(s)}else U=new be(t);return U}function Fn(){let t=S();if(t.sqliteDb)return t.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${t.dialect}'. Use the async model API instead.`)}var Qe=4096,_e=1000;function Ve(t,r,o){let s=t.attributes,i=new Map(Object.entries(s).map(([a,d])=>[C(a),d]));for(let a of r){let d=String(i.get(a)?.type??"").toLowerCase();if(d==="json"||d==="jsonb")return!1}for(let a of o)for(let d of r){let u=a[d];if(u===null||u===void 0||u instanceof Date)continue;let c=typeof u;if(c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="bigint")return!1}return!0}function ze(t,r){return typeof r==="bigint"?r.toString():r}function xe(t){return 2**Math.floor(Math.log2(t))}var L="deleted_at",Ae=500,ye="__btm_rel__";function ee(t){let r=t.traits;return Boolean(r?.useSoftDeletes||r?.softDeletable)}function Z(t){let r=t.traits;return Boolean(r?.useTimestamps||r?.timestampable)}var Ee=new WeakMap;function Ge(t){let r=Ee.get(t);if(r)return r;let o=new Set,s=t.belongsToMany;if(s){if(Array.isArray(s)){for(let i of s)if(typeof i==="string")o.add(i.toLowerCase());else if(i&&typeof i==="object"&&i.model)o.add(i.model.toLowerCase())}else if(typeof s==="object")for(let i of Object.keys(s))o.add(i)}return Ee.set(t,o),o}function Oe(t){let r={};for(let[o,s]of Object.entries(t))r[C(o)]=s;return r}function Xe(t){for(let r in t)if(C(r)!==r)return Oe(t);return t}function Ye(t,r){if(t[r])return t[r];let o=C(r);if(t[o])return t[o];for(let s of Object.keys(t))if(C(s)===o)return t[s];return}class I{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_exists;_relations={};constructor(t,r,o){this._definition=t,this._exists=o,this._attributes=Xe({...r}),this._original=null;let s=Ge(t);if(s.size===0)return;let i=this;return new Proxy(this,{get(a,d,u){if(typeof d==="string"&&s.has(d)&&!(d in a))return()=>{let c=Ie(t,d);if(!c||c.type!=="belongsToMany")throw Error(`[orm] relation '${d}' did not resolve to a belongsToMany on '${t.name}'`);let T=j(c.relatedModelName),f=T?.getDefinition?.()||T?.definition;if(!f)throw Error(`[orm] related model '${c.relatedModelName}' is not registered`);return new Lt(i,t,c,f)};return Reflect.get(a,d,u)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(t){let r=this._definition.get?.[t];if(r)try{let o=r(this._attributes);if(o!==void 0)return o}catch{}return this._attributes[C(t)]}getAttribute(t){return this._attributes[C(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[C(t)]=r}only(t){let r={};for(let o of t)r[o]=this._attributes[C(o)];return r}except(t){let r=new Set(t.map((s)=>C(s))),o={};for(let s of Object.keys(this._attributes))if(!r.has(s))o[s]=this._attributes[s];return o}getRelation(t){return this._relations[t]}setRelation(t,r){this._relations[t]=r}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let t=this._definition.primaryKey||"id";return this._attributes[t]}isDirty(t){if(this._original===null)return!1;if(t){let r=C(t);return this._attributes[r]!==this._original[r]}return Object.keys(this._attributes).some((r)=>this._attributes[r]!==this._original[r])}isClean(t){return!this.isDirty(t)}getOriginal(t){return this.getOriginalAttributes()[C(t)]}getChanges(){if(this._original===null)return{};let t={};for(let r of Object.keys(this._attributes))if(this._attributes[r]!==this._original[r])t[r]=this._attributes[r];return t}fill(t){let r=this._definition.attributes;for(let[o,s]of Object.entries(t)){let i=Ye(r,o),a=!i&&C(o).endsWith("_id");if(i?.fillable&&!i?.guarded||a){if(this._original===null)this._original={...this._attributes};this._attributes[C(o)]=s}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Oe(t);Object.assign(this._attributes,r);for(let o of Object.keys(r))this._forced.add(o);return this}async _prepareInsert(){this._applySetters();let t=this._definition.primaryKey||"id",r=this._definition.hooks,o=this._definition.attributes,s={};for(let[u,c]of Object.entries(o)){if(c.guarded&&!this._forced.has(C(u)))continue;let T=C(u);if(this._attributes[T]!==void 0)s[T]=this._attributes[T]}for(let u of Object.keys(this._attributes))if(u.endsWith("_id")&&u!==t&&!(u in s))s[u]=this._attributes[u];let i=this._attributes[t],d=o[t]?.guarded&&!this._forced.has(t);if(i!=null&&!(t in s)&&!d)s[t]=i;if(Z(this._definition)){let u=Y(),c=this._attributes.created_at;s.created_at=c===void 0||c===null?u:c,s.updated_at=u}if(this._definition.traits?.useUuid&&!s.uuid)s.uuid=crypto.randomUUID();return await r?.beforeCreate?.(s),s}async _markInserted(t,r){let o=this._definition.primaryKey||"id";for(let[s,i]of Object.entries(t))this._attributes[s]=i;if(!(o in t)&&r!=null)this._attributes[o]=r;this._exists=!0,await this._definition.hooks?.afterCreate?.(this),this._original={...this._attributes},this._hasSaved=!0}_applySetters(){let t=this._definition.set||{};for(let[r,o]of Object.entries(t))if(this.isDirty(r))this._attributes[C(r)]=o(this._attributes)}async save(){let t=S(),r=this._definition.primaryKey||"id",o=this._definition.hooks;if(this._exists){this._applySetters(),await o?.beforeUpdate?.(this,this.getChanges());let s=this.getChanges(),i=Object.keys(s);if(i.length>0){if(this._attributes[r]==null)throw Error(`Cannot save a model without a primary key: '${r}' was not selected`);let a=i.map((u)=>`${u} = ?`).join(", "),d=[...Object.values(s),this._attributes[r]];if(Z(this._definition)){let u=Y();await t.run(`UPDATE ${this._definition.table} SET ${a}, updated_at = ? WHERE ${r} = ?`,[...Object.values(s),u,this._attributes[r]])}else await t.run(`UPDATE ${this._definition.table} SET ${a} WHERE ${r} = ?`,d)}await o?.afterUpdate?.(this)}else{let s=await this._prepareInsert(),i=Object.keys(s),a=i.map(()=>"?").join(", "),d=await t.insert(`INSERT INTO ${this._definition.table} (${i.join(", ")}) VALUES (${a})`,Object.values(s),r);return await this._markInserted(s,r in s?void 0:d.lastInsertId),this}return this._original={...this._attributes},this._hasSaved=!0,this}async update(t){return this.fill(t),this.save()}async fresh(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(o==null)return null;let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return new I(this._definition,s,!0)}async delete(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r],s=this._definition.hooks;if(o==null)throw Error("Cannot delete a model without a primary key");if(await s?.beforeDelete?.(this),ee(this._definition)){let i=Y();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[i,o]),this._attributes[L]=i}else await t.run(`DELETE FROM ${this._definition.table} WHERE ${r} = ?`,[o]);return await s?.afterDelete?.(this),!0}async forceDelete(){let t=this._definition.primaryKey||"id",r=this._attributes[t],o=this._definition.hooks;if(r==null)throw Error("Cannot delete a model without a primary key");return await o?.beforeDelete?.(this),await S().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await o?.afterDelete?.(this),!0}async restore(){if(!ee(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let t=this._definition.primaryKey||"id",r=this._attributes[t];if(!r)throw Error("Cannot restore a model without a primary key");return await S().run(`UPDATE ${this._definition.table} SET ${L} = ? WHERE ${t} = ?`,[null,r]),this._attributes[L]=null,this._original=null,this}trashed(){return this._attributes[L]!=null}async refresh(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(!o)throw Error("Cannot refresh a model without a primary key");let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return this._attributes=s,this._original=null,this}replicate(){let t=this._definition.primaryKey||"id",r={...this._attributes};return delete r[t],delete r.uuid,delete r.created_at,delete r.updated_at,new I(this._definition,r,!1)}toArray(){let t={...this._attributes};for(let[r,o]of Object.entries(this._relations))if(Array.isArray(o))t[r]=o.map((s)=>s.toArray());else if(o)t[r]=o.toArray();else t[r]=null;return t}toJSON(){let t=new Set;for(let[o,s]of Object.entries(this._definition.attributes))if(s.hidden)t.add(o);let r={};for(let[o,s]of Object.entries(this._attributes))if(!t.has(o))r[o]=s;for(let[o,s]of Object.entries(this._relations))if(Array.isArray(s))r[o]=s.map((i)=>i.toJSON());else if(s)r[o]=s.toJSON();else r[o]=null;return r}}var ve=new Map,Ne=new Map,re=new Map,Je=1000;function W(t){return C(t)}function C(t){let r=ve.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ve.set(t,r),r}function G(t){let r=Ne.get(t);if(r!==void 0)return r;return r=Fe(t),Ne.set(t,r),r}var fe=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],Ze=[...fe,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Ce(t,r){let o=t[r];if(!o)return[];if(Array.isArray(o))return o.map((s)=>typeof s==="string"?s:String(s?.model??"")).filter(Boolean);if(typeof o==="object")return Object.keys(o);if(typeof o==="string")return[o];return[]}function et(t,r){let o=t.name??t.table??"model",i=Ze.filter((d)=>Ce(t,d).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((d)=>!fe.includes(d));if(i.length>0)return`[orm] '${o}' declares '${r}' as ${i.join("/")}, which eager loading does not support yet. Supported kinds: ${fe.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let a=fe.flatMap((d)=>Ce(t,d));return a.length>0?`[orm] '${o}' has no relation '${r}'. Available: ${a.join(", ")}.`:`[orm] '${o}' has no relation '${r}' \u2014 it declares no relations at all.`}function Ie(t,r){let{name:o,table:s}=t,i=t.primaryKey||"id";function a(w){if(!w)return null;if(Array.isArray(w)){for(let h of w){let K=typeof h==="string"?h:h?.model||"";if(K&&K.toLowerCase()===r.toLowerCase())return K}return null}if(typeof w==="object"){for(let[h,K]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return typeof K==="string"?K:K?.model||K?.target||h}return null}function d(){let w=t.belongsTo;if(!w)return null;let h=r.toLowerCase(),K=(p)=>{if(typeof p==="string")return{model:p};if(p&&typeof p==="object"&&typeof p.model==="string")return{model:p.model,foreignKey:p.foreignKey};return null};if(Array.isArray(w)){for(let p of w){let y=K(p);if(y&&y.model.toLowerCase()===h)return y}return null}if(typeof w==="object"){for(let[p,y]of Object.entries(w))if(p===r||p.toLowerCase()===h)return K(y)}return null}function u(){let w=t.belongsToMany;if(!w)return null;if(Array.isArray(w)){for(let h of w)if(typeof h==="string"){if(h.toLowerCase()===r.toLowerCase())return{entry:h}}else if(h&&typeof h==="object"&&h.model){if(h.model.toLowerCase()===r.toLowerCase())return{entry:h}}return null}if(typeof w==="object"){for(let[h,K]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return{entry:K}}return null}function c(w){let h=t[w];if(!h)return null;let K=r.toLowerCase();if(Array.isArray(h)){for(let p of h){let y=typeof p==="string"?p:String(p?.model??"");if(!y||y.toLowerCase()!==K)continue;let v=typeof p==="object"?p?.morphName:void 0;return{model:y,morphName:String(v??`${C(o)}able`)}}return null}if(typeof h==="object")for(let[p,y]of Object.entries(h)){let v=typeof y==="string"?y:String(y?.model??"");if(p.toLowerCase()!==K&&v.toLowerCase()!==K)continue;let P=typeof y==="object"?y?.morphName:void 0;return{model:v,morphName:String(P??p)}}return null}for(let w of["morphMany","morphOne"]){let h=c(w);if(!h)continue;let p=j(h.model)?.getTable?.()||G(h.model);return{type:w,relatedModelName:h.model,relatedTable:p,foreignKey:`${h.morphName}_id`,localKey:i,morphTypeColumn:`${h.morphName}_type`,morphTypeValue:s}}let T=a(t.hasMany);if(T){let h=j(T)?.getTable?.()||G(T),K=C(o)+"_id";return{type:"hasMany",relatedModelName:T,relatedTable:h,foreignKey:K,localKey:i}}let f=a(t.hasOne);if(f){let h=j(f)?.getTable?.()||G(f),K=C(o)+"_id";return{type:"hasOne",relatedModelName:f,relatedTable:h,foreignKey:K,localKey:i}}let g=d();if(g){let w=g.model,h=j(w),K=h?.getTable?.()||G(w),p=h?.getDefinition?.()?.primaryKey||"id",y=g.foreignKey||`${C(w)}_id`;return{type:"belongsTo",relatedModelName:w,relatedTable:K,foreignKey:y,localKey:p}}let R=u();if(R){let w=typeof R.entry==="object",h=w?R.entry.model:R.entry,p=j(h)?.getTable?.()||G(h),y=w?R.entry:null,v,P;if(y?.table)v=y.table;else if(y?.through){P=y.through;let B=j(y.through);if(!B)throw Error(`[orm] belongsToMany relation '${r}' on '${o}' references unknown through model '${y.through}'. Make sure '${y.through}' is registered.`);v=B.getTable?.()||B.getDefinition?.()?.table||G(y.through)}else{let B=ie(s),q=ie(p);v=[B,q].sort().join("_")}let F=y?.foreignKey||`${ie(s)}_id`,J=y?.relatedKey||`${ie(p)}_id`,V=[];if(y?.pivot?.columns)for(let B of Object.keys(y.pivot.columns))V.push(B);if(P){let B=j(P),q=B?.getDefinition?.()||B?.definition,he=q?.attributes??{},je=q?.primaryKey??"id";for(let se of Object.keys(he)){if(se===F||se===J||se===je)continue;if(!V.includes(se))V.push(se)}}return{type:"belongsToMany",relatedModelName:h,relatedTable:p,foreignKey:F,localKey:i,pivotTable:v,pivotFkParent:F,pivotFkRelated:J,pivotColumns:V,pivotModelName:P,pivotTimestamps:Boolean(y?.pivot?.timestamps)}}let M=(w,h)=>{if(!w||typeof w!=="object"||Array.isArray(w))return null;let K=w[r]??w[Object.keys(w).find((q)=>q.toLowerCase()===r.toLowerCase())??""];if(!K||typeof K!=="object")return null;let{through:p,target:y}=K;if(!p||!y)return null;let v=j(p),P=v?.getDefinition?.()||v?.definition,F=v?.getTable?.()||P?.table||G(p),J=P?.primaryKey||"id",B=j(y)?.getTable?.()||G(y);return{type:h,relatedModelName:y,relatedTable:B,foreignKey:`${C(o)}_id`,localKey:i,throughTable:F,throughForeignKey:`${C(o)}_id`,throughLocalKey:J,targetForeignKey:`${ie(F)}_id`}},x=M(t.hasManyThrough,"hasManyThrough");if(x)return x;let A=M(t.hasOneThrough,"hasOneThrough");if(A)return A;return null}function ge(t,r){let o=new Set;for(let s of t){let i=s.get(r);if(i!=null)o.add(i)}return[...o]}function ie(t){return m(e.relations?.singularizeStrategy)(t)}class Lt{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(t,r,o,s){this._parent=t,this._parentDef=r,this._resolved=o,this._relatedDef=s}get parentId(){let t=this._parentDef.primaryKey||"id";return this._parent.get(t)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(t,r,o){if(o===void 0)this._wheres.push({sql:`${this.relatedTable}.${t} = ?`,params:[r]});else this._wheres.push({sql:`${this.relatedTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivot(t,r,o){if(o===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${t} = ?`,params:[r]});else this._pivotWheres.push({sql:`${this.pivotTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IN (${o})`,params:[...r]}),this}wherePivotNotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} NOT IN (${o})`,params:[...r]}),this}wherePivotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NULL`,params:[]}),this}wherePivotNotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NOT NULL`,params:[]}),this}orderBy(t,r="asc"){if(Se(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push(`${t} ${r.toUpperCase()}`),this}limit(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${t}`);return this._limit=t,this}offset(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${t}`);return this._offset=t,this}relatedSelectColumns(){let t=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),r=this._relatedDef.traits;if(r?.useTimestamps||r?.timestampable)t.add("created_at"),t.add("updated_at");if(r?.useSoftDeletes||r?.softDeletable)t.add("deleted_at");if(r?.useUuid)t.add("uuid");return[...t]}buildSelect(){let t=[],o=`SELECT ${this.relatedSelectColumns().map((s)=>`${this.relatedTable}.${s} AS ${ye}${s}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;o+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,o+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,t.push(this.parentId);for(let s of this._pivotWheres)o+=` AND ${s.sql}`,t.push(...s.params);for(let s of this._wheres)o+=` AND ${s.sql}`,t.push(...s.params);if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}hydrateRows(t){let r=this.fkParent,o=this.fkRelated;return t.map((s)=>{let i={},a={};for(let[u,c]of Object.entries(s))if(u.startsWith(ye))i[u.slice(ye.length)]=c;else if(u!==r&&u!==o)a[u]=c;let d=new I(this._relatedDef,i,!0);return d.pivot=a,d})}async get(){let t=S(),{sql:r,params:o}=this.buildSelect(),s=await t.all(r,o);return this.hydrateRows(s)}async first(){return this._limit=1,(await this.get())[0]}async count(){let t=S(),r=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,o=[this.parentId];for(let i of this._pivotWheres)r+=` AND ${i.sql}`,o.push(...i.params);let s=await t.get(r,o);return Number(s?.count??0)}async exists(){return await this.count()>0}now(){return Y()}async attach(t,r={}){let o=S(),s=Array.isArray(t)?t:[t];if(s.length===0)return 0;let i=this._resolved.pivotTimestamps?this.now():null,a=0;for(let d of s){let u={[this.fkParent]:this.parentId,[this.fkRelated]:d,...r};if(i){if(u.created_at===void 0)u.created_at=i;if(u.updated_at===void 0)u.updated_at=i}let c=Object.keys(u),T=c.map(()=>"?").join(", "),f=`INSERT INTO ${this.pivotTable} (${c.join(", ")}) VALUES (${T})`,g=c.map((R)=>u[R]);await o.run(f,g),a++}return a}async detach(t){let r=S(),o=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,s=[this.parentId];if(t!==void 0&&t!==null){let i=Array.isArray(t)?t:[t];if(i.length===0)return 0;let a=i.map(()=>"?").join(", ");o+=` AND ${this.fkRelated} IN (${a})`,s.push(...i)}return(await r.run(o,s)).changes}async updateExistingPivot(t,r){let o=S(),s={...r};if(this._resolved.pivotTimestamps&&s.updated_at===void 0)s.updated_at=this.now();let i=Object.keys(s);if(i.length===0)return 0;let a=i.map((c)=>`${c} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${a} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,u=[...i.map((c)=>s[c]),this.parentId,t];return(await o.run(d,u)).changes}async sync(t){let r=S(),o=new Map;for(let T of t)if(T!=null&&typeof T==="object"&&"id"in T){let{id:f,...g}=T;o.set(f,g)}else o.set(T,{});let s=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),i=new Set(s.map((T)=>T[this.fkRelated])),a=[],d=[],u=[],c=[...i].filter((T)=>!o.has(T));if(c.length>0)await this.detach(c),d.push(...c);for(let[T,f]of o)if(!i.has(T))await this.attach(T,f),a.push(T);else if(Object.keys(f).length>0)await this.updateExistingPivot(T,f),u.push(T);return{attached:a,detached:d,updated:u}}async toggle(t){let r=S(),o=Array.isArray(t)?t:[t];if(o.length===0)return{attached:[],detached:[]};let s=o.map(()=>"?").join(", "),i=await r.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${s})`,[this.parentId,...o]),a=new Set(i.map((c)=>c[this.fkRelated])),d=o.filter((c)=>!a.has(c)),u=o.filter((c)=>a.has(c));if(d.length>0)await this.attach(d);if(u.length>0)await this.detach(u);return{attached:d,detached:u}}}class E{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(t){this._definition=t}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"and"});else this._wheres.push({column:t,operator:r,value:o,boolean:"and"});return this}orWhere(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"or"});else this._wheres.push({column:t,operator:r,value:o,boolean:"or"});return this}whereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"and"}),this}orWhereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"or"}),this}whereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"and"}),this}orWhereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"or"}),this}whereNull(t){return H(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return H(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return H(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return H(t,"orWhereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"or"}),this}whereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"and"}),this}orWhereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"or"}),this}whereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"and"}),this}orWhereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"or"}),this}whereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Me(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Me(t,r),boolean:"or"}),this}whereGroup(t){return this._addGroup("and",t)}orWhereGroup(t){return this._addGroup("or",t)}_addGroup(t,r){let o=new E(this._definition);if(r(o),o._wheres.length===0)return this;let s=[],i=o.buildWhereClauses(s);if(!i)return this;return this._wheres.push({raw:`(${i})`,rawParams:s,boolean:t}),this}whereBetween(t,r){return H(t,"whereBetween(column)"),this._wheres.push({column:t,operator:">=",value:r[0],boolean:"and"}),this._wheres.push({column:t,operator:"<=",value:r[1],boolean:"and"}),this}whereNotBetween(t,r){H(t,"whereNotBetween(column)");let o=W(t);return this._wheres.push({raw:`(${o} < ? OR ${o} > ?)`,rawParams:[r[0],r[1]],boolean:"and"}),this}when(t,r){if(t)return r(this);return this}orderBy(t,r="asc"){if(Se(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push({column:t,direction:r}),this}orderByDesc(t){return this.orderBy(t,"desc")}orderByAsc(t){return this.orderBy(t,"asc")}latest(t="created_at"){return this.orderBy(t,"desc")}oldest(t="created_at"){return this.orderBy(t,"asc")}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}select(...t){return this._select=t,this}with(...t){for(let r of t)if(!this._withRelations.includes(r))this._withRelations.push(r);return this}getWithRelations(){return this._withRelations}buildWhereClauses(t){let r=[];for(let o of this._wheres){let s;if(o.raw){if(s=o.raw,o.rawParams&&o.rawParams.length>0)t.push(...o.rawParams)}else if(o.value===null){let i=W(o.column);s=o.operator==="="?`${i} IS NULL`:`${i} IS NOT NULL`}else if(o.operator==="in"||o.operator==="not in"){let i=o.value;s=l(W(o.column),i,o.operator==="not in",i.map(()=>"?").join(", ")),t.push(...i)}else s=`${W(o.column)} ${o.operator} ?`,t.push(o.value);r.push({conn:o.boolean==="or"?"OR":"AND",sql:s})}return D(r)}softDeleteClause(){if(this._trashed==="include"||!ee(this._definition))return"";return this._trashed==="only"?`${L} IS NOT NULL`:`${L} IS NULL`}assertNoUnappliedClauses(t){let r=[];if(this._limit!==void 0)r.push("limit()");if(this._offset!==void 0)r.push("offset()");if(this._orderBy.length>0)r.push("orderBy()");if(r.length>0)throw TypeError(`[orm] ${t}() cannot apply ${r.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere(t){let r=this._wheres.length>0?this.buildWhereClauses(t):"",o=this.softDeleteClause();if(r&&o)return`(${r}) AND ${o}`;return r||o}buildQuery(){let t=[],o=`SELECT ${this._select.map((i)=>i==="*"?i:W(i)).join(", ")} FROM ${this._definition.table}`,s=this.composeWhere(t);if(s)o+=` WHERE ${s}`;if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.map((i)=>`${W(i.column)} ${i.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}toSql(){return this.buildQuery()}async eagerLoadRelations(t){if(t.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((r)=>this.eagerLoadRelation(r,t)))}async eagerLoadRelation(t,r){let o=S(),s=this._definition.primaryKey||"id",i=`${this._definition.name}:${t}`,a=re.get(i);if(a===void 0){if(a=Ie(this._definition,t),re.size>=Je)re.clear();re.set(i,a)}if(!a)throw Error(et(this._definition,t));let d=a.type==="hasOne"||a.type==="morphOne";if(a.type==="hasMany"||a.type==="hasOne"||a.type==="morphMany"||a.type==="morphOne"){let u=ge(r,s);if(u.length===0)return;let c=u.map(()=>"?").join(", "),T=a.morphTypeColumn?` AND ${a.morphTypeColumn} = ?`:"",f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.foreignKey} IN (${c})${T}`,a.morphTypeColumn?[...u,a.morphTypeValue]:u),g=j(a.relatedModelName),R=g?.getDefinition?.()||g?.definition||this._definition;if(!d){let M=new Map;for(let x of f){let A=x[a.foreignKey];if(!M.has(A))M.set(A,[]);M.get(A).push(x)}for(let x of r){let A=M.get(x.get(s))||[];x.setRelation(t,A.map((w)=>new I(R,w,!0)))}}else{let M=new Map;for(let x of f){let A=x[a.foreignKey];if(!M.has(A))M.set(A,x)}for(let x of r){let A=M.get(x.get(s));x.setRelation(t,A?new I(R,A,!0):null)}}}if(a.type==="belongsTo"){let u=new Set;for(let x of r){let A=x._attributes[a.foreignKey];if(A!=null)u.add(A)}let c=[...u];if(c.length===0)return;let T=c.map(()=>"?").join(", "),f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.localKey} IN (${T})`,c),g=j(a.relatedModelName),R=g?.getDefinition?.()||g?.definition||this._definition,M=new Map;for(let x of f)M.set(x[a.localKey],x);for(let x of r){let A=x._attributes[a.foreignKey],w=M.get(A);x.setRelation(t,w?new I(R,w,!0):null)}}if(a.type==="belongsToMany"){let u=ge(r,s);if(u.length===0)return;if(!a.pivotTable||!a.pivotFkParent||!a.pivotFkRelated)return;let c=u.map(()=>"?").join(", "),T=await o.all(`SELECT * FROM ${a.pivotTable} WHERE ${a.pivotFkParent} IN (${c})`,u);if(T.length===0){for(let p of r)p.setRelation(t,[]);return}let f=new Set;for(let p of T){let y=p[a.pivotFkRelated];if(y!=null)f.add(y)}let g=[...f],R=j(a.relatedModelName),M=R?.getDefinition?.()||R?.definition||this._definition,x=M?.primaryKey||"id",A=[];if(g.length>0){let p=g.map(()=>"?").join(", ");A=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${x} IN (${p})`,g)}let w=new Map;for(let p of A)w.set(p[x],p);let h=new Map;for(let p of T){let y=p[a.pivotFkParent];if(!h.has(y))h.set(y,[]);h.get(y).push(p)}let K=new Set([a.pivotFkParent,a.pivotFkRelated]);for(let p of r){let y=p.get(s),P=(h.get(y)||[]).map((F)=>{let J=w.get(F[a.pivotFkRelated]);if(!J)return null;let V=new I(M,J,!0),B={};for(let[q,he]of Object.entries(F))if(!K.has(q))B[q]=he;return V.pivot=B,V}).filter((F)=>F!==null);p.setRelation(t,P)}}if(a.type==="hasManyThrough"||a.type==="hasOneThrough"){let u=ge(r,s);if(u.length===0)return;let c=a.throughLocalKey||"id",T=u.map(()=>"?").join(", "),f=await o.all(`SELECT ${c}, ${a.throughForeignKey} FROM ${a.throughTable} WHERE ${a.throughForeignKey} IN (${T})`,u);if(f.length===0){for(let K of r)K.setRelation(t,a.type==="hasManyThrough"?[]:null);return}let g=new Map;for(let K of f)g.set(K[c],K[a.throughForeignKey]);let R=[...new Set(f.map((K)=>K[c]))],M=R.map(()=>"?").join(", "),x=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.targetForeignKey} IN (${M})`,R),A=j(a.relatedModelName),w=A?.getDefinition?.()||A?.definition||this._definition,h=new Map;for(let K of x){let p=g.get(K[a.targetForeignKey]);if(p==null)continue;if(!h.has(p))h.set(p,[]);h.get(p).push(new I(w,K,!0))}for(let K of r){let p=h.get(K.get(s))||[];K.setRelation(t,a.type==="hasManyThrough"?p:p[0]??null)}}}async get(){let t=S(),{sql:r,params:o}=this.buildQuery(),i=(await t.all(r,o)).map((a)=>new I(this._definition,a,!0));if(this._withRelations.length>0)await this.eagerLoadRelations(i);return i}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let t=await this.first();if(!t)throw Error(`No ${this._definition.name} found`);return t}async find(t){let r=this._definition.primaryKey||"id";return this.where(r,t).first()}async findOrFail(t){let r=await this.find(t);if(!r)throw Error(`${this._definition.name} with id ${t} not found`);return r}async last(){let t=this._definition.primaryKey||"id";return this._orderBy=[{column:t,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let t=S(),r=[],o=`SELECT COUNT(*) as count FROM ${this._definition.table}`,s=this.composeWhere(r);if(s)o+=` WHERE ${s}`;let i=await t.get(o,r);return Number(i?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let t=await this.get();if(t.length===0)throw Error(`No ${this._definition.name} found`);if(t.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return t[0]}async increment(t,r=1){H(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let o=S(),s=[r],i=W(t),a=`UPDATE ${this._definition.table} SET ${i} = ${i} + ?`;if(Z(this._definition))a+=", updated_at = ?",s.push(Y());let d=this.composeWhere(s);if(d)a+=` WHERE ${d}`;return(await o.run(a,s)).changes}decrement(t,r=1){return this.increment(t,-r)}async chunk(t,r){let o=0;while(!0){let s=new E(this._definition);s._wheres=[...this._wheres],s._orderBy=[...this._orderBy],s._select=[...this._select],s._withRelations=[...this._withRelations],s._trashed=this._trashed,s._limit=t,s._offset=o*t;let i=await s.get();if(i.length===0)break;if(await r(i)===!1)break;if(i.length<t)break;o++}}async paginate(t=1,r=15){if(typeof t==="object"&&t!==null){let a=t;r=a.perPage??15,t=a.page??1}let o=await this.count(),s=Math.ceil(o/r);this._limit=r,this._offset=(t-1)*r;let i=await this.get();return{data:i,total:o,page:t,perPage:r,lastPage:s,hasMorePages:t<s,isEmpty:i.length===0,from:i.length>0?(t-1)*r+1:null,to:i.length>0?(t-1)*r+i.length:null,meta:{perPage:r,page:t,total:o,lastPage:s}}}async pluck(t){H(t,"pluck(column)");let r=S(),o=[],s=W(t),i=`SELECT ${s} FROM ${this._definition.table}`,a=this.composeWhere(o);if(a)i+=` WHERE ${a}`;if(this._orderBy.length>0)i+=` ORDER BY ${this._orderBy.map((u)=>`${W(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)i+=` LIMIT ${this._limit}`;if(this._offset!==void 0)i+=` OFFSET ${this._offset}`;return(await r.all(i,o)).map((u)=>u[s])}async aggregate(t,r){H(r,`${t}(column)`);let o=S(),s=[],i=`SELECT ${t}(${W(r)}) as v FROM ${this._definition.table}`,a=this.composeWhere(s);if(a)i+=` WHERE ${a}`;let u=(await o.get(i,s))?.v;if(u==null)return null;if(typeof u==="string"){let c=Number(u);return u.trim()!==""&&!Number.isNaN(c)?c:u}return u}max(t){return this.aggregate("MAX",t)}min(t){return this.aggregate("MIN",t)}async avg(t){return Number(await this.aggregate("AVG",t)??0)||0}async sum(t){return Number(await this.aggregate("SUM",t)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let t=ee(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=S(),o=this._definition.table,s=this._definition.hooks,i=[],a=this.composeWhere(i);if(t&&this._trashed==="include")a=a?`(${a}) AND ${L} IS NULL`:`${L} IS NULL`;let d=a?` WHERE ${a}`:"",u=t?Y():void 0;if(!s?.beforeDelete&&!s?.afterDelete)return t?(await r.run(`UPDATE ${o} SET ${L} = ?${d}`,[u,...i])).changes:(await r.run(`DELETE FROM ${o}${d}`,i)).changes;let c=this._definition.primaryKey||"id",f=(await r.all(`SELECT * FROM ${o}${d}`,i)).map((M)=>new I(this._definition,M,!0)),g=f.map((M)=>M._attributes[c]);if(g.some((M)=>M==null))throw Error(`Cannot delete a model without a primary key: '${c}' is missing from a matching row`);for(let M of f)await s.beforeDelete?.(M);let R=0;for(let M=0;M<g.length;M+=Ae){let x=g.slice(M,M+Ae),A=`${c} IN (${x.map(()=>"?").join(", ")})`;R+=t?(await r.run(`UPDATE ${o} SET ${L} = ? WHERE ${A}`,[u,...x])).changes:(await r.run(`DELETE FROM ${o} WHERE ${A}`,x)).changes}for(let M of f){if(t)M._attributes[L]=u;await s.afterDelete?.(M)}return R}async update(t){this.assertNoUnappliedClauses("update");let r=S(),o=Object.entries(t),s=o.map(([u])=>`${W(u)} = ?`).join(", "),i=o.map(([,u])=>u);if(Z(this._definition))i.push(Y());let a=`UPDATE ${this._definition.table} SET ${s}${Z(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(i);if(d)a+=` WHERE ${d}`;return(await r.run(a,i)).changes}}function tt(t){let r={query:()=>new E(t),where(o,s,i){return new E(t).where(o,s,i)},orWhere(o,s,i){return new E(t).orWhere(o,s,i)},whereIn(o,s){return new E(t).whereIn(o,s)},whereNotIn(o,s){return new E(t).whereNotIn(o,s)},whereNull(o){return new E(t).whereNull(o)},whereNotNull(o){return new E(t).whereNotNull(o)},whereLike(o,s){return new E(t).whereLike(o,s)},orderBy(o,s="asc"){return new E(t).orderBy(o,s)},orderByDesc(o){return new E(t).orderByDesc(o)},select(...o){return new E(t).select(...o)},with(...o){return new E(t).with(...o)},limit:(o)=>new E(t).limit(o),take:(o)=>new E(t).take(o),skip:(o)=>new E(t).skip(o),withTrashed:()=>new E(t).withTrashed(),onlyTrashed:()=>new E(t).onlyTrashed(),async find(o){let s=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} IS NULL`:"",d=await s.get(`SELECT * FROM ${t.table} WHERE ${i} = ?${a}`,[o]);return d?new I(t,d,!0):void 0},async findOrFail(o){let s=await r.find(o);if(!s)throw Error(`${t.name} with id ${o} not found`);return s},async findMany(o){let s=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} IS NULL`:"";return(await s.all(`SELECT * FROM ${t.table} WHERE ${i} IN (${o.map(()=>"?").join(", ")})${a}`,o)).map((u)=>new I(t,u,!0))},all:()=>new E(t).get(),first:()=>new E(t).first(),firstOrFail:()=>new E(t).firstOrFail(),last:()=>new E(t).last(),count:()=>new E(t).count(),exists:()=>new E(t).exists(),doesntExist:()=>new E(t).doesntExist(),paginate:(o,s)=>new E(t).paginate(o,s),whereBetween(o,s){return new E(t).whereBetween(o,s)},whereNotBetween(o,s){return new E(t).whereNotBetween(o,s)},async create(o){let s=new I(t,o,!1);return await s.save(),s},async createMany(o){let s=o.map((c)=>new I(t,c,!1));if(!s.length)return[];let i=S(),a=t.primaryKey||"id",d=[];for(let c of s)d.push(await c._prepareInsert());let u=new Map;d.forEach((c,T)=>{let f=Object.keys(c).join("\x00"),g=u.get(f);if(g)g.push(T);else u.set(f,[T])});for(let[c,T]of u){let f=c?c.split("\x00"):[],g=!f.includes(a);if(!f.length||g&&i.dialect==="mysql"){for(let M of T){let x=d[M],A=Object.keys(x),w=await i.insert(A.length?`INSERT INTO ${t.table} (${A.join(", ")}) VALUES (${A.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(x),a);await s[M]._markInserted(x,g?w.lastInsertId:void 0)}continue}if(i.dialect==="postgres"&&Ve(t,f,T.map((M)=>d[M]))){let M=t.table,x=f.join(", "),A=`INSERT INTO ${M} (${x}) SELECT ${x} FROM jsonb_populate_recordset(NULL::${M}, (?::text)::jsonb)`;for(let w=0;w<T.length;w+=_e){let h=T.slice(w,w+_e),K=JSON.stringify(h.map((v)=>Object.fromEntries(f.map((P)=>[P,d[v][P]??null]))),ze);if(!g){await i.run(A,[K]);for(let v of h)await s[v]._markInserted(d[v]);continue}let p=(await i.all(`${A} RETURNING ${a}`,[K])).map((v)=>v[a]),y=p.every((v)=>typeof v==="number"||typeof v==="bigint")?[...p].sort((v,P)=>v<P?-1:v>P?1:0):p;for(let v=0;v<h.length;v++)await s[h[v]]._markInserted(d[h[v]],y[v])}continue}let R=xe(Math.max(1,Math.floor(Qe/f.length)));for(let M=0;M<T.length;){let x=Math.min(R,xe(T.length-M)),A=T.slice(M,M+x);M+=x;let w=`INSERT INTO ${t.table} (${f.join(", ")}) VALUES ${A.map(()=>`(${f.map(()=>"?").join(", ")})`).join(", ")}`,h=A.flatMap((y)=>f.map((v)=>d[y][v]));if(!g){await i.run(w,h);for(let y of A)await s[y]._markInserted(d[y]);continue}let K=(await i.all(`${w} RETURNING ${a}`,h)).map((y)=>y[a]),p=K.every((y)=>typeof y==="number"||typeof y==="bigint")?[...K].sort((y,v)=>y<v?-1:y>v?1:0):K;for(let y=0;y<A.length;y++)await s[A[y]]._markInserted(d[A[y]],p[y])}}return s},async updateOrCreate(o,s){let i=new E(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);let a=await i.first();if(a)return await a.update(s),a;return this.create({...o,...s})},async firstOrCreate(o,s){let i=new E(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);return await i.first()||this.create({...o,...s})},async update(o,s){let i=await r.findOrFail(o);return await i.update(s),i},async delete(o){let s=await r.find(o);return s?s.delete():!1},destroy(o){return r.delete(o)},async forceDelete(o){let s=await r.withTrashed().find(o);return s?s.forceDelete():!1},remove(o){return r.forceDelete(o)},async truncate(){await S().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(o={}){return new I(t,o,!1)},latest:(o="created_at")=>new E(t).orderByDesc(o),oldest:(o="created_at")=>new E(t).orderBy(o,"asc"),max:(o)=>new E(t).max(o),min:(o)=>new E(t).min(o),avg:(o)=>new E(t).avg(o),sum:(o)=>new E(t).sum(o),pluck(o){return new E(t).pluck(o)}};return new Proxy(r,{get(o,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let i=s.slice(5),a=i.charAt(0).toLowerCase()+i.slice(1);if(a in t.attributes||a==="id"||a===t.primaryKey)return(d)=>new E(t).where(a,d)}return Reflect.get(o,s)}})}function Kt(t){let r=tt(t);if(t?.name)qe(t.name,r);return r}async function jn(t){let r=S(),o=C(t.primaryKey||"id"),s=[],i=new Set([o]);if(s.push(t.autoIncrement!==!1?`${o} INTEGER PRIMARY KEY AUTOINCREMENT`:`${o} INTEGER PRIMARY KEY`),t.traits?.useUuid)s.push("uuid TEXT UNIQUE"),i.add("uuid");for(let[a,d]of Object.entries(t.attributes)){let u=C(a);if(i.has(u))continue;i.add(u);let c=De(d.type),T=Pe(c);if(u.endsWith("_id")&&(c===void 0||N(c)))T="INTEGER";let f=`${u} ${T}`;if(d.unique)f+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let g=d.foreignKey;if(f+=` REFERENCES ${g.table}(${g.column??"id"})`,g.onDelete)f+=` ON DELETE ${g.onDelete.toUpperCase()}`;if(g.onUpdate)f+=` ON UPDATE ${g.onUpdate.toUpperCase()}`}s.push(f)}for(let a of O(t.belongsTo)){let d=a.foreignKey??`${C(a.model)}_id`;if(i.has(d))continue;i.add(d),s.push(`${d} INTEGER`)}if(Z(t))for(let a of["created_at","updated_at"]){if(i.has(a))continue;i.add(a),s.push(`${a} TEXT`)}if(ee(t)&&!i.has("deleted_at"))i.add("deleted_at"),s.push("deleted_at TEXT");await r.run(`CREATE TABLE IF NOT EXISTS ${t.table} (${s.join(", ")})`,[])}async function qn(t,r,o){let s=S(),i=t.traits?.useSeeder,a=r??(typeof i==="object"&&i?i.count:10);if(!o)try{let d=await import("./chunk-r2ta1rnj.js");o=Pt(d.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let d=0;d<a;d++){let u={};for(let[T,f]of Object.entries(t.attributes))if(f.factory)u[C(T)]=f.factory(o);if(Z(t)){let T=Y();u.created_at=T,u.updated_at=T}if(t.traits?.useUuid)u.uuid=crypto.randomUUID();let c=Object.keys(u);await s.run(`INSERT INTO ${t.table} (${c.join(", ")}) VALUES (${c.map(()=>"?").join(", ")})`,Object.values(u))}}var oe=new Map;function rn(t){return oe.get(t)}function sn(){return[...oe.values()]}function an(){return Object.fromEntries(oe)}function on(t){return oe.has(t)}function ln(){oe.clear(),Bt()}function Ft(t,r){return oe.set(t,r),r}function nt(){return typeof window<"u"&&typeof document<"u"}function cn(t){let r;if(nt())r=We(t);else{let o=Kt(t);r=Object.assign(o,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return Ft(t.name,r),r}function un(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
|
|
2
|
+
import{We}from"./chunk-93ny6tvm.js";import{n,e,k,_,b,Fe,m,D,l,at,X}from"./chunk-3hwsz4q7.js";function N(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function De(t){if(typeof t!=="string")return;switch(t.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function Pe(t){switch(t){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}import{Database as Te}from"bun:sqlite";function te(t){if(typeof t==="number")return{length:t};return t}function me(t){if(typeof t==="number")return{max:t};return t}function Le(t){return typeof t==="function"}function Ue(t){return t.replace(/[A-Z]/g,(r)=>r.toLowerCase())}function ke(t,r){if(!r||typeof r.fractionDigits!=="number")return t;return Number(t.toFixed(r.fractionDigits))}function z(t,r={}){if(!t)return r;return new Proxy(t,{get(o,s){if(s in r)return r[s];let i=o[s];if(i!==void 0)return i;let a=o[Ue(s)];if(Le(a))return a.bind(o);return}})}function Pt(t){let r=(f)=>{let g=Array.isArray(f)?f:[],R=Math.floor(Math.random()*g.length);return g[R]},o=()=>t.string,s=()=>t.number,i=()=>t.random,a=z(t.string,{alpha:(f)=>o()?.alpha?.(te(f)),alphanumeric:(f)=>o()?.alphanumeric?.(te(f)),numeric:(f)=>o()?.numeric?.(te(f)),sample:(f)=>o()?.sample?.(te(f)),hexadecimal:(f)=>o()?.hexadecimal?.(te(f))}),d=z(t.number,{int:(f)=>s()?.int?.(me(f)),float:(f)=>{let g=me(f);return ke(Number(s()?.float?.(g)??0),g)}}),u=z(t.helpers,{arrayElement:r,arrayElements:(f,g)=>{let R=[...Array.isArray(f)?f:[]],M=typeof g==="number"?g:Math.max(1,Math.floor(Math.random()*R.length));for(let x=R.length-1;x>0;x-=1){let A=Math.floor(Math.random()*(x+1));[R[x],R[A]]=[R[A],R[x]]}return R.slice(0,Math.min(M,R.length))},shuffle:(f)=>{let g=[...Array.isArray(f)?f:[]];for(let R=g.length-1;R>0;R-=1){let M=Math.floor(Math.random()*(R+1));[g[R],g[M]]=[g[M],g[R]]}return g},maybe:(f,g)=>{let R=typeof g?.probability==="number"?g.probability:0.5;return Math.random()<R?f():void 0},slugify:(f)=>String(f??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),T={string:a,number:d,helpers:u,datatype:{boolean:(f)=>{let g=typeof f==="number"?f:f?.probability;if(typeof g==="number")return Math.random()<g;return Boolean(i()?.boolean?.())},number:(f)=>Number(s()?.int?.(me(f))??0),float:(f)=>ke(Number(s()?.float?.(f)??0),f),uuid:()=>crypto.randomUUID(),string:(f)=>String(o()?.alphanumeric?.({length:f??10})??""),hexadecimal:(f)=>String(o()?.hexadecimal?.(te(f))??""),array:(f)=>Array.from({length:f??3},()=>o()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:o()?.alphanumeric?.({length:8})})},location:z(t.address),address:z(t.address),vehicle:z(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:z(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(f,g){if(g in T)return T[g];let R=f[g];if(R&&typeof R==="object")return z(R);return R}})}function Be(t){if(typeof t==="string")return{model:t};if(t&&typeof t==="object"&&typeof t.model==="string"){let r=t;return{model:r.model,foreignKey:r.foreignKey,onDelete:r.onDelete}}return null}function O(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(Be).filter((o)=>o!==null)}function Y(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var $e=/^[A-Z_][A-Z0-9_]*$/i;function H(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);if(t.length>64)throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' exceeds 64 chars`);if(!$e.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Se(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);let o=t.split(".");if(o.length>2||o.some((s)=>s.length===0||s.length>64||!$e.test(s)))throw TypeError(`[bun-query-builder] ${r}: invalid ORDER BY column '${t}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Me(t,r){if(r.length!==1)return r;let o=r[0];if(Array.isArray(o))return[...o];if(o===void 0&&X(t)===0)return[];return r}var ae=null,we=new Map;function qe(t,r){we.set(t,r),re.clear()}function Bt(){we.clear(),re.clear()}function j(t){if(!ae)try{ae=import.meta.require("./chunk-56n17myf.js").getModel}catch{ae=()=>{return}}return ae(t)??we.get(t)}var le=new Map,He=500;function Ke(t){let r=le.get(t);if(r!==void 0)return r;let o=at(t,"postgres");if(le.size>=He)le.clear();return le.set(t,o),o}function _t(t){if(t==null)return 0;if(typeof t.affectedRows==="number")return t.affectedRows;if(typeof t.count==="number")return t.count;if(Array.isArray(t))return t.length;return 0}function It(t){if(t==null||typeof t!=="object")return null;if("insertId"in t&&t.insertId!=null)return t.insertId;if("lastInsertRowid"in t&&t.lastInsertRowid!=null)return t.lastInsertRowid;return null}class pe{sqliteDb;dialect="sqlite";constructor(t){this.sqliteDb=t}all(t,r){return Promise.resolve(this.sqliteDb.query(t).all(...r))}get(t,r){return Promise.resolve(this.sqliteDb.query(t).get(...r)??void 0)}run(t,r){let o=this.sqliteDb.run(t,r);return Promise.resolve({changes:o.changes,lastInsertId:o.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class be{dialect;constructor(t){this.dialect=t}conn(){return b()}text(t){return this.dialect==="postgres"?Ke(t):t}async all(t,r){let o=await this.conn().unsafe(this.text(t),r);return Array.isArray(o)?o:[]}async get(t,r){let o=await this.conn().unsafe(this.text(t),r);if(Array.isArray(o))return o[0]??void 0;return o??void 0}async run(t,r){let o=await this.conn().unsafe(this.text(t),r);return{changes:_t(o),lastInsertId:It(o)}}async insert(t,r,o){if(this.dialect==="postgres"){let a=await this.conn().unsafe(`${Ke(t)} RETURNING ${o}`,r),d=Array.isArray(a)?a[0]:a;return{changes:1,lastInsertId:d?d[o]??null:null}}let s=await this.conn().unsafe(t,r),i=It(s);if(i==null&&this.dialect!=="sqlite"){let a=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);i=(Array.isArray(a)?a[0]:a)?.id??null}return{changes:_t(s)||1,lastInsertId:i}}}var Q=null,ce=!1,U=null,ne=null,ue=null,de=null;function Ln(t){if(t.database instanceof Te)Q=t.database,ce=!1;else Q=new Te(t.database||":memory:",{create:!0}),ce=!0,k(Q);U=null,ne=null}function Kn(){let t=ce,r=Q;if(Q=null,ce=!1,U=null,ne=null,ue=null,de=null,t&&r)try{r.close()}catch{}}var Re=!1;function S(){if(Q){if(!U||ne!==Q)U=new pe(Q),ne=Q,ue="sqlite",de=null;return U}let t=e.dialect,r=e.database?.database??null,o=`${r??""}|${_()?.url??""}`;if(U&&ne===null&&ue===t&&de===o)return U;if(ne=null,ue=t,de=o,t==="sqlite"&&_())U=new be(t);else if(t==="sqlite"){if(!r&&!Re)Re=!0,console.warn("[bun-query-builder] The model layer has no database configured, so it is using an in-memory SQLite database and nothing it writes will persist. Configure one with setConfig({ dialect, database }) or configureOrm({ database }), or name ':memory:' explicitly to silence this.");let s=new Te(r||":memory:",{create:!0});k(s),U=new pe(s)}else U=new be(t);return U}function Fn(){let t=S();if(t.sqliteDb)return t.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${t.dialect}'. Use the async model API instead.`)}var Qe=4096,_e=1000;function Ve(t,r,o){let s=t.attributes,i=new Map(Object.entries(s).map(([a,d])=>[C(a),d]));for(let a of r){let d=String(i.get(a)?.type??"").toLowerCase();if(d==="json"||d==="jsonb")return!1}for(let a of o)for(let d of r){let u=a[d];if(u===null||u===void 0||u instanceof Date)continue;let c=typeof u;if(c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="bigint")return!1}return!0}function ze(t,r){return typeof r==="bigint"?r.toString():r}function xe(t){return 2**Math.floor(Math.log2(t))}var L="deleted_at",Ae=500,ye="__btm_rel__";function ee(t){let r=t.traits;return Boolean(r?.useSoftDeletes||r?.softDeletable)}function Z(t){let r=t.traits;return Boolean(r?.useTimestamps||r?.timestampable)}var Ee=new WeakMap;function Ge(t){let r=Ee.get(t);if(r)return r;let o=new Set,s=t.belongsToMany;if(s){if(Array.isArray(s)){for(let i of s)if(typeof i==="string")o.add(i.toLowerCase());else if(i&&typeof i==="object"&&i.model)o.add(i.model.toLowerCase())}else if(typeof s==="object")for(let i of Object.keys(s))o.add(i)}return Ee.set(t,o),o}function Oe(t){let r={};for(let[o,s]of Object.entries(t))r[C(o)]=s;return r}function Xe(t){for(let r in t)if(C(r)!==r)return Oe(t);return t}function Ye(t,r){if(t[r])return t[r];let o=C(r);if(t[o])return t[o];for(let s of Object.keys(t))if(C(s)===o)return t[s];return}class I{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_exists;_relations={};constructor(t,r,o){this._definition=t,this._exists=o,this._attributes=Xe({...r}),this._original=null;let s=Ge(t);if(s.size===0)return;let i=this;return new Proxy(this,{get(a,d,u){if(typeof d==="string"&&s.has(d)&&!(d in a))return()=>{let c=Ie(t,d);if(!c||c.type!=="belongsToMany")throw Error(`[orm] relation '${d}' did not resolve to a belongsToMany on '${t.name}'`);let T=j(c.relatedModelName),f=T?.getDefinition?.()||T?.definition;if(!f)throw Error(`[orm] related model '${c.relatedModelName}' is not registered`);return new Lt(i,t,c,f)};return Reflect.get(a,d,u)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(t){let r=this._definition.get?.[t];if(r)try{let o=r(this._attributes);if(o!==void 0)return o}catch{}return this._attributes[C(t)]}getAttribute(t){return this._attributes[C(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[C(t)]=r}only(t){let r={};for(let o of t)r[o]=this._attributes[C(o)];return r}except(t){let r=new Set(t.map((s)=>C(s))),o={};for(let s of Object.keys(this._attributes))if(!r.has(s))o[s]=this._attributes[s];return o}getRelation(t){return this._relations[t]}setRelation(t,r){this._relations[t]=r}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let t=this._definition.primaryKey||"id";return this._attributes[t]}isDirty(t){if(this._original===null)return!1;if(t){let r=C(t);return this._attributes[r]!==this._original[r]}return Object.keys(this._attributes).some((r)=>this._attributes[r]!==this._original[r])}isClean(t){return!this.isDirty(t)}getOriginal(t){return this.getOriginalAttributes()[C(t)]}getChanges(){if(this._original===null)return{};let t={};for(let r of Object.keys(this._attributes))if(this._attributes[r]!==this._original[r])t[r]=this._attributes[r];return t}fill(t){let r=this._definition.attributes;for(let[o,s]of Object.entries(t)){let i=Ye(r,o),a=!i&&C(o).endsWith("_id");if(i?.fillable&&!i?.guarded||a){if(this._original===null)this._original={...this._attributes};this._attributes[C(o)]=s}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Oe(t);Object.assign(this._attributes,r);for(let o of Object.keys(r))this._forced.add(o);return this}async _prepareInsert(){this._applySetters();let t=this._definition.primaryKey||"id",r=this._definition.hooks,o=this._definition.attributes,s={};for(let[u,c]of Object.entries(o)){if(c.guarded&&!this._forced.has(C(u)))continue;let T=C(u);if(this._attributes[T]!==void 0)s[T]=this._attributes[T]}for(let u of Object.keys(this._attributes))if(u.endsWith("_id")&&u!==t&&!(u in s))s[u]=this._attributes[u];let i=this._attributes[t],d=o[t]?.guarded&&!this._forced.has(t);if(i!=null&&!(t in s)&&!d)s[t]=i;if(Z(this._definition)){let u=Y(),c=this._attributes.created_at;s.created_at=c===void 0||c===null?u:c,s.updated_at=u}if(this._definition.traits?.useUuid&&!s.uuid)s.uuid=crypto.randomUUID();return await r?.beforeCreate?.(s),s}async _markInserted(t,r){let o=this._definition.primaryKey||"id";for(let[s,i]of Object.entries(t))this._attributes[s]=i;if(!(o in t)&&r!=null)this._attributes[o]=r;this._exists=!0,await this._definition.hooks?.afterCreate?.(this),this._original={...this._attributes},this._hasSaved=!0}_applySetters(){let t=this._definition.set||{};for(let[r,o]of Object.entries(t))if(this.isDirty(r))this._attributes[C(r)]=o(this._attributes)}async save(){let t=S(),r=this._definition.primaryKey||"id",o=this._definition.hooks;if(this._exists){this._applySetters(),await o?.beforeUpdate?.(this,this.getChanges());let s=this.getChanges(),i=Object.keys(s);if(i.length>0){if(this._attributes[r]==null)throw Error(`Cannot save a model without a primary key: '${r}' was not selected`);let a=i.map((u)=>`${u} = ?`).join(", "),d=[...Object.values(s),this._attributes[r]];if(Z(this._definition)){let u=Y();await t.run(`UPDATE ${this._definition.table} SET ${a}, updated_at = ? WHERE ${r} = ?`,[...Object.values(s),u,this._attributes[r]])}else await t.run(`UPDATE ${this._definition.table} SET ${a} WHERE ${r} = ?`,d)}await o?.afterUpdate?.(this)}else{let s=await this._prepareInsert(),i=Object.keys(s),a=i.map(()=>"?").join(", "),d=await t.insert(`INSERT INTO ${this._definition.table} (${i.join(", ")}) VALUES (${a})`,Object.values(s),r);return await this._markInserted(s,r in s?void 0:d.lastInsertId),this}return this._original={...this._attributes},this._hasSaved=!0,this}async update(t){return this.fill(t),this.save()}async fresh(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(o==null)return null;let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return new I(this._definition,s,!0)}async delete(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r],s=this._definition.hooks;if(o==null)throw Error("Cannot delete a model without a primary key");if(await s?.beforeDelete?.(this),ee(this._definition)){let i=Y();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[i,o]),this._attributes[L]=i}else await t.run(`DELETE FROM ${this._definition.table} WHERE ${r} = ?`,[o]);return await s?.afterDelete?.(this),!0}async forceDelete(){let t=this._definition.primaryKey||"id",r=this._attributes[t],o=this._definition.hooks;if(r==null)throw Error("Cannot delete a model without a primary key");return await o?.beforeDelete?.(this),await S().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await o?.afterDelete?.(this),!0}async restore(){if(!ee(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let t=this._definition.primaryKey||"id",r=this._attributes[t];if(!r)throw Error("Cannot restore a model without a primary key");return await S().run(`UPDATE ${this._definition.table} SET ${L} = ? WHERE ${t} = ?`,[null,r]),this._attributes[L]=null,this._original=null,this}trashed(){return this._attributes[L]!=null}async refresh(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(!o)throw Error("Cannot refresh a model without a primary key");let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return this._attributes=s,this._original=null,this}replicate(){let t=this._definition.primaryKey||"id",r={...this._attributes};return delete r[t],delete r.uuid,delete r.created_at,delete r.updated_at,new I(this._definition,r,!1)}toArray(){let t={...this._attributes};for(let[r,o]of Object.entries(this._relations))if(Array.isArray(o))t[r]=o.map((s)=>s.toArray());else if(o)t[r]=o.toArray();else t[r]=null;return t}toJSON(){let t=new Set;for(let[o,s]of Object.entries(this._definition.attributes))if(s.hidden)t.add(o);let r={};for(let[o,s]of Object.entries(this._attributes))if(!t.has(o))r[o]=s;for(let[o,s]of Object.entries(this._relations))if(Array.isArray(s))r[o]=s.map((i)=>i.toJSON());else if(s)r[o]=s.toJSON();else r[o]=null;return r}}var ve=new Map,Ne=new Map,re=new Map,Je=1000;function W(t){return C(t)}function C(t){let r=ve.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ve.set(t,r),r}function G(t){let r=Ne.get(t);if(r!==void 0)return r;return r=Fe(t),Ne.set(t,r),r}var fe=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],Ze=[...fe,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Ce(t,r){let o=t[r];if(!o)return[];if(Array.isArray(o))return o.map((s)=>typeof s==="string"?s:String(s?.model??"")).filter(Boolean);if(typeof o==="object")return Object.keys(o);if(typeof o==="string")return[o];return[]}function et(t,r){let o=t.name??t.table??"model",i=Ze.filter((d)=>Ce(t,d).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((d)=>!fe.includes(d));if(i.length>0)return`[orm] '${o}' declares '${r}' as ${i.join("/")}, which eager loading does not support yet. Supported kinds: ${fe.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let a=fe.flatMap((d)=>Ce(t,d));return a.length>0?`[orm] '${o}' has no relation '${r}'. Available: ${a.join(", ")}.`:`[orm] '${o}' has no relation '${r}' \u2014 it declares no relations at all.`}function Ie(t,r){let{name:o,table:s}=t,i=t.primaryKey||"id";function a(w){if(!w)return null;if(Array.isArray(w)){for(let h of w){let K=typeof h==="string"?h:h?.model||"";if(K&&K.toLowerCase()===r.toLowerCase())return K}return null}if(typeof w==="object"){for(let[h,K]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return typeof K==="string"?K:K?.model||K?.target||h}return null}function d(){let w=t.belongsTo;if(!w)return null;let h=r.toLowerCase(),K=(p)=>{if(typeof p==="string")return{model:p};if(p&&typeof p==="object"&&typeof p.model==="string")return{model:p.model,foreignKey:p.foreignKey};return null};if(Array.isArray(w)){for(let p of w){let y=K(p);if(y&&y.model.toLowerCase()===h)return y}return null}if(typeof w==="object"){for(let[p,y]of Object.entries(w))if(p===r||p.toLowerCase()===h)return K(y)}return null}function u(){let w=t.belongsToMany;if(!w)return null;if(Array.isArray(w)){for(let h of w)if(typeof h==="string"){if(h.toLowerCase()===r.toLowerCase())return{entry:h}}else if(h&&typeof h==="object"&&h.model){if(h.model.toLowerCase()===r.toLowerCase())return{entry:h}}return null}if(typeof w==="object"){for(let[h,K]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return{entry:K}}return null}function c(w){let h=t[w];if(!h)return null;let K=r.toLowerCase();if(Array.isArray(h)){for(let p of h){let y=typeof p==="string"?p:String(p?.model??"");if(!y||y.toLowerCase()!==K)continue;let v=typeof p==="object"?p?.morphName:void 0;return{model:y,morphName:String(v??`${C(o)}able`)}}return null}if(typeof h==="object")for(let[p,y]of Object.entries(h)){let v=typeof y==="string"?y:String(y?.model??"");if(p.toLowerCase()!==K&&v.toLowerCase()!==K)continue;let P=typeof y==="object"?y?.morphName:void 0;return{model:v,morphName:String(P??p)}}return null}for(let w of["morphMany","morphOne"]){let h=c(w);if(!h)continue;let p=j(h.model)?.getTable?.()||G(h.model);return{type:w,relatedModelName:h.model,relatedTable:p,foreignKey:`${h.morphName}_id`,localKey:i,morphTypeColumn:`${h.morphName}_type`,morphTypeValue:s}}let T=a(t.hasMany);if(T){let h=j(T)?.getTable?.()||G(T),K=C(o)+"_id";return{type:"hasMany",relatedModelName:T,relatedTable:h,foreignKey:K,localKey:i}}let f=a(t.hasOne);if(f){let h=j(f)?.getTable?.()||G(f),K=C(o)+"_id";return{type:"hasOne",relatedModelName:f,relatedTable:h,foreignKey:K,localKey:i}}let g=d();if(g){let w=g.model,h=j(w),K=h?.getTable?.()||G(w),p=h?.getDefinition?.()?.primaryKey||"id",y=g.foreignKey||`${C(w)}_id`;return{type:"belongsTo",relatedModelName:w,relatedTable:K,foreignKey:y,localKey:p}}let R=u();if(R){let w=typeof R.entry==="object",h=w?R.entry.model:R.entry,p=j(h)?.getTable?.()||G(h),y=w?R.entry:null,v,P;if(y?.table)v=y.table;else if(y?.through){P=y.through;let B=j(y.through);if(!B)throw Error(`[orm] belongsToMany relation '${r}' on '${o}' references unknown through model '${y.through}'. Make sure '${y.through}' is registered.`);v=B.getTable?.()||B.getDefinition?.()?.table||G(y.through)}else{let B=ie(s),q=ie(p);v=[B,q].sort().join("_")}let F=y?.foreignKey||`${ie(s)}_id`,J=y?.relatedKey||`${ie(p)}_id`,V=[];if(y?.pivot?.columns)for(let B of Object.keys(y.pivot.columns))V.push(B);if(P){let B=j(P),q=B?.getDefinition?.()||B?.definition,he=q?.attributes??{},je=q?.primaryKey??"id";for(let se of Object.keys(he)){if(se===F||se===J||se===je)continue;if(!V.includes(se))V.push(se)}}return{type:"belongsToMany",relatedModelName:h,relatedTable:p,foreignKey:F,localKey:i,pivotTable:v,pivotFkParent:F,pivotFkRelated:J,pivotColumns:V,pivotModelName:P,pivotTimestamps:Boolean(y?.pivot?.timestamps)}}let M=(w,h)=>{if(!w||typeof w!=="object"||Array.isArray(w))return null;let K=w[r]??w[Object.keys(w).find((q)=>q.toLowerCase()===r.toLowerCase())??""];if(!K||typeof K!=="object")return null;let{through:p,target:y}=K;if(!p||!y)return null;let v=j(p),P=v?.getDefinition?.()||v?.definition,F=v?.getTable?.()||P?.table||G(p),J=P?.primaryKey||"id",B=j(y)?.getTable?.()||G(y);return{type:h,relatedModelName:y,relatedTable:B,foreignKey:`${C(o)}_id`,localKey:i,throughTable:F,throughForeignKey:`${C(o)}_id`,throughLocalKey:J,targetForeignKey:`${ie(F)}_id`}},x=M(t.hasManyThrough,"hasManyThrough");if(x)return x;let A=M(t.hasOneThrough,"hasOneThrough");if(A)return A;return null}function ge(t,r){let o=new Set;for(let s of t){let i=s.get(r);if(i!=null)o.add(i)}return[...o]}function ie(t){return m(e.relations?.singularizeStrategy)(t)}class Lt{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(t,r,o,s){this._parent=t,this._parentDef=r,this._resolved=o,this._relatedDef=s}get parentId(){let t=this._parentDef.primaryKey||"id";return this._parent.get(t)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(t,r,o){if(o===void 0)this._wheres.push({sql:`${this.relatedTable}.${t} = ?`,params:[r]});else this._wheres.push({sql:`${this.relatedTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivot(t,r,o){if(o===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${t} = ?`,params:[r]});else this._pivotWheres.push({sql:`${this.pivotTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IN (${o})`,params:[...r]}),this}wherePivotNotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} NOT IN (${o})`,params:[...r]}),this}wherePivotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NULL`,params:[]}),this}wherePivotNotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NOT NULL`,params:[]}),this}orderBy(t,r="asc"){if(Se(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push(`${t} ${r.toUpperCase()}`),this}limit(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${t}`);return this._limit=t,this}offset(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${t}`);return this._offset=t,this}relatedSelectColumns(){let t=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),r=this._relatedDef.traits;if(r?.useTimestamps||r?.timestampable)t.add("created_at"),t.add("updated_at");if(r?.useSoftDeletes||r?.softDeletable)t.add("deleted_at");if(r?.useUuid)t.add("uuid");return[...t]}buildSelect(){let t=[],o=`SELECT ${this.relatedSelectColumns().map((s)=>`${this.relatedTable}.${s} AS ${ye}${s}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;o+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,o+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,t.push(this.parentId);for(let s of this._pivotWheres)o+=` AND ${s.sql}`,t.push(...s.params);for(let s of this._wheres)o+=` AND ${s.sql}`,t.push(...s.params);if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}hydrateRows(t){let r=this.fkParent,o=this.fkRelated;return t.map((s)=>{let i={},a={};for(let[u,c]of Object.entries(s))if(u.startsWith(ye))i[u.slice(ye.length)]=c;else if(u!==r&&u!==o)a[u]=c;let d=new I(this._relatedDef,i,!0);return d.pivot=a,d})}async get(){let t=S(),{sql:r,params:o}=this.buildSelect(),s=await t.all(r,o);return this.hydrateRows(s)}async first(){return this._limit=1,(await this.get())[0]}async count(){let t=S(),r=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,o=[this.parentId];for(let i of this._pivotWheres)r+=` AND ${i.sql}`,o.push(...i.params);let s=await t.get(r,o);return Number(s?.count??0)}async exists(){return await this.count()>0}now(){return Y()}async attach(t,r={}){let o=S(),s=Array.isArray(t)?t:[t];if(s.length===0)return 0;let i=this._resolved.pivotTimestamps?this.now():null,a=0;for(let d of s){let u={[this.fkParent]:this.parentId,[this.fkRelated]:d,...r};if(i){if(u.created_at===void 0)u.created_at=i;if(u.updated_at===void 0)u.updated_at=i}let c=Object.keys(u),T=c.map(()=>"?").join(", "),f=`INSERT INTO ${this.pivotTable} (${c.join(", ")}) VALUES (${T})`,g=c.map((R)=>u[R]);await o.run(f,g),a++}return a}async detach(t){let r=S(),o=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,s=[this.parentId];if(t!==void 0&&t!==null){let i=Array.isArray(t)?t:[t];if(i.length===0)return 0;let a=i.map(()=>"?").join(", ");o+=` AND ${this.fkRelated} IN (${a})`,s.push(...i)}return(await r.run(o,s)).changes}async updateExistingPivot(t,r){let o=S(),s={...r};if(this._resolved.pivotTimestamps&&s.updated_at===void 0)s.updated_at=this.now();let i=Object.keys(s);if(i.length===0)return 0;let a=i.map((c)=>`${c} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${a} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,u=[...i.map((c)=>s[c]),this.parentId,t];return(await o.run(d,u)).changes}async sync(t){let r=S(),o=new Map;for(let T of t)if(T!=null&&typeof T==="object"&&"id"in T){let{id:f,...g}=T;o.set(f,g)}else o.set(T,{});let s=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),i=new Set(s.map((T)=>T[this.fkRelated])),a=[],d=[],u=[],c=[...i].filter((T)=>!o.has(T));if(c.length>0)await this.detach(c),d.push(...c);for(let[T,f]of o)if(!i.has(T))await this.attach(T,f),a.push(T);else if(Object.keys(f).length>0)await this.updateExistingPivot(T,f),u.push(T);return{attached:a,detached:d,updated:u}}async toggle(t){let r=S(),o=Array.isArray(t)?t:[t];if(o.length===0)return{attached:[],detached:[]};let s=o.map(()=>"?").join(", "),i=await r.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${s})`,[this.parentId,...o]),a=new Set(i.map((c)=>c[this.fkRelated])),d=o.filter((c)=>!a.has(c)),u=o.filter((c)=>a.has(c));if(d.length>0)await this.attach(d);if(u.length>0)await this.detach(u);return{attached:d,detached:u}}}class E{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(t){this._definition=t}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"and"});else this._wheres.push({column:t,operator:r,value:o,boolean:"and"});return this}orWhere(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"or"});else this._wheres.push({column:t,operator:r,value:o,boolean:"or"});return this}whereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"and"}),this}orWhereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"or"}),this}whereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"and"}),this}orWhereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"or"}),this}whereNull(t){return H(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return H(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return H(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return H(t,"orWhereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"or"}),this}whereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"and"}),this}orWhereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"or"}),this}whereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"and"}),this}orWhereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"or"}),this}whereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Me(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Me(t,r),boolean:"or"}),this}whereGroup(t){return this._addGroup("and",t)}orWhereGroup(t){return this._addGroup("or",t)}_addGroup(t,r){let o=new E(this._definition);if(r(o),o._wheres.length===0)return this;let s=[],i=o.buildWhereClauses(s);if(!i)return this;return this._wheres.push({raw:`(${i})`,rawParams:s,boolean:t}),this}whereBetween(t,r){return H(t,"whereBetween(column)"),this._wheres.push({column:t,operator:">=",value:r[0],boolean:"and"}),this._wheres.push({column:t,operator:"<=",value:r[1],boolean:"and"}),this}whereNotBetween(t,r){H(t,"whereNotBetween(column)");let o=W(t);return this._wheres.push({raw:`(${o} < ? OR ${o} > ?)`,rawParams:[r[0],r[1]],boolean:"and"}),this}when(t,r){if(t)return r(this);return this}orderBy(t,r="asc"){if(Se(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push({column:t,direction:r}),this}orderByDesc(t){return this.orderBy(t,"desc")}orderByAsc(t){return this.orderBy(t,"asc")}latest(t="created_at"){return this.orderBy(t,"desc")}oldest(t="created_at"){return this.orderBy(t,"asc")}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}select(...t){return this._select=t,this}with(...t){for(let r of t)if(!this._withRelations.includes(r))this._withRelations.push(r);return this}getWithRelations(){return this._withRelations}buildWhereClauses(t){let r=[];for(let o of this._wheres){let s;if(o.raw){if(s=o.raw,o.rawParams&&o.rawParams.length>0)t.push(...o.rawParams)}else if(o.value===null){let i=W(o.column);s=o.operator==="="?`${i} IS NULL`:`${i} IS NOT NULL`}else if(o.operator==="in"||o.operator==="not in"){let i=o.value;s=l(W(o.column),i,o.operator==="not in",i.map(()=>"?").join(", ")),t.push(...i)}else s=`${W(o.column)} ${o.operator} ?`,t.push(o.value);r.push({conn:o.boolean==="or"?"OR":"AND",sql:s})}return D(r)}softDeleteClause(){if(this._trashed==="include"||!ee(this._definition))return"";return this._trashed==="only"?`${L} IS NOT NULL`:`${L} IS NULL`}assertNoUnappliedClauses(t){let r=[];if(this._limit!==void 0)r.push("limit()");if(this._offset!==void 0)r.push("offset()");if(this._orderBy.length>0)r.push("orderBy()");if(r.length>0)throw TypeError(`[orm] ${t}() cannot apply ${r.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere(t){let r=this._wheres.length>0?this.buildWhereClauses(t):"",o=this.softDeleteClause();if(r&&o)return`(${r}) AND ${o}`;return r||o}buildQuery(){let t=[],o=`SELECT ${this._select.map((i)=>i==="*"?i:W(i)).join(", ")} FROM ${this._definition.table}`,s=this.composeWhere(t);if(s)o+=` WHERE ${s}`;if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.map((i)=>`${W(i.column)} ${i.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}toSql(){return this.buildQuery()}async eagerLoadRelations(t){if(t.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((r)=>this.eagerLoadRelation(r,t)))}async eagerLoadRelation(t,r){let o=S(),s=this._definition.primaryKey||"id",i=`${this._definition.name}:${t}`,a=re.get(i);if(a===void 0){if(a=Ie(this._definition,t),re.size>=Je)re.clear();re.set(i,a)}if(!a)throw Error(et(this._definition,t));let d=a.type==="hasOne"||a.type==="morphOne";if(a.type==="hasMany"||a.type==="hasOne"||a.type==="morphMany"||a.type==="morphOne"){let u=ge(r,s);if(u.length===0)return;let c=u.map(()=>"?").join(", "),T=a.morphTypeColumn?` AND ${a.morphTypeColumn} = ?`:"",f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.foreignKey} IN (${c})${T}`,a.morphTypeColumn?[...u,a.morphTypeValue]:u),g=j(a.relatedModelName),R=g?.getDefinition?.()||g?.definition||this._definition;if(!d){let M=new Map;for(let x of f){let A=x[a.foreignKey];if(!M.has(A))M.set(A,[]);M.get(A).push(x)}for(let x of r){let A=M.get(x.get(s))||[];x.setRelation(t,A.map((w)=>new I(R,w,!0)))}}else{let M=new Map;for(let x of f){let A=x[a.foreignKey];if(!M.has(A))M.set(A,x)}for(let x of r){let A=M.get(x.get(s));x.setRelation(t,A?new I(R,A,!0):null)}}}if(a.type==="belongsTo"){let u=new Set;for(let x of r){let A=x._attributes[a.foreignKey];if(A!=null)u.add(A)}let c=[...u];if(c.length===0)return;let T=c.map(()=>"?").join(", "),f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.localKey} IN (${T})`,c),g=j(a.relatedModelName),R=g?.getDefinition?.()||g?.definition||this._definition,M=new Map;for(let x of f)M.set(x[a.localKey],x);for(let x of r){let A=x._attributes[a.foreignKey],w=M.get(A);x.setRelation(t,w?new I(R,w,!0):null)}}if(a.type==="belongsToMany"){let u=ge(r,s);if(u.length===0)return;if(!a.pivotTable||!a.pivotFkParent||!a.pivotFkRelated)return;let c=u.map(()=>"?").join(", "),T=await o.all(`SELECT * FROM ${a.pivotTable} WHERE ${a.pivotFkParent} IN (${c})`,u);if(T.length===0){for(let p of r)p.setRelation(t,[]);return}let f=new Set;for(let p of T){let y=p[a.pivotFkRelated];if(y!=null)f.add(y)}let g=[...f],R=j(a.relatedModelName),M=R?.getDefinition?.()||R?.definition||this._definition,x=M?.primaryKey||"id",A=[];if(g.length>0){let p=g.map(()=>"?").join(", ");A=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${x} IN (${p})`,g)}let w=new Map;for(let p of A)w.set(p[x],p);let h=new Map;for(let p of T){let y=p[a.pivotFkParent];if(!h.has(y))h.set(y,[]);h.get(y).push(p)}let K=new Set([a.pivotFkParent,a.pivotFkRelated]);for(let p of r){let y=p.get(s),P=(h.get(y)||[]).map((F)=>{let J=w.get(F[a.pivotFkRelated]);if(!J)return null;let V=new I(M,J,!0),B={};for(let[q,he]of Object.entries(F))if(!K.has(q))B[q]=he;return V.pivot=B,V}).filter((F)=>F!==null);p.setRelation(t,P)}}if(a.type==="hasManyThrough"||a.type==="hasOneThrough"){let u=ge(r,s);if(u.length===0)return;let c=a.throughLocalKey||"id",T=u.map(()=>"?").join(", "),f=await o.all(`SELECT ${c}, ${a.throughForeignKey} FROM ${a.throughTable} WHERE ${a.throughForeignKey} IN (${T})`,u);if(f.length===0){for(let K of r)K.setRelation(t,a.type==="hasManyThrough"?[]:null);return}let g=new Map;for(let K of f)g.set(K[c],K[a.throughForeignKey]);let R=[...new Set(f.map((K)=>K[c]))],M=R.map(()=>"?").join(", "),x=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.targetForeignKey} IN (${M})`,R),A=j(a.relatedModelName),w=A?.getDefinition?.()||A?.definition||this._definition,h=new Map;for(let K of x){let p=g.get(K[a.targetForeignKey]);if(p==null)continue;if(!h.has(p))h.set(p,[]);h.get(p).push(new I(w,K,!0))}for(let K of r){let p=h.get(K.get(s))||[];K.setRelation(t,a.type==="hasManyThrough"?p:p[0]??null)}}}async get(){let t=S(),{sql:r,params:o}=this.buildQuery(),i=(await t.all(r,o)).map((a)=>new I(this._definition,a,!0));if(this._withRelations.length>0)await this.eagerLoadRelations(i);return i}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let t=await this.first();if(!t)throw Error(`No ${this._definition.name} found`);return t}async find(t){let r=this._definition.primaryKey||"id";return this.where(r,t).first()}async findOrFail(t){let r=await this.find(t);if(!r)throw Error(`${this._definition.name} with id ${t} not found`);return r}async last(){let t=this._definition.primaryKey||"id";return this._orderBy=[{column:t,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let t=S(),r=[],o=`SELECT COUNT(*) as count FROM ${this._definition.table}`,s=this.composeWhere(r);if(s)o+=` WHERE ${s}`;let i=await t.get(o,r);return Number(i?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let t=await this.get();if(t.length===0)throw Error(`No ${this._definition.name} found`);if(t.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return t[0]}async increment(t,r=1){H(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let o=S(),s=[r],i=W(t),a=`UPDATE ${this._definition.table} SET ${i} = ${i} + ?`;if(Z(this._definition))a+=", updated_at = ?",s.push(Y());let d=this.composeWhere(s);if(d)a+=` WHERE ${d}`;return(await o.run(a,s)).changes}decrement(t,r=1){return this.increment(t,-r)}async chunk(t,r){let o=0;while(!0){let s=new E(this._definition);s._wheres=[...this._wheres],s._orderBy=[...this._orderBy],s._select=[...this._select],s._withRelations=[...this._withRelations],s._trashed=this._trashed,s._limit=t,s._offset=o*t;let i=await s.get();if(i.length===0)break;if(await r(i)===!1)break;if(i.length<t)break;o++}}async paginate(t=1,r=15){if(typeof t==="object"&&t!==null){let a=t;r=a.perPage??15,t=a.page??1}let o=await this.count(),s=Math.ceil(o/r);this._limit=r,this._offset=(t-1)*r;let i=await this.get();return{data:i,total:o,page:t,perPage:r,lastPage:s,hasMorePages:t<s,isEmpty:i.length===0,from:i.length>0?(t-1)*r+1:null,to:i.length>0?(t-1)*r+i.length:null,meta:{perPage:r,page:t,total:o,lastPage:s}}}async pluck(t){H(t,"pluck(column)");let r=S(),o=[],s=W(t),i=`SELECT ${s} FROM ${this._definition.table}`,a=this.composeWhere(o);if(a)i+=` WHERE ${a}`;if(this._orderBy.length>0)i+=` ORDER BY ${this._orderBy.map((u)=>`${W(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)i+=` LIMIT ${this._limit}`;if(this._offset!==void 0)i+=` OFFSET ${this._offset}`;return(await r.all(i,o)).map((u)=>u[s])}async aggregate(t,r){H(r,`${t}(column)`);let o=S(),s=[],i=`SELECT ${t}(${W(r)}) as v FROM ${this._definition.table}`,a=this.composeWhere(s);if(a)i+=` WHERE ${a}`;let u=(await o.get(i,s))?.v;if(u==null)return null;if(typeof u==="string"){let c=Number(u);return u.trim()!==""&&!Number.isNaN(c)?c:u}return u}max(t){return this.aggregate("MAX",t)}min(t){return this.aggregate("MIN",t)}async avg(t){return Number(await this.aggregate("AVG",t)??0)||0}async sum(t){return Number(await this.aggregate("SUM",t)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let t=ee(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=S(),o=this._definition.table,s=this._definition.hooks,i=[],a=this.composeWhere(i);if(t&&this._trashed==="include")a=a?`(${a}) AND ${L} IS NULL`:`${L} IS NULL`;let d=a?` WHERE ${a}`:"",u=t?Y():void 0;if(!s?.beforeDelete&&!s?.afterDelete)return t?(await r.run(`UPDATE ${o} SET ${L} = ?${d}`,[u,...i])).changes:(await r.run(`DELETE FROM ${o}${d}`,i)).changes;let c=this._definition.primaryKey||"id",f=(await r.all(`SELECT * FROM ${o}${d}`,i)).map((M)=>new I(this._definition,M,!0)),g=f.map((M)=>M._attributes[c]);if(g.some((M)=>M==null))throw Error(`Cannot delete a model without a primary key: '${c}' is missing from a matching row`);for(let M of f)await s.beforeDelete?.(M);let R=0;for(let M=0;M<g.length;M+=Ae){let x=g.slice(M,M+Ae),A=`${c} IN (${x.map(()=>"?").join(", ")})`;R+=t?(await r.run(`UPDATE ${o} SET ${L} = ? WHERE ${A}`,[u,...x])).changes:(await r.run(`DELETE FROM ${o} WHERE ${A}`,x)).changes}for(let M of f){if(t)M._attributes[L]=u;await s.afterDelete?.(M)}return R}async update(t){this.assertNoUnappliedClauses("update");let r=S(),o=Object.entries(t),s=o.map(([u])=>`${W(u)} = ?`).join(", "),i=o.map(([,u])=>u);if(Z(this._definition))i.push(Y());let a=`UPDATE ${this._definition.table} SET ${s}${Z(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(i);if(d)a+=` WHERE ${d}`;return(await r.run(a,i)).changes}}function tt(t){let r={query:()=>new E(t),where(o,s,i){return new E(t).where(o,s,i)},orWhere(o,s,i){return new E(t).orWhere(o,s,i)},whereIn(o,s){return new E(t).whereIn(o,s)},whereNotIn(o,s){return new E(t).whereNotIn(o,s)},whereNull(o){return new E(t).whereNull(o)},whereNotNull(o){return new E(t).whereNotNull(o)},whereLike(o,s){return new E(t).whereLike(o,s)},orderBy(o,s="asc"){return new E(t).orderBy(o,s)},orderByDesc(o){return new E(t).orderByDesc(o)},select(...o){return new E(t).select(...o)},with(...o){return new E(t).with(...o)},limit:(o)=>new E(t).limit(o),take:(o)=>new E(t).take(o),skip:(o)=>new E(t).skip(o),withTrashed:()=>new E(t).withTrashed(),onlyTrashed:()=>new E(t).onlyTrashed(),async find(o){let s=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} IS NULL`:"",d=await s.get(`SELECT * FROM ${t.table} WHERE ${i} = ?${a}`,[o]);return d?new I(t,d,!0):void 0},async findOrFail(o){let s=await r.find(o);if(!s)throw Error(`${t.name} with id ${o} not found`);return s},async findMany(o){let s=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} IS NULL`:"";return(await s.all(`SELECT * FROM ${t.table} WHERE ${i} IN (${o.map(()=>"?").join(", ")})${a}`,o)).map((u)=>new I(t,u,!0))},all:()=>new E(t).get(),first:()=>new E(t).first(),firstOrFail:()=>new E(t).firstOrFail(),last:()=>new E(t).last(),count:()=>new E(t).count(),exists:()=>new E(t).exists(),doesntExist:()=>new E(t).doesntExist(),paginate:(o,s)=>new E(t).paginate(o,s),whereBetween(o,s){return new E(t).whereBetween(o,s)},whereNotBetween(o,s){return new E(t).whereNotBetween(o,s)},async create(o){let s=new I(t,o,!1);return await s.save(),s},async createMany(o){let s=o.map((c)=>new I(t,c,!1));if(!s.length)return[];let i=S(),a=t.primaryKey||"id",d=[];for(let c of s)d.push(await c._prepareInsert());let u=new Map;d.forEach((c,T)=>{let f=Object.keys(c).join("\x00"),g=u.get(f);if(g)g.push(T);else u.set(f,[T])});for(let[c,T]of u){let f=c?c.split("\x00"):[],g=!f.includes(a);if(!f.length||g&&i.dialect==="mysql"){for(let M of T){let x=d[M],A=Object.keys(x),w=await i.insert(A.length?`INSERT INTO ${t.table} (${A.join(", ")}) VALUES (${A.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(x),a);await s[M]._markInserted(x,g?w.lastInsertId:void 0)}continue}if(i.dialect==="postgres"&&Ve(t,f,T.map((M)=>d[M]))){let M=t.table,x=f.join(", "),A=`INSERT INTO ${M} (${x}) SELECT ${x} FROM jsonb_populate_recordset(NULL::${M}, (?::text)::jsonb)`;for(let w=0;w<T.length;w+=_e){let h=T.slice(w,w+_e),K=JSON.stringify(h.map((v)=>Object.fromEntries(f.map((P)=>[P,d[v][P]??null]))),ze);if(!g){await i.run(A,[K]);for(let v of h)await s[v]._markInserted(d[v]);continue}let p=(await i.all(`${A} RETURNING ${a}`,[K])).map((v)=>v[a]),y=p.every((v)=>typeof v==="number"||typeof v==="bigint")?[...p].sort((v,P)=>v<P?-1:v>P?1:0):p;for(let v=0;v<h.length;v++)await s[h[v]]._markInserted(d[h[v]],y[v])}continue}let R=xe(Math.max(1,Math.floor(Qe/f.length)));for(let M=0;M<T.length;){let x=Math.min(R,xe(T.length-M)),A=T.slice(M,M+x);M+=x;let w=`INSERT INTO ${t.table} (${f.join(", ")}) VALUES ${A.map(()=>`(${f.map(()=>"?").join(", ")})`).join(", ")}`,h=A.flatMap((y)=>f.map((v)=>d[y][v]));if(!g){await i.run(w,h);for(let y of A)await s[y]._markInserted(d[y]);continue}let K=(await i.all(`${w} RETURNING ${a}`,h)).map((y)=>y[a]),p=K.every((y)=>typeof y==="number"||typeof y==="bigint")?[...K].sort((y,v)=>y<v?-1:y>v?1:0):K;for(let y=0;y<A.length;y++)await s[A[y]]._markInserted(d[A[y]],p[y])}}return s},async updateOrCreate(o,s){let i=new E(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);let a=await i.first();if(a)return await a.update(s),a;return this.create({...o,...s})},async firstOrCreate(o,s){let i=new E(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);return await i.first()||this.create({...o,...s})},async update(o,s){let i=await r.findOrFail(o);return await i.update(s),i},async delete(o){let s=await r.find(o);return s?s.delete():!1},destroy(o){return r.delete(o)},async forceDelete(o){let s=await r.withTrashed().find(o);return s?s.forceDelete():!1},remove(o){return r.forceDelete(o)},async truncate(){await S().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(o={}){return new I(t,o,!1)},latest:(o="created_at")=>new E(t).orderByDesc(o),oldest:(o="created_at")=>new E(t).orderBy(o,"asc"),max:(o)=>new E(t).max(o),min:(o)=>new E(t).min(o),avg:(o)=>new E(t).avg(o),sum:(o)=>new E(t).sum(o),pluck(o){return new E(t).pluck(o)}};return new Proxy(r,{get(o,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let i=s.slice(5),a=i.charAt(0).toLowerCase()+i.slice(1);if(a in t.attributes||a==="id"||a===t.primaryKey)return(d)=>new E(t).where(a,d)}return Reflect.get(o,s)}})}function Kt(t){let r=tt(t);if(t?.name)qe(t.name,r);return r}async function jn(t){let r=S(),o=C(t.primaryKey||"id"),s=[],i=new Set([o]);if(s.push(t.autoIncrement!==!1?`${o} INTEGER PRIMARY KEY AUTOINCREMENT`:`${o} INTEGER PRIMARY KEY`),t.traits?.useUuid)s.push("uuid TEXT UNIQUE"),i.add("uuid");for(let[a,d]of Object.entries(t.attributes)){let u=C(a);if(i.has(u))continue;i.add(u);let c=De(d.type),T=Pe(c);if(u.endsWith("_id")&&(c===void 0||N(c)))T="INTEGER";let f=`${u} ${T}`;if(d.unique)f+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let g=d.foreignKey;if(f+=` REFERENCES ${g.table}(${g.column??"id"})`,g.onDelete)f+=` ON DELETE ${g.onDelete.toUpperCase()}`;if(g.onUpdate)f+=` ON UPDATE ${g.onUpdate.toUpperCase()}`}s.push(f)}for(let a of O(t.belongsTo)){let d=a.foreignKey??`${C(a.model)}_id`;if(i.has(d))continue;i.add(d),s.push(`${d} INTEGER`)}if(Z(t))for(let a of["created_at","updated_at"]){if(i.has(a))continue;i.add(a),s.push(`${a} TEXT`)}if(ee(t)&&!i.has("deleted_at"))i.add("deleted_at"),s.push("deleted_at TEXT");await r.run(`CREATE TABLE IF NOT EXISTS ${t.table} (${s.join(", ")})`,[])}async function qn(t,r,o){let s=S(),i=t.traits?.useSeeder,a=r??(typeof i==="object"&&i?i.count:10);if(!o)try{let d=await import("./chunk-r2ta1rnj.js");o=Pt(d.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let d=0;d<a;d++){let u={};for(let[T,f]of Object.entries(t.attributes))if(f.factory)u[C(T)]=f.factory(o);if(Z(t)){let T=Y();u.created_at=T,u.updated_at=T}if(t.traits?.useUuid)u.uuid=crypto.randomUUID();let c=Object.keys(u);await s.run(`INSERT INTO ${t.table} (${c.join(", ")}) VALUES (${c.map(()=>"?").join(", ")})`,Object.values(u))}}var oe=new Map;function rn(t){return oe.get(t)}function sn(){return[...oe.values()]}function an(){return Object.fromEntries(oe)}function on(t){return oe.has(t)}function ln(){oe.clear(),Bt()}function Ft(t,r){return oe.set(t,r),r}function nt(){return typeof window<"u"&&typeof document<"u"}function cn(t){let r;if(nt())r=We(t);else{let o=Kt(t);r=Object.assign(o,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return Ft(t.name,r),r}function un(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
|
|
3
3
|
export{N,Pe,Pt,Be,O,Bt,_t,It,Ln,Kn,Fn,Lt,Kt,jn,qn,rn,sn,an,on,ln,Ft,cn,un};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{n,e,t,s,_e,b,r,m,Ht,D,l,X,je,qe}from"./chunk-bpwg9p8b.js";import{Buffer as St}from"buffer";import{serialize as Mt}from"v8";function vt(p){return m(e.relations?.singularizeStrategy)(p)}function E(p,B,w,j={}){let re=j.singularize??vt,oe=p.relations?.[B]?.belongsToMany?.[w];if(oe==null)return null;let Ee=typeof oe==="object",pe=Ee?oe:null,be=Ee?pe.model:oe,He=p.modelToTable[be]||be,Ve,et;if(pe?.table)Ve=pe.table;else if(pe?.through){if(et=pe.through,Ve=p.modelToTable[pe.through],!Ve)throw Error(`[query-builder] belongsToMany relation '${w}' on '${B}' references unknown through model '${pe.through}'. Make sure '${pe.through}' is registered via defineModels({...}).`)}else{let Je=re(B),h=re(He);Ve=[Je,h].sort().join("_")}let tt=pe?.foreignKey??`${re(B)}_id`,ct=pe?.relatedKey??`${re(He)}_id`,ne={};if(pe?.pivot?.columns)Object.assign(ne,pe.pivot.columns);if(et&&j.models){let Je=j.models[et],h=Je?.definition??Je?.getDefinition?.()??Je,g=h?.attributes??{};for(let[d,y]of Object.entries(g)){if(d===tt||d===ct||d===(h?.primaryKey??"id"))continue;ne[d]={default:y?.default,nullable:y?.nullable,validation:y?.validation}}}let Qe=Boolean(pe?.pivot?.timestamps),xe=Object.keys(ne);return{pivotTable:Ve,fkParent:tt,fkRelated:ct,pivotColumns:xe,pivotColumnDefs:ne,pivotModelName:et,timestamps:Qe,relatedModelName:be,relatedTable:He,hasConfig:Ee}}function*In(p,B={}){let w=p.relations;if(!w)return;for(let[j,re]of Object.entries(w)){let N=re?.belongsToMany;if(!N)continue;for(let oe of Object.keys(N)){let Ee=E(p,j,oe,B);if(Ee)yield{parentTable:j,relationKey:oe,resolved:Ee}}}}function Fe(p){return typeof p==="object"&&p!==null&&"raw"in p&&typeof p.raw==="string"}function pt(p,B,w){if(Array.isArray(B)){let re=s(B.length,w.length+1),N=l(p,B,!1,re);return w.push(...B),N}let j=`${p} = ${t(w.length+1)}`;return w.push(B),j}function Ge(p){return typeof p==="object"&&p!==null&&"sql"in p&&typeof p.sql==="string"&&(!("parameters"in p)||Array.isArray(p.parameters))}function Wt(p,B){let[w,...j]=B;if(j.length>0||w!==void 0&&!Array.isArray(w))throw TypeError("[query-builder] db.raw(sql, bindings): pass the bindings as one array, db.raw('a = ? AND b = ?', [a, b]).");let re={sql:p,parameters:[...w??[]]};return Object.defineProperty(re,"then",{enumerable:!1,value:(N,oe)=>{let Ee=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 oe==="function")return oe(Ee);throw Ee}}),re}function it(p){return p instanceof Promise&&typeof p.execute==="function"&&typeof p.cancel==="function"}function lt(p){throw TypeError(`[query-builder] ${p}: 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 Ye(p,B){let w=p.parameters??(Array.isArray(p.values)?p.values:[]);if(e.dialect!=="postgres"||w.length===0)return{text:p.sql,parameters:w};let j=0,{text:re}=je(p.sql,()=>j<w.length?t(B+j++):void 0);if(j!==w.length)throw TypeError(`[query-builder] SQL expression declares ${w.length} parameters but contains only ${j} placeholders`);return{text:re,parameters:w}}function kt(p,B){if(B.length===2){let[w,j]=B;if(Array.isArray(j)&&typeof w==="number"&&j[w]===p)return!1;if(j instanceof Set&&w===p&&j.has(p))return!1;if(j instanceof Map&&j.get(w)===p)return!1}return B.some((w)=>w!==void 0&&!(Array.isArray(w)&&w.length===0))}function en(p,...B){if(typeof p==="string"){if(!(B.length===1&&Number.isInteger(B[0])&&B[0]>=0&&!p.includes("?"))&&kt(p,B))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:p}}let w=p[0];for(let j=0;j<B.length;j++)w+=Ke(B[j])+p[j+1];return{raw:w}}function De(p){return n(e.dialect)?`\`${p.replace(/`/g,"``")}\``:`"${p.replace(/"/g,'""')}"`}function ft(p,B=1){let w=Object.keys(p[0]??{}),j=[],re=B,N=p.map((oe)=>`(${w.map((pe)=>(j.push(oe[pe]),t(re++))).join(", ")})`);return{colsSql:w.map(De).join(", "),valuesSql:N.join(", "),params:j,nextIndex:re}}function ut(p){return Boolean(p&&(p.onSlowQuery||p.slowQueryThresholdMs!=null&&p.slowQueryThresholdMs>=0))}function c(p,B=e.dialect){if(!n(B))return p;let w=/^([A-Z_][\w$]*)(?:\.([A-Z_][\w$]*))?(?:\s+as\s+([A-Z_][\w$]*))?$/i.exec(p.trim());if(!w)return p;let[,j,re,N]=w,oe=re?`\`${j}\`.\`${re}\``:`\`${j}\``;return N?`${oe} AS \`${N}\``:oe}function Ct(p,B=e.dialect){if(!n(B)||p===null||p===void 0)return p;if(typeof p==="string"){let w=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(p);if(!w)return p;let[,j,re]=w;return`${j} ${re.length===5?`${re}:00`:re}`}if(!(p instanceof Date)||Number.isNaN(p.getTime()))return p;return p.toISOString().replace("T"," ").replace(/\.\d+Z$/,"")}function $t(p){if(typeof p==="string")return c(p);if(Fe(p))return p.raw;if(p&&typeof p==="object"){let B=p;if(typeof B.raw==="function")return String(B.raw());if(typeof B.sql==="string")return B.sql;let w=String(p);if(w!=="[object Object]")return w}throw TypeError(`[query-builder] select(): unsupported column ${String(p)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function Ft(p){let B=/\(|\)|\bORDER\s+BY\b/gi,w=0,j;while(j=B.exec(p))if(j[0]==="(")w++;else if(j[0]===")")w=Math.max(0,w-1);else if(w===0)return!0;return!1}var ye={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},Bt=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function F(p,B){if(!ye.IDENTIFIER.test(p)){let w=B?` in ${B}`:"";throw Error(`[query-builder] Invalid identifier${w}: '${p}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function $e(p,B){if(typeof p!=="string")throw TypeError(`[query-builder] ${B}: operator must be a string, got ${typeof p}`);let w=p.toLowerCase();if(!Bt.has(w))throw TypeError(`[query-builder] ${B}: refusing to use '${p}' as a SQL operator \u2014 not in the allowed set (${[...Bt].join(", ")})`);return p}function Ue(p,B,w,j){let re=B.toLowerCase();if(re!=="is"&&re!=="is not")return null;if(w!==null&&w!==void 0)throw TypeError(`[query-builder] ${j}: operator '${B}' only accepts NULL/undefined as value, got ${typeof w} (${String(w)})`);return`${p} IS ${re==="is not"?"NOT ":""}NULL`}function Pe(p,B){if(typeof p!=="string"||p.length===0)throw TypeError(`[query-builder] ${B}: identifier must be a non-empty string, got ${typeof p}`);if(p.length>129)throw TypeError(`[query-builder] ${B}: identifier '${p}' too long`);let w=p.split(".");if(w.length>2)throw TypeError(`[query-builder] ${B}: identifier '${p}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let j of w)if(!/^[A-Z_][A-Z0-9_]*$/i.test(j))throw TypeError(`[query-builder] ${B}: identifier segment '${j}' contains characters outside [A-Za-z0-9_]`)}function ze(p,B,w=[]){let j=typeof p==="object"&&p!==null?p.parameters??p.values:void 0;if(kt(p,w)||Array.isArray(j)&&j.length>0){let re=B.startsWith("whereRaw(")?", or use where(). Model.query().whereRaw(sql, ...bindings) is the builder that binds `?` values.":B.startsWith("orWhereRaw(")?", or use orWhere(). Model.query().orWhereRaw(sql, ...bindings) is the builder that binds `?` values.":".";throw TypeError(`[query-builder] ${B}: 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${re}`)}if(typeof p==="string")return Kt(B),p;if(p===null||p===void 0)throw TypeError(`[query-builder] ${B}: fragment must be a SqlFragment, got ${p}`);if(Fe(p))return p.raw;if(typeof p==="object"){let re=p;if(typeof re.raw==="string")return re.raw;if(typeof re.raw==="function"){let oe=re.raw();if(typeof oe==="string")return oe}if(typeof re.sql==="string")return re.sql;let N=String(p);if(N!=="[object Object]"&&N!=="[object Promise]")return N}throw TypeError(`[query-builder] ${B}: 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 Jt(p,B){if(!B||B.length===0)return;if(e.dialect!=="postgres")return;if(/\$\d/.test(p))return;let w=X(p),j=`${B.length} binding${B.length===1?"":"s"}`,re=w>0?`the query binds them with ${w} \`?\` placeholder${w===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(): ${j} supplied, but ${re}. 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 Dt=new Set;function Kt(p){if(Dt.has(p))return;Dt.add(p),console.warn(`[query-builder] ${p}: 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 Rt(p,B=e.dialect){return n(B)?p.replace(/\\/g,"\\\\").replace(/'/g,"''"):p.replace(/'/g,"''")}function Ke(p){if(p===null)return"NULL";if(typeof p==="number"&&Number.isFinite(p))return String(p);if(typeof p==="boolean")return p?"1":"0";if(typeof p==="string")return`'${Rt(p)}'`;if(p instanceof Date)return`'${p.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof p}`)}function _t(p,B){let w=Array.isArray(p)?p:p?[p]:[],j=[];if(w.length)j.push(`PARTITION BY ${w.join(", ")}`);if(B&&B.length)j.push(`ORDER BY ${B.map(([re,N])=>`${re} ${N==="desc"?"DESC":"ASC"}`).join(", ")}`);return j.length?`OVER (${j.join(" ")})`:"OVER ()"}class Ot{cache=new Map;maxSize=100;get(p){let B=this.cache.get(p);if(!B)return null;if(Date.now()>B.expiresAt)return this.cache.delete(p),null;return this.cache.delete(p),this.cache.set(p,B),B.data}set(p,B,w){if(this.cache.has(p))this.cache.delete(p);if(this.cache.size>=this.maxSize){let j=Date.now(),re=!1;for(let[N,oe]of this.cache)if(j>oe.expiresAt){if(this.cache.delete(N),re=!0,this.cache.size<this.maxSize)break}if(!re){let N=this.cache.keys().next().value;if(N!==void 0)this.cache.delete(N)}}this.cache.set(p,{data:B,expiresAt:Date.now()+w})}clear(){this.cache.clear()}setMaxSize(p){this.maxSize=Math.max(0,Math.floor(p));while(this.cache.size>this.maxSize){let B=this.cache.keys().next().value;if(B===void 0)break;this.cache.delete(B)}}}var mt=new Ot,Et=new WeakMap,jt=0;function Ut(p,B,w){let j=Et.get(p);if(j===void 0)j=++jt,Et.set(p,j);let re=w.map((N)=>ArrayBuffer.isView(N)?["view",St.isBuffer(N)?"Buffer":Object.prototype.toString.call(N),St.from(N.buffer,N.byteOffset,N.byteLength).toString("base64")]:["value",Mt(N).toString("base64")]);return`${j}\x00${B}\x00${JSON.stringify(re)}`}function Vt(p){let B=String(p?.message||"").toLowerCase();return B.includes("deadlock")||B.includes("serialization failure")||B.includes("could not serialize access")||B.includes("deadlock found when trying to get lock")||B.includes("lock wait timeout exceeded")||B.includes("database is locked")||B.includes("busy")}function Gt(p,B){if(!B||B.length===0)return!1;let w=p&&(p.code||p.sqlState||p.sqlstate);if(!w)return!1;return B.includes(w)}function Yt(p){return new Promise((B)=>setTimeout(B,p))}var bt=new Map,zt=500,Xt=[{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}],Zt=[{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}],tn=[{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 Xe(p){let B=bt.get(p);if(B!==void 0)return B;let w=nn(p);if(bt.size>=zt)bt.clear();return bt.set(p,w),w}function nn(p){let B=qe(p,Xt);if(B.length<=1)return p;let w=p.slice(0,B[0].start).trimEnd(),j={};for(let oe=0;oe<B.length;oe++){let Ee=B[oe].start,pe=oe+1<B.length?B[oe+1].start:p.length,be=p.slice(Ee,pe).trim();if(!j[B[oe].key])j[B[oe].key]=[];j[B[oe].key].push(be)}let N=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((oe)=>j[oe]).map((oe)=>j[oe].join(" ")).join(" ");return N?`${w} ${N}`:w}function rn(p,B){let w=Math.max(1,B?.baseMs??50),j=Math.max(1,B?.factor??2),re=Math.max(w,B?.maxMs??2000),N=Math.min(re,w*j**Math.max(0,p-1));if(B?.jitter)N=Math.min(re,N*(0.9+Math.random()*0.2));return Math.floor(N)}function i(p){let B=p?.sql??b(),w=p?.meta,j=p?.schema,re;function N(h,g){let d=B.unsafe(h,g);if(typeof d.sql!=="string")re??=new WeakMap,re.set(d,{sql:h,params:g?.slice()});return d}let oe,Ee=(h,g)=>{let d=w?.temporalColumns?.[h];if(!d||d.length===0||!n(e.dialect))return g;return g.map((y)=>{let A=null;for(let f of d){if(!(f in y))continue;let Y=Ct(y[f]);if(Y!==y[f])A=A??{...y},A[f]=Y}return A??y})};function pe(h){if(typeof h==="number")return h;let g=String(h),d=7;for(let y=0;y<g.length;y++)d=d*31+g.charCodeAt(y)|0;return Math.abs(d)}function be(){if(!p?.hooks)return e.hooks;return{...e.hooks,...p.hooks}}let He=new Map;function Ve(h){if(Array.isArray(h)){let[f,Y,v]=h;F(f,"where(column)");let K=String(f);switch(Y){case"in":if(Array.isArray(v)){let q=s(v.length);return N(`${K} IN (${q})`,v)}return N(`${K} IN (${t(1)})`,[v]);case"not in":if(Array.isArray(v)){let q=s(v.length);return N(`${K} NOT IN (${q})`,v)}return N(`${K} NOT IN (${t(1)})`,[v]);case"like":return N(`${K} LIKE ${t(1)}`,[v]);case"is":case"is not":{if(v!==null&&v!==void 0)throw TypeError(`[query-builder] where(..., '${Y}', ?): operator '${Y}' only accepts NULL/undefined as value, got ${typeof v} (${String(v)})`);return N(`${K} IS ${Y==="is not"?"NOT ":""}NULL`)}case"!=":return N(`${K} <> ${t(1)}`,[v]);case"<":case">":case"<=":case">=":case"=":return N(`${K} ${Y} ${t(1)}`,[v]);default:throw TypeError(`[query-builder] where(..., '${String(Y)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in h)return h.raw;let g=Object.keys(h);if(g.length===0)return N("");let d=[],y=[],A=1;for(let f of g){F(f,"where(object key)");let Y=h[f];if(Array.isArray(Y)){let v=s(Y.length,A);d.push(`${f} IN (${v})`),y.push(...Y),A+=Y.length}else d.push(`${f} = ${t(A++)}`),y.push(Y)}return N(d.join(" AND "),y)}function et(h,g,d){if(!d)return g;let y=Ve(d);return B`${g} WHERE ${y}`}function tt(h){let g=re?.get(h);if(g)return g.sql;let d=e.debug?.captureText;if(e.debug)e.debug.captureText=!0;let y=String(h);if(e.debug)e.debug.captureText=d;return y}function ct(h){let g=re?.get(h);if(g)return g.params;if(!h||typeof h!=="object")return;if(Array.isArray(h.values))return h.values;if(Array.isArray(h.parameters))return h.parameters;if(Array.isArray(h.params))return h.params;return}function ne(h,g,d){let y=be(),A=y?.slowQueryThresholdMs,f=A!=null&&A>=0,Y=Boolean(y?.onSlowQuery||f),v=y&&(y.onQueryStart||y.onQueryEnd||y.onQueryError||y.startSpan||Y),K=d?.timeoutMs&&d.timeoutMs>0||d?.signal;if(!v&&!K)return h.execute();let q=tt(h),R=ct(h),J=Date.now(),k;try{if(y?.onQueryStart?.({sql:q,params:R,kind:g}),y?.startSpan)k=y.startSpan({sql:q,params:R,kind:g})}catch{}let I=!1,U=(V,ee,M=Boolean(V))=>{if(I)return;I=!0;let H=Date.now()-J;try{if(M)y?.onQueryError?.({sql:q,params:R,error:V,durationMs:H,kind:g});else if(y?.onQueryEnd?.({sql:q,params:R,durationMs:H,rowCount:ee,kind:g}),f&&H>=A)if(y?.onSlowQuery)y.onSlowQuery({sql:q,params:R,durationMs:H,kind:g});else console.warn(`[query-builder] slow query (${H}ms >= ${A}ms): ${q}`)}catch{}try{k?.end(V)}catch{}};if(typeof h.executeSync==="function"){let V,ee,M=!1;try{V=h.executeSync()}catch(te){ee=te,M=!0}if(d?.signal?.aborted){try{h.cancel?.()}catch{}ee=Object.assign(Error("Query aborted"),{code:"EBQBABORT"}),M=!0}if(M)return U(ee,void 0,!0),Promise.reject(ee);let H=Array.isArray(V)?V.length:typeof V==="number"?V:void 0;return U(void 0,H),Promise.resolve(V)}let W=h.execute(),_=[W],G;if(d?.timeoutMs&&d.timeoutMs>0){let V=new Promise((ee,M)=>{G=setTimeout(()=>{try{h.cancel?.()}catch{}let H=Error(`Query timed out after ${d.timeoutMs}ms`);H.code="EBQBTIMEOUT",M(H)},d.timeoutMs)});_.push(V)}if(d?.signal){if(d.signal.aborted){try{h.cancel?.()}catch{}let ee=Error("Query aborted");return ee.code="EBQBABORT",U(ee),Promise.reject(ee)}let V=()=>{try{h.cancel?.()}catch{}};d.signal.addEventListener("abort",V,{once:!0}),W.finally(()=>{d.signal?.removeEventListener("abort",V)})}return Promise.race(_).then((V)=>{clearTimeout(G);let ee=Array.isArray(V)?V.length:typeof V==="number"?V:void 0;return U(void 0,ee),V}).catch((V)=>{throw clearTimeout(G),U(V),V})}function Qe(h){if(typeof h==="number")return Number.isFinite(h)?h:0;if(typeof h==="bigint")return Number(h);if(!h||typeof h!=="object")return 0;let g=h;for(let d of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(g[d]!==void 0&&g[d]!==null)return Qe(g[d]);if(Array.isArray(h))return h.reduce((d,y)=>d+Qe(y),0);return 0}function xe(h,g){let d=g??tt(h);return{sql:d,toString:()=>d,execute:()=>h.execute(),values:()=>h.values(),raw:()=>h.raw()}}function Je(h,g){let d=B,y=g&&g.length>0?`SELECT ${g.join(", ")} FROM ${String(h)}`:`SELECT * FROM ${String(h)}`,A=[],f=[],Y=!1,v=!1,K=!1,q=null,R=()=>{if(q===null){let a=Xe(W());q=f.length>0?N(a,f):N(a)}return q},J=(a="",o="",u=[])=>N(`${a}${Xe(W())}${o}`,[...f,...u]),k=(a,o)=>{A.push({conn:a,sql:o}),q=null},I=(a,o)=>{k(a==="OR"?"OR":"AND",o)},U=(a)=>{let o=qe(a,Zt,1);return o.length>0?o[0].start:-1},W=(a)=>{let o=D(a?[...A,a]:A);if(!o)return y;if(Y)return`${y} ${v?"AND":"WHERE"} ${o}`;let u=U(y);return u>=0?`${y.slice(0,u)}WHERE ${o} ${y.slice(u)}`:`${y} WHERE ${o}`},_=(a,o,u,T)=>{let S=typeof u?.__sqlState==="function"?u.__sqlState():void 0,O;if(S){let C=f.length;O=C>0&&e.dialect==="postgres"?S.sql.replace(/\$(\d+)/g,(L,Q)=>`$${Number(Q)+C}`):S.sql,f.push(...S.params)}else O=String(u.toSQL());k(a,`${o} ${T?"NOT IN":"IN"} (${O})`)},G=(a,o)=>{let u=Je(h);o(u);let T=u.__whereState?.();if(!T||!T.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let S=f.length,O=S>0&&e.dialect==="postgres"?T.body.replace(/\$(\d+)/g,(C,L)=>`$${Number(L)+S}`):T.body;f.push(...T.params),k(a,`(${O})`)},V=(a,o,u,T,S,O)=>{if(typeof T==="string"&&S!==void 0){F(String(T),`${u}(column)`),$e(S,`${u}(operator)`);let C=Ue(String(T),String(S),O,u);if(C)return k(o,C),a;let L=f.length+1;return f.push(O),k(o,`${String(T)} ${String(S)} ${t(L)}`),a}if(Array.isArray(T)){let[C,L,Q]=T,x=String(C);F(x,`${u}(column)`);let P=$e(L,`${u}(operator)`);if(P==="in"||P==="not in"){let z=Array.isArray(Q)?Q:[Q],ae=s(z.length,f.length+1),we=l(c(x),z,P==="not in",ae);f.push(...z),k(o,we)}else{let z=Ue(x,P,Q,u);if(z)return k(o,z),a;let ae=f.length+1;f.push(Q),k(o,`${x} ${P} ${t(ae)}`)}return a}if(typeof T==="function")return G(o,T),a;if(it(T))lt(`${u}(expr)`);if(Ge(T)){let C=Ye(T,f.length+1);return f.push(...C.parameters),k(o,C.text),a}if(T&&typeof T==="object"&&!("raw"in T)){let C=[];for(let L of Object.keys(T)){F(L,`${u}(column)`);let Q=T[L];if(Array.isArray(Q)){let x=s(Q.length,f.length+1);C.push(l(c(L),Q,!1,x)),f.push(...Q)}else{let x=f.length+1;C.push(`${L} = ${t(x)}`),f.push(Q)}}if(C.length>0)k(o,C.length>1?`(${C.join(" AND ")})`:C[0]);return a}if(T&&typeof T.raw<"u")return k(o,T.raw),a;return a},ee=(a,o)=>{if(A.length>0)y=W(),A.length=0;Y=!0;let u=o.__rawState?.();if(u){let T=f.length,S=e.dialect==="postgres"?u.sql.replace(/\$(\d+)/g,(O,C)=>`$${Number(C)+T}`):u.sql;y+=` ${a} ${S}`,f.push(...u.params),v=o.__hasPredicate?.()??ye.WHERE.test(S)}else{let T=String(o.toSQL());y+=` ${a} ${T}`,v=o.__hasPredicate?.()??ye.WHERE.test(T)}q=null},M=(a)=>{let o=qe(y,tn,1),u=o.length>0?o[0].start:-1;y=u>=0?`${y.slice(0,u)}${a} ${y.slice(u)}`:`${y} ${a}`,q=null},H=new Set,te,Z,ce=!1,me=!1,Ie=!1,Le=new Map,ve=new Set,dt=60000,he=(a)=>m(e.relations.singularizeStrategy)(a),Ce=(a)=>{if(!w)return null;return E(w,String(h),a,{singularize:he,models:w.models})},nt=(a)=>{if(!a||typeof a!=="object"||ve.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},rt=(a)=>{if(ve.size===0||!a)return a;if(Array.isArray(a))for(let o=0;o<a.length;o++)nt(a[o]);else nt(a);return a},st=(a)=>{if(!w)return;if(H.has(a.pivotTable))return;let o=String(h),u=w.primaryKeys[o]??"id";F(a.pivotTable,"wherePivot auto-join (pivot table)"),F(a.fkParent,"wherePivot auto-join (parent FK)"),F(o,"wherePivot auto-join (parent table)"),F(u,"wherePivot auto-join (parent PK)"),q=d`${R()} 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}`,H.add(a.pivotTable)},at=(a)=>{if(ye.SELECT_STAR.test(y))y=y.replace(ye.SELECT_STAR,`SELECT *, ${a}`);else if(ye.SELECT.test(y))y=y.replace(ye.SELECT_FROM,`SELECT $1, ${a} FROM`);let o=String(R());if(ye.SELECT_STAR.test(o)){let u=o.replace(ye.SELECT_STAR,`SELECT *, ${a}`);q=N(u)}else if(ye.SELECT.test(o)){if(ye.SELECT_FROM.exec(o)){let T=o.replace(ye.SELECT_FROM,`SELECT $1, ${a} FROM`);q=N(T)}}},Me=(a,o,u,T)=>{at(`${a} ${_t(u,T)} AS ${o}`)},yt=(a,o,u,T)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)");let S=`${a.endsWith("s")?a.slice(0,-1):a}_id`;F(S,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${o} WHERE ${o}.${S} = ${a}.${u}`;if(T){let L=T({where:(Q,x,P)=>(F(Q,"relationship subquery condition"),`${o}.${Q} ${$e(x,"whereHas callback")} ${Ke(P)}`)});if(L)O+=` AND ${L}`}return O},Tt=(a,o,u,T)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)");let S=`${o.endsWith("s")?o.slice(0,-1):o}_id`;F(S,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${o} WHERE ${o}.${u} = ${a}.${S}`;if(T){let L=T({where:(Q,x,P)=>(F(Q,"relationship subquery condition"),`${o}.${Q} ${$e(x,"whereHas callback")} ${Ke(P)}`)});if(L)O+=` AND ${L}`}return O},ht=(a,o,u,T,S,O)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)"),F(T,"relationship subquery (target primary key)");let C=O&&w?E(w,a,O,{singularize:he,models:w.models}):null,L=he(a),Q=he(o),x=C?.pivotTable??[L,Q].sort().join("_"),P=C?.fkParent??`${L}_id`,z=C?.fkRelated??`${Q}_id`;F(x,"relationship subquery (pivot table)"),F(P,"relationship subquery (foreign key A)"),F(z,"relationship subquery (foreign key B)");let ae=`SELECT 1 FROM ${x} JOIN ${o} ON ${o}.${T} = ${x}.${z} WHERE ${x}.${P} = ${a}.${u}`;if(S){let se=S({where:(Se,ke,Oe)=>(F(Se,"relationship subquery condition"),`${o}.${Se} ${$e(ke,"whereHas callback")} ${Ke(Oe)}`)});if(se)ae+=` AND ${se}`}return ae},Nt=(a,o,u)=>{F(a,"withCount (parent table)"),F(o,"withCount (target table)"),F(u,"withCount (primary key)");let T=`${a.endsWith("s")?a.slice(0,-1):a}_id`;return F(T,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${o} WHERE ${o}.${T} = ${a}.${u})`},At=(a,o,u,T)=>{F(a,"withCount (parent table)"),F(o,"withCount (target table)"),F(u,"withCount (primary key)");let S=T&&w?E(w,a,T,{singularize:he,models:w.models}):null,O=he(a),C=he(o),L=S?.pivotTable??[O,C].sort().join("_"),Q=S?.fkParent??`${O}_id`;return F(L,"withCount (pivot table)"),F(Q,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${L} WHERE ${L}.${Q} = ${a}.${u})`},gt=(a,o,u)=>{if(!w)return;F(u,`with${a[0]}${a.slice(1).toLowerCase()} (column)`);let T=String(h),S=w.relations?.[T];if(!S)return;let O=Object.entries(S).find(([se,Se])=>Se&&typeof Se==="object"&&(o in Se));if(!O)return;let[C,L]=O,Q=L[o],x=typeof Q==="string"?Q:Q?.model||Q?.target||Q,P=w.modelToTable[x]||x,z=w.primaryKeys[T]??"id";F(P,`with${a} (target table)`);let ae=`${a}(${P}.${u})`,we;if(C==="hasMany"||C==="hasOne"){let se=`${T.endsWith("s")?T.slice(0,-1):T}_id`;F(se,`with${a} (foreign key)`),we=`(SELECT ${ae} FROM ${P} WHERE ${P}.${se} = ${T}.${z})`}else if(C==="belongsToMany"){let se=w?E(w,T,o,{singularize:he,models:w.models}):null,Se=he(T),ke=he(P),Oe=se?.pivotTable??[Se,ke].sort().join("_"),Be=se?.fkParent??`${Se}_id`,ie=se?.fkRelated??`${ke}_id`,ot=w.primaryKeys[P]??"id";F(Oe,`with${a} (pivot table)`),F(Be,`with${a} (foreign key)`),F(ie,`with${a} (related key)`),we=`(SELECT ${ae} FROM ${Oe} JOIN ${P} ON ${P}.${ot} = ${Oe}.${ie} WHERE ${Oe}.${Be} = ${T}.${z})`}else return;at(`${we} AS ${o}_${a.toLowerCase()}_${u}`)},wt=()=>{if(Le.size===0)return;let a=[];for(let[o,u]of Le.entries()){let T=Ce(o);if(!T)continue;for(let O of u)F(O,"withPivot");let S=u.map((O)=>`${T.pivotTable}.${O} AS pivot_${O}`);a.push(...S)}if(a.length>0){let o=a.join(", ");at(o)}};return new Proxy({distinct(){return y=y.replace(/^SELECT\s+/i,"SELECT DISTINCT "),q=null,this},distinctOn(...a){let o=a.map(String).join(", ");return y=y.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${o}) `),q=null,this},selectRaw(a,...o){let u=ze(a,"selectRaw(fragment)",o),T=y.indexOf(" FROM ");if(T!==-1)y=`${y.substring(0,T)}, ${u}${y.substring(T)}`;else y+=`, ${u}`;return q=null,this},rowNumber(a="row_number",o,u){let T=[];if(o){let L=Array.isArray(o)?o:[o];T.push(`PARTITION BY ${L.join(", ")}`)}if(u&&u.length)T.push(`ORDER BY ${u.map(([L,Q])=>`${L} ${Q==="desc"?"DESC":"ASC"}`).join(", ")}`);let O=`ROW_NUMBER() ${T.length?`OVER (${T.join(" ")})`:"OVER ()"} AS ${a}`,C=y.indexOf(" FROM ");if(C!==-1)y=`${y.substring(0,C)}, ${O}${y.substring(C)}`;else y+=`, ${O}`;return q=null,this},denseRank(a="dense_rank",o,u){let T=Array.isArray(o)?o:o?[o]:[],S=[];if(T.length)S.push(`PARTITION BY ${T.join(", ")}`);if(u&&u.length)S.push(`ORDER BY ${u.map(([Q,x])=>`${Q} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let C=`DENSE_RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${a}`,L=y.indexOf(" FROM ");if(L!==-1)y=`${y.substring(0,L)}, ${C}${y.substring(L)}`;else y+=`, ${C}`;return q=null,this},rank(a="rank",o,u){let T=Array.isArray(o)?o:o?[o]:[],S=[];if(T.length)S.push(`PARTITION BY ${T.join(", ")}`);if(u&&u.length)S.push(`ORDER BY ${u.map(([Q,x])=>`${Q} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let C=`RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${a}`,L=y.indexOf(" FROM ");if(L!==-1)y=`${y.substring(0,L)}, ${C}${y.substring(L)}`;else y+=`, ${C}`;return q=null,this},over(a,o,u={}){return Me(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 Me(`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 Me(`LEAD(${u.join(", ")})`,o.alias??`${a}_lead`,o.partitionBy,o.orderBy),this},sumOver(a,o={}){return Me(`SUM(${a})`,o.alias??`${a}_sum`,o.partitionBy,o.orderBy),this},avgOver(a,o={}){return Me(`AVG(${a})`,o.alias??`${a}_avg`,o.partitionBy,o.orderBy),this},countOver(a="*",o={}){return Me(`COUNT(${a})`,o.alias??"count_over",o.partitionBy,o.orderBy),this},minOver(a,o={}){return Me(`MIN(${a})`,o.alias??`${a}_min`,o.partitionBy,o.orderBy),this},maxOver(a,o={}){return Me(`MAX(${a})`,o.alias??`${a}_max`,o.partitionBy,o.orderBy),this},firstValue(a,o={}){return Me(`FIRST_VALUE(${a})`,o.alias??`${a}_first`,o.partitionBy,o.orderBy),this},lastValue(a,o={}){return Me(`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($t),T=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(y),S=T?T[1]:"",O=y.indexOf(" FROM ");if(O!==-1)y=`SELECT ${S}${u.join(", ")}${y.substring(O)}`;else y=`SELECT ${S}${u.join(", ")} FROM ${h}`;return q=null,this},addSelect(...a){if(!a.length)return this;let o=a.map($t),u=y.indexOf(" FROM ");if(u!==-1)y=`${y.substring(0,u)}, ${o.join(", ")}${y.substring(u)}`;else y+=`, ${o.join(", ")}`;return q=null,this},with(...a){if(!w||!a||a.length===0)return this;let o=[];for(let x of a){if(!x)continue;if(typeof x==="string")o.push({name:x});else if(typeof x==="object"&&!Array.isArray(x))for(let[P,z]of Object.entries(x))if(typeof z==="function")o.push({name:P,callback:z});else o.push({name:P})}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 T=String(h),S=new Set,O=new Set,C=new Map,L=(x)=>{let P=w.relations?.[x];if(!P)return[];return[...Object.keys(P.hasOne||{}),...Object.keys(P.hasMany||{}),...Object.keys(P.belongsTo||{}),...Object.keys(P.belongsToMany||{}),...Object.keys(P.hasOneThrough||{}),...Object.keys(P.hasManyThrough||{}),...Object.keys(P.morphOne||{}),...Object.keys(P.morphMany||{}),...Object.keys(P.morphToMany||{}),...Object.keys(P.morphedByMany||{})]},Q=(x,P,z=0,ae)=>{let we=e.relations.maxDepth??10;if(z>=we)throw Error(`[query-builder] Maximum relationship depth (${we}) exceeded at '${P}'. Consider using separate queries or increasing maxDepth.`);let se=w.relations?.[x];if(!se)return x;let Se=(le)=>{if(e.softDeletes?.enabled&&e.softDeletes?.defaultFilter){let ue=e.softDeletes.column||"deleted_at";return` AND ${le}.${ue} IS NULL`}return""},ke=(le)=>{if(!ae)return"";let ue=[],ge=(de,Ne,We)=>{F(String(de),"with() constraint column");let Ze=$e(Ne,"with() constraint operator");ue.push(`${le}.${String(de)} ${Ze} ${Ke(We)}`)},Te=(de)=>()=>{throw Error(`[query-builder] with('${P}', ...): ${de} 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.)`)},fe={where:(de,Ne,We)=>{if(Array.isArray(de))ge(de[0],de[1],de[2]);else if(de&&typeof de==="object")for(let Ze of Object.keys(de))ge(Ze,"=",de[Ze]);else if(Ne!==void 0&&We!==void 0)ge(de,Ne,We);else if(Ne!==void 0)ge(de,"=",Ne);return fe},whereIn:(de,Ne)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IN (${Ne.map(Ke).join(", ")})`),fe),whereNull:(de)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IS NULL`),fe),whereNotNull:(de)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IS NOT NULL`),fe),orderBy:Te("orderBy()"),limit:Te("limit()"),offset:Te("offset()"),take:Te("take()")};return ae(fe),ue.length?` AND ${ue.join(" AND ")}`:""},Oe=()=>{let le=(Te)=>{let fe=Te?.[P];return fe?w.modelToTable[fe]:void 0},ue=(Te)=>{let fe=Te?.[P],de=typeof fe==="string"?fe:fe?.model;return de?w.modelToTable[de]:void 0},ge=(Te)=>{let fe=Te?.[P];return fe?.target?w.modelToTable[fe.target]:void 0};return le(se?.hasOne)||le(se?.hasMany)||le(se?.belongsTo)||ue(se?.belongsToMany)||ge(se?.hasOneThrough)||ge(se?.hasManyThrough)||le(se?.morphOne)||le(se?.morphMany)||le(se?.morphToMany)||le(se?.morphedByMany)},Be=Oe()??(w.modelToTable[P]||w.tableToModel[P]?w.modelToTable[P]??P:P),ie=String(Be);if(!Be||!Oe()&&!w.modelToTable[P]&&!w.tableToModel[P]){let le=L(x);if(le.length>0&&!le.includes(P)){let ue=` Available relationships: ${le.join(", ")}`;throw Error(`[query-builder] Relationship '${P}' not found on table '${x}'.${ue}`)}}if(e.relations.detectCycles!==!1){let le=`${x}->${ie}`;if(S.has(le))throw Error(`[query-builder] Circular relationship detected: ${le}. This would cause an infinite loop.`);S.add(le)}if(!ie||ie===x)return x;let ot=se?.hasOneThrough?.[P]||se?.hasManyThrough?.[P];if(ot){let{through:le,target:ue}=ot,ge=w.modelToTable[le]||le,Te=w.modelToTable[ue]||ue,fe=w.primaryKeys[x]??"id",de=w.primaryKeys[ge]??"id",Ne=`${he(x)}_id`,We=`${he(ge)}_id`;return M(`LEFT JOIN ${ge} ON ${ge}.${Ne} = ${x}.${fe} LEFT JOIN ${Te} ON ${Te}.${We} = ${ge}.${de}`),H.add(ge),H.add(Te),Te}if(Boolean(se?.belongsToMany?.[P])){let le=E(w,x,P,{singularize:he,models:w.models}),ue=le?.pivotTable??[he(x),he(ie)].sort().join("_"),ge=w.primaryKeys[x]??"id",Te=w.primaryKeys[ie]??"id",fe=le?.fkParent??`${he(x)}_id`,de=le?.fkRelated??`${he(ie)}_id`;return M(`LEFT JOIN ${ue} ON ${ue}.${fe} = ${x}.${ge} LEFT JOIN ${ie} ON ${ie}.${Te} = ${ue}.${de}${ke(ie)}`),H.add(ue),H.add(ie),ie}if(Boolean(se?.morphToMany?.[P])){let le=P,ue=`${he(ie)}_${le}`,ge=w.primaryKeys[x]??"id",Te=w.primaryKeys[ie]??"id",fe=`${le}_type`,de=`${le}_id`,Ne=`${he(ie)}_id`,We=Ke(w.tableToModel[x]||x);return M(`LEFT JOIN ${ue} ON ${ue}.${de} = ${x}.${ge} AND ${ue}.${fe} = ${We} LEFT JOIN ${ie} ON ${ie}.${Te} = ${ue}.${Ne}`),H.add(ue),H.add(ie),ie}if(Boolean(se?.morphedByMany?.[P])){let le=se.morphedByMany?.[P]||P,ue=w.modelToTable[le]||le,ge=he(x),Te=`${he(ue)}_${ge}`,fe=w.primaryKeys[x]??"id",de=w.primaryKeys[ue]??"id",Ne=`${ge}_type`,We=`${ge}_id`,Ze=`${he(ue)}_id`,Qt=Ke(w.tableToModel[ue]||ue);return M(`LEFT JOIN ${Te} ON ${Te}.${Ze} = ${x}.${fe} LEFT JOIN ${ue} ON ${ue}.${de} = ${Te}.${We} AND ${Te}.${Ne} = ${Qt}`),H.add(Te),H.add(ue),ue}if(Boolean(se?.belongsTo?.[P])){let le=`${he(ie)}_id`,ue=w.primaryKeys[ie]??"id";return M(`LEFT JOIN ${ie} ON ${x}.${le} = ${ie}.${ue}${ke(ie)}`),H.add(ie),ie}let It=Boolean(se?.morphOne?.[P]),xt=Boolean(se?.morphMany?.[P]);if(It||xt){let le=`${P}_type`,ue=`${P}_id`,ge=w.primaryKeys[x]??"id",Te=Ke(w.tableToModel[x]||x);return M(`LEFT JOIN ${ie} ON ${ie}.${ue} = ${x}.${ge} AND ${ie}.${le} = ${Te}`),H.add(ie),ie}let Lt=`${he(x)}_id`,Pt=w.primaryKeys[x]??"id",qt=`${Se(ie)}${ke(ie)}`;return M(`LEFT JOIN ${ie} ON ${ie}.${Lt} = ${x}.${Pt}${qt}`),H.add(ie),ie};for(let x of o){let P=x.name.trim();if(x.callback)C.set(P,x.callback);let z=P.split("."),ae=T,we=0;for(let se of z){if(!se||se.trim().length===0)continue;let Se=se.trim(),ke=C.get(Se);ae=Q(ae,Se,we,ke)||ae,we++}O.add(P)}if(Le.size>0){let x=[];for(let[P,z]of Le.entries()){let ae=Ce(P);if(!ae)continue;let we=z.map((se)=>`${ae.pivotTable}.${se} AS pivot_${se}`);x.push(...we)}if(x.length>0){let P=x.join(", ");at(P)}}return q=null,this},whereHas(a,o){if(!w)return this;let u=String(h),T=w.relations?.[u];if(!T)throw Error(`[query-builder] No relationships defined for table '${u}'`);let S=Object.entries(T).find(([z,ae])=>ae&&typeof ae==="object"&&(a in ae));if(!S)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[O,C]=S,L=C[a],Q=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[Q]||Q,P;if(O==="hasMany"||O==="hasOne"){let z=w.primaryKeys[u]??"id";P=yt(u,x,z,o)}else if(O==="belongsTo"){let z=w.primaryKeys[x]??"id";P=Tt(u,x,z,o)}else if(O==="belongsToMany"){let z=w.primaryKeys[u]??"id",ae=w.primaryKeys[x]??"id";P=ht(u,x,z,ae,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereHas`);return I("WHERE",`EXISTS (${P})`),this},whereDoesntHave(a,o){if(!w)return this;let u=String(h),T=w.relations?.[u];if(!T)throw Error(`[query-builder] No relationships defined for table '${u}'`);let S=Object.entries(T).find(([z,ae])=>ae&&typeof ae==="object"&&(a in ae));if(!S)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[O,C]=S,L=C[a],Q=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[Q]||Q,P;if(O==="hasMany"||O==="hasOne"){let z=w.primaryKeys[u]??"id";P=yt(u,x,z,o)}else if(O==="belongsTo"){let z=w.primaryKeys[x]??"id";P=Tt(u,x,z,o)}else if(O==="belongsToMany"){let z=w.primaryKeys[u]??"id",ae=w.primaryKeys[x]??"id";P=ht(u,x,z,ae,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereDoesntHave`);return I("WHERE",`NOT EXISTS (${P})`),this},has(a){if(!w)return this;let o=String(h),u=w.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let T=Object.entries(u).find(([P,z])=>z&&typeof z==="object"&&(a in z));if(!T)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[S,O]=T,C=O[a],L=typeof C==="string"?C:C?.model||C?.target||C,Q=w.modelToTable[L]||L,x;if(S==="hasMany"||S==="hasOne"){let P=w.primaryKeys[o]??"id";x=yt(o,Q,P)}else if(S==="belongsTo"){let P=w.primaryKeys[Q]??"id";x=Tt(o,Q,P)}else if(S==="belongsToMany"){let P=w.primaryKeys[o]??"id",z=w.primaryKeys[Q]??"id";x=ht(o,Q,P,z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for has`);return I("WHERE",`EXISTS (${x})`),this},doesntHave(a){if(!w)return this;let o=String(h),u=w.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let T=Object.entries(u).find(([P,z])=>z&&typeof z==="object"&&(a in z));if(!T)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[S,O]=T,C=O[a],L=typeof C==="string"?C:C?.model||C?.target||C,Q=w.modelToTable[L]||L,x;if(S==="hasMany"||S==="hasOne"){let P=w.primaryKeys[o]??"id";x=yt(o,Q,P)}else if(S==="belongsTo"){let P=w.primaryKeys[Q]??"id";x=Tt(o,Q,P)}else if(S==="belongsToMany"){let P=w.primaryKeys[o]??"id",z=w.primaryKeys[Q]??"id";x=ht(o,Q,P,z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for doesntHave`);return I("WHERE",`NOT EXISTS (${x})`),this},withCount(...a){if(!w||!a||a.length===0)return this;let o=String(h);for(let u of a){let T=w.relations?.[o];if(!T)continue;let S=Object.entries(T).find(([we,se])=>se&&typeof se==="object"&&(u in se));if(!S)continue;let[O,C]=S,L=C[u],Q=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[Q]||Q,P=w.primaryKeys[o]??"id",z;if(O==="hasMany"||O==="hasOne")z=Nt(o,x,P);else if(O==="belongsToMany")z=At(o,x,P,u);else continue;let ae=`${u}_count`;at(`${z} AS ${ae}`)}return this},withSum(a,o){return gt("SUM",a,o),this},withAvg(a,o){return gt("AVG",a,o),this},withMax(a,o){return gt("MAX",a,o),this},withMin(a,o){return gt("MIN",a,o),this},applyPivotColumns(){return wt(),this},withPivot(a,...o){if(!w)return this;let u=String(h),T=Ce(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${u}'`);let S=o&&o.length>0?o:T.hasConfig?T.pivotColumns:[];if(S.length===0)return this;if(Le.set(a,S),T.hasConfig)ve.add(a);return wt(),this},wherePivot(a,o,u,T){if(!w)return this;let S=Ce(a);if(!S)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(S.pivotTable,"wherePivot (pivot table)"),F(o,"wherePivot (column)"),st(S);let O=T===void 0?"=":String(u),C=T===void 0?u:T,L=f.length+1,Q=`${S.pivotTable}.${o} ${O} ${t(L)}`;if(f.push(C),k("AND",Q),S.hasConfig)ve.add(a);return this},wherePivotIn(a,o,u){if(!w||!Array.isArray(u))return this;let T=Ce(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(T.pivotTable,"wherePivotIn (pivot table)"),F(o,"wherePivotIn (column)"),st(T);let S=s(u.length,f.length+1),O=l(`${T.pivotTable}.${o}`,u,!1,S);if(f.push(...u),k("AND",O),T.hasConfig)ve.add(a);return this},wherePivotNotIn(a,o,u){if(!w||!Array.isArray(u)||u.length===0)return this;let T=Ce(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(T.pivotTable,"wherePivotNotIn (pivot table)"),F(o,"wherePivotNotIn (column)"),st(T);let S=s(u.length,f.length+1),O=`${T.pivotTable}.${o} NOT IN (${S})`;if(f.push(...u),k("AND",O),T.hasConfig)ve.add(a);return this},wherePivotNull(a,o){if(!w)return this;let u=Ce(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);if(F(u.pivotTable,"wherePivotNull (pivot table)"),F(o,"wherePivotNull (column)"),st(u),k("AND",`${u.pivotTable}.${o} IS NULL`),u.hasConfig)ve.add(a);return this},wherePivotNotNull(a,o){if(!w)return this;let u=Ce(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);if(F(u.pivotTable,"wherePivotNotNull (pivot table)"),F(o,"wherePivotNotNull (column)"),st(u),k("AND",`${u.pivotTable}.${o} IS NOT NULL`),u.hasConfig)ve.add(a);return this},where(a,o,u){if(typeof a==="string"&&o!==void 0){F(String(a),"where(column)"),$e(o,"where(operator)");let T=String(o).toLowerCase();if(T==="in"||T==="not in"){let C=Array.isArray(u)?u:[u],L=s(C.length,f.length+1),Q=l(c(String(a)),C,T==="not in",L);return f.push(...C),k("AND",Q),this}let S=Ue(c(String(a)),T,u,"where");if(S)return k("AND",S),this;let O=f.length+1;return f.push(u),k("AND",`${c(String(a))} ${String(o)} ${t(O)}`),this}if(Array.isArray(a)){let[T,S,O]=a,C=String(T);F(C,"where(column)");let L=$e(S,"where(operator)");if(L==="in"||L==="not in"){let Q=Array.isArray(O)?O:[O],x=s(Q.length,f.length+1),P=l(c(C),Q,L==="not in",x);f.push(...Q),k("AND",P)}else{let Q=Ue(c(C),L,O,"where");if(Q)return k("AND",Q),this;let x=f.length+1;f.push(O),k("AND",`${c(C)} ${L} ${t(x)}`)}return this}if(it(a))lt("where(expr)");if(Ge(a)){let T=Ye(a,f.length+1);return f.push(...T.parameters),k("AND",T.text),this}if(a&&typeof a==="object"&&!Fe(a)){let T=a,S=Object.keys(T),O=[];for(let C of S){F(C,"where(column)");let L=T[C];if(Array.isArray(L)){let Q=s(L.length,f.length+1);O.push(l(c(C),L,!1,Q)),f.push(...L)}else{let Q=f.length+1;O.push(`${c(C)} = ${t(Q)}`),f.push(L)}}if(O.length>0)k("AND",O.length>1?`(${O.join(" AND ")})`:O[0]);return this}if(Fe(a))return k("AND",a.raw),this;if(typeof a==="function")return G("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 F(String(a),"whereNull(column)"),k("AND",`${String(a)} IS NULL`),this},whereNotNull(a){return F(String(a),"whereNotNull(column)"),k("AND",`${String(a)} IS NOT NULL`),this},orWhereNull(a){return F(String(a),"orWhereNull(column)"),k("OR",`${String(a)} IS NULL`),this},orWhereNotNull(a){return F(String(a),"orWhereNotNull(column)"),k("OR",`${String(a)} IS NOT NULL`),this},whereBetween(a,o,u){F(String(a),"whereBetween(column)");let T=f.length+1;return f.push(o,u),k("AND",`${String(a)} BETWEEN ${t(T)} AND ${t(T+1)}`),this},orWhereBetween(a,o,u){F(String(a),"orWhereBetween(column)");let T=f.length+1;return f.push(o,u),k("OR",`${String(a)} BETWEEN ${t(T)} AND ${t(T+1)}`),this},whereExists(a){return k("AND",`EXISTS (${a.toSQL()})`),this},orWhereExists(a){return k("OR",`EXISTS (${a.toSQL()})`),this},whereGroup(a){return G("AND",a),this},orWhereGroup(a){return G("OR",a),this},__whereState(){return{body:D(A),params:[...f]}},__sqlState(){return{sql:Xe(W()),params:[...f]}},whereJsonContains(a,o){F(String(a),"whereJsonContains(column)");let u=e.dialect,T=f.length+1;if(u==="postgres"){let O=typeof o==="number"||typeof o==="boolean"?`to_jsonb(${t(T)})`:t(T);if(e.sql?.jsonContainsMode==="function")k("AND",`jsonb_contains(${a}, ${O})`);else k("AND",`${a} @> ${O}`);f.push(o)}else if(n(u))k("AND",`JSON_CONTAINS(${a}, ${t(T)})`),f.push(JSON.stringify(o));else if(Array.isArray(o)){let S=o.map((O,C)=>`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(T+C)})`);k("AND",`(${S.join(" AND ")})`);for(let O of o)f.push(O)}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 k("AND",`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(T)})`),f.push(o);return this},whereJsonPath(a,o,u){if($e(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 T=e.dialect,S=f.length+1;if(T==="postgres")k("AND",`${a} ${o} ${t(S)}`);else if(n(T))k("AND",`JSON_EXTRACT(${a}) ${o} ${t(S)}`);else k("AND",`json_extract(${a}) ${o} ${t(S)}`);return f.push(u),this},whereLike(a,o,u=!1){let T=t(f.length+1);return I("WHERE",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},whereILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("WHERE",`${String(a)} ILIKE ${u}`);else I("WHERE",`LOWER(${String(a)}) LIKE LOWER(${u})`);return f.push(o),q=null,this},orWhereLike(a,o,u=!1){let T=t(f.length+1);return I("OR",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},orWhereILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("OR",`${String(a)} ILIKE ${u}`);else I("OR",`LOWER(${String(a)}) LIKE LOWER(${u})`);return f.push(o),q=null,this},whereNotLike(a,o,u=!1){let T=t(f.length+1);return I("WHERE",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},whereNotILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("WHERE",`${String(a)} NOT ILIKE ${u}`);else I("WHERE",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return f.push(o),q=null,this},orWhereNotLike(a,o,u=!1){let T=t(f.length+1);return I("OR",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},orWhereNotILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("OR",`${String(a)} NOT ILIKE ${u}`);else I("OR",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return f.push(o),q=null,this},whereAny(a,o,u){if(a.length===0)return k("AND",`(${Ht})`),this;let T=f.length+1,S=a.map((O,C)=>`${O} ${o} ${t(T+C)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`(${S.join(" OR ")})`),this},whereAll(a,o,u){if(a.length===0)return this;let T=f.length+1,S=a.map((O,C)=>`${O} ${o} ${t(T+C)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`(${S.join(" AND ")})`),this},whereNone(a,o,u){if(a.length===0)return this;let T=f.length+1,S=a.map((O,C)=>`${O} ${o} ${t(T+C)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`NOT (${S.join(" OR ")})`),this},whereNotBetween(a,o,u){F(String(a),"whereNotBetween(column)");let T=f.length+1;return f.push(o,u),k("AND",`${a} NOT BETWEEN ${t(T)} AND ${t(T+1)}`),this},whereDate(a,o,u){F(a,"whereDate(column)");let T=u instanceof Date?u.toISOString():typeof u==="string"?u:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof u}`)})(),S=f.length+1;return f.push(T),k("AND",`${a} ${o} ${t(S)}`),this},whereRaw(a,...o){return k("AND",ze(a,"whereRaw(fragment)",o)),this},orWhereRaw(a,...o){return k("OR",ze(a,"orWhereRaw(fragment)",o)),this},whereColumn(a,o,u){return F(a,"whereColumn(left)"),F(u,"whereColumn(right)"),k("AND",`${a} ${o} ${u}`),this},orWhereColumn(a,o,u){return F(a,"orWhereColumn(left)"),F(u,"orWhereColumn(right)"),k("OR",`${a} ${o} ${u}`),this},whereIn(a,o){if(F(String(a),"whereIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!1,u);f.push(...o),k("AND",T)}else _("AND",a,o,!1);return this},orWhereIn(a,o){if(F(String(a),"orWhereIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!1,u);f.push(...o),k("OR",T)}else _("OR",a,o,!1);return this},whereNotIn(a,o){if(F(String(a),"whereNotIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!0,u);f.push(...o),k("AND",T)}else _("AND",a,o,!0);return this},orWhereNotIn(a,o){if(F(String(a),"orWhereNotIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!0,u);f.push(...o),k("OR",T)}else _("OR",a,o,!0);return this},whereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return k("AND",`(${o})`),this},orWhereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return k("OR",`(${o})`),this},andWhere(a,o,u){return V(this,"AND","andWhere",a,o,u)},orWhere(a,o,u){return V(this,"OR","orWhere",a,o,u)},orderBy(a,o="asc"){let u=o==="asc"?"ASC":"DESC",T=c(String(a));return y=ye.ORDER_BY.test(y)?`${y}, ${T} ${u}`:`${y} ORDER BY ${T} ${u}`,q=null,this},orderByDesc(a){return y=ye.ORDER_BY.test(y)?`${y}, ${a} DESC`:`${y} ORDER BY ${a} DESC`,q=null,this},inRandomOrder(){let a=e.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return y=ye.ORDER_BY.test(y)?`${y}, ${a}`:`${y} ORDER BY ${a}`,q=null,this},reorder(a,o="asc"){return y=y.replace(/ORDER BY[\s\S]*$/i,""),y+=` ORDER BY ${a} ${o==="asc"?"ASC":"DESC"}`,q=null,this},latest(a){let o=a??e.timestamps.defaultOrderColumn;return y=ye.ORDER_BY.test(y)?`${y}, ${o} DESC`:`${y} ORDER BY ${o} DESC`,q=null,this},oldest(a){let o=a??e.timestamps.defaultOrderColumn;return y=ye.ORDER_BY.test(y)?`${y}, ${o} ASC`:`${y} ORDER BY ${o} ASC`,q=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=ye.LIMIT.test(y)?y.replace(ye.LIMIT,` LIMIT ${a}`):`${y} LIMIT ${a}`,q=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=ye.OFFSET.test(y)?y.replace(ye.OFFSET,` OFFSET ${a}`):`${y} OFFSET ${a}`,q=null,this},join(a,o,u,T){return F(a,"join(table)"),Pe(o,"join(onLeft)"),Pe(T,"join(onRight)"),$e(u,"join(operator)"),M(`JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},joinSub(a,o,u,T,S){return F(o,"joinSub(alias)"),Pe(u,"joinSub(onLeft)"),Pe(S,"joinSub(onRight)"),$e(T,"joinSub(operator)"),M(`JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${T} ${S}`),H.add(o),this},innerJoin(a,o,u,T){return F(a,"innerJoin(table)"),Pe(o,"innerJoin(onLeft)"),Pe(T,"innerJoin(onRight)"),$e(u,"innerJoin(operator)"),M(`INNER JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},leftJoin(a,o,u,T){return F(a,"leftJoin(table)"),Pe(o,"leftJoin(onLeft)"),Pe(T,"leftJoin(onRight)"),$e(u,"leftJoin(operator)"),M(`LEFT JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},leftJoinSub(a,o,u,T,S){return F(o,"leftJoinSub(alias)"),Pe(u,"leftJoinSub(onLeft)"),Pe(S,"leftJoinSub(onRight)"),$e(T,"leftJoinSub(operator)"),M(`LEFT JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${T} ${S}`),H.add(o),this},rightJoin(a,o,u,T){return F(a,"rightJoin(table)"),Pe(o,"rightJoin(onLeft)"),Pe(T,"rightJoin(onRight)"),$e(u,"rightJoin(operator)"),M(`RIGHT JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},crossJoin(a){return F(a,"crossJoin(table)"),M(`CROSS JOIN ${a}`),H.add(a),this},crossJoinSub(a,o){return F(o,"crossJoinSub(alias)"),M(`CROSS JOIN (${String(a.toSQL())}) AS ${o}`),H.add(o),this},selectAllRelations(){if(!j)return this;let a=String(h),o=Object.keys(j[a]?.columns??{}),u=[];if(o.length>0)u.push(d`${d(a)}.*`);for(let T of H){let S=Object.keys(j[T]?.columns??{});for(let O of S){let C=e.aliasing.relationColumnAliasFormat==="camelCase"?`${T}_${O}`.replace(/_([a-z])/g,(L,Q)=>Q.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${T}.${O}`:`${T}_${O}`;u.push(d`${d(`${T}.${O}`)} AS ${d(C)}`)}}if(u.length>0){let T=o.length>0?`${a}.*`:"",S=[];for(let L of H){let Q=Object.keys(j[L]?.columns??{});for(let x of Q){let P=e.aliasing.relationColumnAliasFormat==="camelCase"?`${L}_${x}`.replace(/_([a-z])/g,(z,ae)=>ae.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${L}.${x}`:`${L}_${x}`;S.push(`${L}.${x} AS ${P}`)}}let O=[T,...S].filter(Boolean).join(", "),C=y.indexOf(" FROM ");if(C!==-1)y=`SELECT ${O}${y.substring(C)}`;else y=`SELECT ${O} FROM ${a}`;q=null}return this},groupBy(...a){if(a.length)y=ye.GROUP_BY.test(y)?`${y}, ${a.map((o)=>c(String(o))).join(", ")}`:`${y} GROUP BY ${a.map((o)=>c(String(o))).join(", ")}`,q=null;return this},groupByRaw(a,...o){let u=ze(a,"groupByRaw(fragment)",o);return y=ye.GROUP_BY.test(y)?`${y}, ${u}`:`${y} GROUP BY ${u}`,q=null,this},having(a){let o=K?"AND":"HAVING";if(Array.isArray(a)){let u=f.length+1;y=`${y} ${o} ${a[0]} ${a[1]} ${t(u)}`,f.push(a[2]),K=!0,q=null}else if(a&&typeof a==="object"&&!("raw"in a)){let u=Object.keys(a),T=u.length;if(T){let S=f.length,O=Array.from({length:T});for(let C=0;C<T;C++){let L=u[C];O[C]=`${L} = ${t(S+C+1)}`,f.push(a[L])}y=`${y} ${o} ${O.join(" AND ")}`,K=!0,q=null}}else if(a&&typeof a.raw<"u")y+=` ${o} ${a.raw}`,K=!0,q=null;return this},havingRaw(a,...o){let u=ze(a,"havingRaw(fragment)",o);return y+=` ${K?"AND":"HAVING"} ${u}`,K=!0,q=null,this},orderByRaw(a,...o){let u=ze(a,"orderByRaw(fragment)",o);return y=ye.ORDER_BY.test(y)?`${y}, ${u}`:`${y} ORDER BY ${u}`,q=null,this},$call(a){return a(this),this},union(a){return ee("UNION",a),this},unionAll(a){return ee("UNION ALL",a),this},intersect(a){return ee("INTERSECT",a),this},intersectAll(a){return ee("INTERSECT ALL",a),this},except(a){return ee("EXCEPT",a),this},exceptAll(a){return ee("EXCEPT ALL",a),this},forPage(a,o){let u=Math.max(1,Math.floor(a)),T=Math.max(1,Math.floor(o));return y+=` LIMIT ${T} OFFSET ${(u-1)*T}`,q=null,this},toSQL(){let a=Xe(W());return{sql:a,toString:()=>a,execute:()=>R().execute(),values:()=>R().values(),raw:()=>R().raw()}},async value(a){let o=J(""," LIMIT 1"),u=await ne(o,"select",{signal:Z,timeoutMs:te}),[T]=u;return T?.[a]},async pluck(a,o){let u=await ne(R(),"select",{signal:Z,timeoutMs:te});if(o){let T={};for(let S of u){let O=String(S?.[o]);if(Object.prototype.hasOwnProperty.call(T,O))throw Error(`[query-builder] pluck(${a}, ${o}): duplicate key '${O}' \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.`);T[O]=S?.[a]}return T}return u.map((T)=>T?.[a])},async exists(){let a=J("SELECT EXISTS (",") as e"),o=await ne(a,"select",{signal:Z,timeoutMs:te}),[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=Xe(W()),ae=[...f],we=await u.tx.unsafe(`SELECT COUNT(*) as c FROM (${z}) as sub`,ae),se=Number(we?.[0]?.c??0),Se=Math.max(1,Math.ceil(se/a)),ke=Math.max(1,Math.min(o,Se)),Oe=(ke-1)*a;return{data:await u.tx.unsafe(`${z} LIMIT ${a} OFFSET ${Oe}`,ae),meta:{perPage:a,page:ke,total:se,lastPage:Se}}}let T=J("SELECT COUNT(*) as c FROM (",") as sub"),S=await ne(T,"select",{signal:Z,timeoutMs:te}),[O]=S,C=Number(O?.c??0),L=Math.max(1,Math.ceil(C/a)),Q=Math.max(1,Math.min(o,L)),x=(Q-1)*a;return{data:await ne(J("",` LIMIT ${t(f.length+1)} OFFSET ${t(f.length+2)}`,[a,x]),"select",{signal:Z,timeoutMs:te}),meta:{perPage:a,page:Q,total:C,lastPage:L}}},async simplePaginate(a,o=1){let u=Math.max(1,o),T=(u-1)*a,S=await ne(J("",` LIMIT ${t(f.length+1)} OFFSET ${t(f.length+2)}`,[a+1,T]),"select",{signal:Z,timeoutMs:te}),O=S.length>a;return{data:O?S.slice(0,a):S,meta:{perPage:a,page:u,hasMore:O}}},async cursorPaginate(a,o,u="id",T="asc"){if(!Number.isInteger(a)||a<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${a}`);let S=(Array.isArray(u)?u:[u]).map(String);for(let Be of S)F(Be,"cursorPaginate(column)");let O=T==="asc"?">":"<",C=T==="asc"?"ASC":"DESC",L=[...f],Q="";if(o!==void 0&&o!==null)if(Array.isArray(u)){let Be=o.map((ie)=>(L.push(ie),t(L.length)));Q=`(${S.join(", ")}) ${O} (${Be.join(", ")})`}else L.push(o),Q=`${S[0]} ${O} ${t(L.length)}`;let x=Xe(Q?W({conn:"AND",sql:Q}):W()),P=S.map((Be)=>`${Be} ${C}`).join(", ");if(Ft(x))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${P} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let z=L.length>0?N(`${x} ORDER BY ${P} LIMIT ${a+1}`,L):N(`${x} ORDER BY ${P} LIMIT ${a+1}`),ae=await ne(z,"select",{signal:Z,timeoutMs:te}),we=ae.length>a,se=ae.slice(0,a),Se=se[se.length-1],ke=we&&Se?Array.isArray(u)?u.map((Be)=>Se[Be]):Se[u]:null,Oe=se.length?Array.isArray(u)?u.map((Be)=>se[0]?.[Be]):se[0]?.[u]:null;return{data:se,meta:{perPage:a,nextCursor:ke??null,prevCursor:Oe}}},async chunk(a,o){let u=1;while(!0){let{data:T,meta:S}=await this.paginate(a,u);if(T.length===0)break;if(await o(T),u>=S.lastPage)break;u+=1}},async chunkById(a,o="id",u){let T;while(!0){let{data:S,meta:O}=await this.cursorPaginate(a,T,o,"asc");if(S.length===0)break;if(u)await u(S);if(T=O.nextCursor,!T)break}},async eachById(a,o="id",u){await this.chunkById(a,o,async(T)=>{for(let S of T)await u?.(S)})},withTimeout(a){return te=Math.max(1,Math.floor(a)),this},abort(a){return Z=a,this},withTrashed(){return ce=!0,me=!1,this},onlyTrashed(){ce=!0,me=!0;let a=e.softDeletes?.column||"deleted_at";return k("AND",`${h}.${a} IS NOT NULL`),this},scope(a,o){let u=String(h),S=w?.scopes?.[u]?.[a];if(S)return S(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(R())),this},dd(){throw console.log(String(R())),Error("Dump and Die")},cache(a=60000){return dt=a,Ie=!0,this},async explain(){let a=J("EXPLAIN ");return await ne(a,"select",{signal:Z,timeoutMs:te})},simple(){return R().simple()},toText(){return W()},async get(){let a=be(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||ut(a));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!o){let L=B._prepareStatement;if(L){let Q=L(W());return rt(f.length>0?Q.all(...f):Q.all())}}let u=W();if(q=f.length>0?N(u,f):N(u),!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!o){let L=R()._stmt,Q=R()._params;if(L)return rt(Q&&Q.length>0?L.all(...Q):L.all());return rt(await R().execute())}if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z)return rt(await ne(R(),"select"));let T=R();if(e.softDeletes?.enabled&&e.softDeletes.defaultFilter&&!ce){let L=e.softDeletes.column,Q=String(h);if((j?Boolean(j[Q]?.columns?.[L]):!0)&&!ye.DELETED_AT.test(W()))I("WHERE",`${String(L)} IS ${me?"NOT ":""}NULL`),T=R()}let S=Ie&&!p?.inTransaction,O=S?Ut(B,W(),f):"";if(S){let L=mt.get(O);if(L)return L}let C=await ne(T,"select",{signal:Z,timeoutMs:te});if(S)mt.set(O,C,dt);return rt(C)},async executeTakeFirst(){let a=await ne(R(),"select",{signal:Z,timeoutMs:te});return nt(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=be(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||ut(a));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!o){let S=B._prepareStatement;if(S){let O=W(),C=O.includes(" LIMIT ")?O:`${O} LIMIT 1`,L=S(C),Q=f.length>0?L.all(...f):L.all();return nt(Q[0])}}let u=await ne(J(""," LIMIT 1"),"select",{signal:Z,timeoutMs:te}),[T]=u;return nt(T)},async firstOrFail(){let a=await this.first();if(!a)throw Error("Record not found");return a},async find(a){let o=w?.primaryKeys[String(h)]??"id",u=await ne(J("",` WHERE ${De(o)} = ${t(f.length+1)} LIMIT 1`,[a]),"select",{signal:Z,timeoutMs:te}),[T]=u;return T},async findOrFail(a){let o=await this.find(a);if(!o)throw Error("Record not found");return o},async findMany(a){let o=w?.primaryKeys[String(h)]??"id";return await ne(J("",` WHERE ${l(De(String(o)),a,!1,s(a.length,f.length+1))}`,a),"select",{signal:Z,timeoutMs:te})},async*lazy(){let a,o=w?.primaryKeys[String(h)]??"id";while(!0){let T=await(a==null?d`${R()} ORDER BY ${d(String(o))} ASC LIMIT 100`:d`${R()} WHERE ${d(String(o))} > ${a} ORDER BY ${d(String(o))} ASC LIMIT 100`).execute();if(T.length===0)break;for(let S of T)yield S;if(a=T[T.length-1]?.[o],a==null)break}},async*lazyById(){let a=w?.primaryKeys[String(h)]??"id",o;while(!0){let T=await(o==null?d`${R()} ORDER BY ${d(String(a))} ASC LIMIT 100`:d`${R()} WHERE ${d(String(a))} > ${o} ORDER BY ${d(String(a))} ASC LIMIT 100`).execute();if(T.length===0)break;for(let S of T)yield S;if(o=T[T.length-1]?.[a],o==null)break}},pipe(a){return a(this)},async count(){let a=W(),o=a.indexOf(" FROM "),u=/ GROUP BY /i.test(a),T;if(u)T=`SELECT COUNT(*) as c FROM (${a}) AS _bqb_count_sub`;else if(o!==-1)T=`SELECT COUNT(*) as c${a.substring(o)}`;else T=`SELECT COUNT(*) as c FROM ${h}`;let S=be(),O=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||ut(S));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!O){let x=B._prepareStatement;if(x){let P=x(T),z=f.length>0?P.all(...f):P.all();return Number(z[0]?.c??0)}}let C=f.length>0?N(T,f):N(T),L=await ne(C,"select",{signal:Z,timeoutMs:te}),[Q]=L;return Number(Q?.c??0)},async avg(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT AVG(${a}) as a${o.substring(u)}`:`SELECT AVG(${a}) as a FROM ${h}`,S=be(),O=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||ut(S));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!O){let x=B._prepareStatement;if(x){let P=x(T),z=f.length>0?P.all(...f):P.all();return Number(z[0]?.a??0)}}let C=f.length>0?N(T,f):N(T),L=await ne(C,"select",{signal:Z,timeoutMs:te}),[Q]=L;return Number(Q?.a??0)},async sum(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT SUM(${a}) as s${o.substring(u)}`:`SELECT SUM(${a}) as s FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await ne(S,"select",{signal:Z,timeoutMs:te}),[C]=O;return Number(C?.s??0)},async max(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT MAX(${a}) as m${o.substring(u)}`:`SELECT MAX(${a}) as m FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await ne(S,"select",{signal:Z,timeoutMs:te}),[C]=O;return C?.m},async min(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT MIN(${a}) as m${o.substring(u)}`:`SELECT MIN(${a}) as m FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await ne(S,"select",{signal:Z,timeoutMs:te}),[C]=O;return C?.m},lockForUpdate(){return y+=" FOR UPDATE",q=null,this},sharedLock(){let a=e.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return y+=` ${a}`,q=null,this},withCTE(a,o){return F(a,"withCTE(name)"),y=`WITH ${a} AS (${String(o.toSQL())}) ${y}`,q=null,this},withRecursive(a,o){return F(a,"withRecursive(name)"),y=`WITH RECURSIVE ${a} AS (${String(o.toSQL())}) ${y}`,q=null,this},execute(){return ne(R(),"select",{signal:Z,timeoutMs:te})},values(){return R().values()},toParams(){return[...f]},__rawState(){return{sql:Xe(W()),params:[...f]}},__hasPredicate(){return A.length>0||v},raw(){return R().raw()},get rows(){return},get row(){return},cancel(){try{R().cancel()}catch{}}},{get(a,o,u){let T=Reflect.get(a,o,u);if(T!==void 0)return T;if(typeof o==="string"&&(o.startsWith("where")||o.startsWith("orWhere")||o.startsWith("andWhere"))){let S=o.startsWith("orWhere"),O=o.startsWith("andWhere"),C=`${String(h)}|${o}`,L=He.get(C);if(L===void 0){let x=o.replace(/^(?:or|and)?where/i,"");if(!x)He.set(C,""),L="";else{let P=x.charAt(0).toLowerCase()+x.slice(1),z=x.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ae=j?Object.keys(j[String(h)]?.columns??{}):[];L=[z,P,P.toLowerCase()].find((we)=>ae.includes(we))??z,He.set(C,L)}}if(L==="")return()=>u;let Q=L;return(x)=>{if(Array.isArray(x)){let P=s(x.length,f.length+1);I(S?"OR":O?"AND":"WHERE",`${Q} IN (${P})`),f.push(...x)}else{let P=t(f.length+1);I(S?"OR":O?"AND":"WHERE",`${Q} = ${P}`),f.push(x)}return u}}return Reflect.get(a,o,u)}})}return{configure(h){return _e(h),this},id(h){if(!ye.IDENTIFIER.test(h))throw Error(`[query-builder] Invalid identifier: '${h}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return B(String(h))},ids(...h){for(let g of h)if(!ye.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 B(h)},select(h,...g){return Je(h,g)},selectFrom(h){return Je(h)},selectFromSub(h,g){function d(R){return()=>{throw Error(`[query-builder] selectFromSub(...).${R}() is not supported. Apply ${R}() 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.")}}F(String(g),"selectFromSub(alias)");let y=typeof h.__rawState==="function"?h.__rawState():null,A=h.toSQL(),f=y?.sql??(typeof A==="string"?A:A?.sql??String(A)),Y=y?.params??(Array.isArray(A?.values)?A.values:[]),v=`SELECT * FROM (${f}) AS ${String(g)}`,K=(R,J,k,I)=>{let U=[...R],W=(G,V,ee)=>{F(G,"selectFromSub where(column)");let M=$e(V,"selectFromSub where(operator)");if(M==="in"||M==="not in"){let te=Array.isArray(ee)?ee:[ee],Z=s(te.length,U.length+1);return U.push(...te),`${G} ${M.toUpperCase()} (${Z})`}let H=t(U.length+1);return U.push(ee),`${G} ${M} ${H}`},_;if(typeof J==="string"&&k!==void 0)_=W(J,k,I);else if(Array.isArray(J)&&J.length===3)_=W(J[0],J[1],J[2]);else if(J&&typeof J==="object"){let G=Object.entries(J).map(([V,ee])=>W(V,"=",ee));_=G.length>1?`(${G.join(" AND ")})`:G[0]}else return{clause:null,params:R};return{clause:_,params:U}};function q(R,J,k,I=""){let U=D(J),W=U?`${R} WHERE ${U}${I}`:`${R}${I}`,_=()=>k.length>0?N(W,k):N(W),G=(M,H,te,Z)=>{let ce=K(k,H,te,Z);return ce.clause===null?q(R,J,k,I):q(R,[...J,{conn:M,sql:ce.clause}],ce.params,I)},V=(M,H)=>{let te=[],Z=[...k],ce=(Le)=>(ve,dt,he)=>{let Ce=K(Z,ve,dt,he);if(Ce.clause!==null)te.push({conn:Le,sql:Ce.clause}),Z=Ce.params;return me},me={where:ce("AND"),andWhere:ce("AND"),orWhere:ce("OR")};H(me);let Ie=D(te);if(!Ie)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return q(R,[...J,{conn:M,sql:`(${Ie})`}],Z,I)},ee={distinct(){return q(R.replace(/^SELECT\s+/i,"SELECT DISTINCT "),J,k,I)},distinctOn(...M){let H=M.map(String).join(", ");return q(R.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${H}) `),J,k,I)},selectRaw(M,...H){let te=ze(M,"selectFromSub.selectRaw(fragment)",H),Z=R.indexOf(" FROM "),ce=Z!==-1?`${R.slice(0,Z)}, ${te}${R.slice(Z)}`:`${R}, ${te}`;return q(ce,J,k,I)},$call(M){return M(this)??this},where(M,H,te){return G("AND",M,H,te)},andWhere(M,H,te){return G("AND",M,H,te)},orWhere(M,H,te){return G("OR",M,H,te)},whereGroup(M){return V("AND",M)},orWhereGroup(M){return V("OR",M)},orderBy(M,H="asc"){F(String(M),"selectFromSub.orderBy(column)");let te=H==="asc"?"ASC":"DESC",Z=ye.ORDER_BY.test(I)?`${I}, ${M} ${te}`:`${I} ORDER BY ${M} ${te}`;return q(R,J,k,Z)},limit(M){if(!Number.isInteger(M)||M<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${M}`);let H=ye.LIMIT.test(I)?I.replace(ye.LIMIT,` LIMIT ${M}`):`${I} LIMIT ${M}`;return q(R,J,k,H)},offset(M){if(!Number.isInteger(M)||M<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${M}`);let H=ye.OFFSET.test(I)?I.replace(ye.OFFSET,` OFFSET ${M}`):`${I} OFFSET ${M}`;return q(R,J,k,H)},toSQL(){return xe(_(),W)},async execute(){return ne(_(),"select")},async executeTakeFirst(){let M=await ne(_(),"select");return Array.isArray(M)?M[0]:M},async executeTakeFirstOrThrow(){let M=await ne(_(),"select"),H=Array.isArray(M)?M[0]:M;if(!H)throw Error("Record not found");return H},async get(){return ne(_(),"select")},async first(){let M=await ne(_(),"select");return Array.isArray(M)?M[0]:M},async firstOrFail(){let M=await ne(_(),"select"),H=Array.isArray(M)?M[0]:M;if(!H)throw Error("No rows found");return H},async count(){let M=k.length>0?N(`SELECT COUNT(*) as c FROM (${W}) as sub`,k):N(`SELECT COUNT(*) as c FROM (${W}) as sub`),H=await ne(M,"select");return Number(H?.[0]?.c??0)},async exists(){let M=k.length>0?N(`SELECT EXISTS(${W}) as e`,k):N(`SELECT EXISTS(${W}) as e`),H=await ne(M,"select");return Boolean(H?.[0]?.e)},async doesntExist(){return!await ee.exists()},values(){return _().values()},raw(){return _().raw()},cancel(){try{_().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:(M)=>M(ee),when:d("when"),tap:()=>ee,dump:()=>ee,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>_().simple(),toText:()=>W,toParams:()=>[...k],withTimeout:()=>ee,abort:()=>ee,lockForUpdate:()=>ee,sharedLock:()=>ee,withCTE:()=>ee,withRecursive:()=>ee,cache:()=>ee,clone:()=>ee,withTrashed:()=>ee,onlyTrashed:()=>ee,scope:()=>ee,get rows(){return[]},get row(){return}};return ee}return q(v,[],Y)},insertInto(h){let g,d="",y=[],A=[],f=!1,Y=()=>K?[]:{changes:0,lastInsertRowid:0},v=()=>{let I=async()=>{return},U=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>v(),andWhere:()=>v(),orWhere:()=>v(),orderBy:()=>v(),limit:()=>v(),offset:()=>v(),toSQL:()=>xe(null,""),execute:async()=>[],get:async()=>[],first:I,executeTakeFirst:I,firstOrFail:U,executeTakeFirstOrThrow:U}},K=e.dialect==="postgres",q=(I)=>{let W=I.flat(2).map(String).filter(Boolean),_=W.length>0&&!W.includes("*")?W.map((ee)=>R(ee)).join(", "):"*",G=async()=>{let ee=await ne(N(d,y),"insert"),M=Number(ee?.lastInsertRowid??0),H=Math.max(1,Number(ee?.affectedRows??1)),te=A.filter((me)=>me!==void 0&&me!==null),Z=M>0?N(`SELECT ${_} FROM ${R(String(h))} WHERE ${R("id")} >= ? AND ${R("id")} < ? ORDER BY ${R("id")} ASC`,[M,M+H]):te.length>0?N(`SELECT ${_} FROM ${R(String(h))} WHERE ${R("id")} IN (${te.map(()=>"?").join(", ")}) ORDER BY ${R("id")} ASC`,te):null;if(!Z)return[];let ce=await Z.execute();return Array.isArray(ce)?ce:[]},V=async()=>(await G())[0];return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>xe(N(d,y),d),execute:G,get:G,first:V,executeTakeFirst:V,async firstOrFail(){let ee=await V();if(!ee)throw Error("Insert with RETURNING returned no rows");return ee},async executeTakeFirstOrThrow(){let ee=await V();if(!ee)throw Error("Insert with RETURNING returned no rows");return ee}}},R=K?(I)=>`"${String(I).replace(/"/g,'""')}"`:n(e.dialect)?(I)=>`\`${String(I).replace(/`/g,"``")}\``:(I)=>`"${String(I).replace(/"/g,'""')}"`,J=K?"postgres":n(e.dialect)?"mysql":"sqlite",k=K?(I)=>`$${I+1}`:(I)=>"?";return{values(I){let U=Ee(String(h),Array.isArray(I)?I:[I]),W=U.length;if(A=U.map((Z)=>Z?.id),W===0)return f=!0,g=null,d="",y.length=0,this;f=!1;let _=U[0],G=Object.keys(_),V=G.length,ee=W*V;y.length=ee;let M=W===1&&V>0&&typeof h==="string",H=M?oe?.get(h):void 0,te=H?.quoteStyle===J&&H.columns.length===V;if(te){for(let Z=0;Z<V;Z++)if(H.columns[Z]!==G[Z]){te=!1;break}}if(te){d=H.sql;for(let Z=0;Z<V;Z++)y[Z]=_[G[Z]]}else if(W===1)if(!K){let Z=R(G[0]),ce="?";y[0]=_[G[0]];for(let me=1;me<V;me++)Z+=`,${R(G[me])}`,ce+=",?",y[me]=_[G[me]];d=`INSERT INTO ${R(h)}(${Z})VALUES(${ce})`}else{let Z=G.map((ce)=>R(ce)).join(",");d=`INSERT INTO ${R(h)}(${Z})VALUES(`;for(let ce=0;ce<V;ce++){if(ce>0)d+=",";d+=k(ce),y[ce]=_[G[ce]]}d+=")"}else{let Z=G.map((me)=>R(me)).join(",");d=`INSERT INTO ${R(h)}(${Z})VALUES`;let ce=0;for(let me=0;me<W;me++){let Ie=U[me];if(me===0)d+="(";else d+="),(";for(let Le=0;Le<V;Le++){if(Le>0)d+=",";d+=k(ce),y[ce++]=Ie[G[Le]]}}d+=")"}if(M&&!te&&d.length<=8192){if(oe??=new Map,oe.size>=32&&!oe.has(h)){let Z=oe.keys().next().value;if(Z!==void 0)oe.delete(Z)}oe.set(h,{columns:G,quoteStyle:J,sql:d})}if(!B._prepareStatement)g=N(d,y);return this},returning(...I){if(f)return v();if(n(e.dialect))return q(I);let U=`${d} RETURNING ${I.join(", ")}`,W=N(U,y),_=async()=>{let G=await ne(W,"insert");return Array.isArray(G)?G[0]:G};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>xe(W,U),execute:()=>ne(W,"insert"),get:()=>ne(W,"insert"),first:_,executeTakeFirst:_,async firstOrFail(){let G=await _();if(!G)throw Error("Insert with RETURNING returned no rows");return G},async executeTakeFirstOrThrow(){let G=await _();if(!G)throw Error("Insert with RETURNING returned no rows");return G}}},toSQL(){if(f)return xe(null,"");if(!g)g=N(d,y);return xe(g,d)},execute(){if(f)return Promise.resolve(Y());let I=be();if(!(I&&(I.onQueryStart||I.onQueryEnd||I.onQueryError||I.startSpan||I.beforeCreate||I.afterCreate||ut(I)))){let W=B._prepareStatement;if(W){let _=W(d);return y.length>0?_.run(...y):_.run()}}if(!g)g=N(d,y);return ne(g,"insert")},async executeTakeFirst(){if(f)return Y();if(!g)g=N(d,y);return await ne(g,"insert")},async executeTakeFirstOrThrow(){if(f)throw Error("Insert failed");if(!g)g=N(d,y);let I=await ne(g,"insert");if(!I)throw Error("Insert failed");return I},returningAll(){return this.returning("*")}}},updateTable(h){let g,d=[],y=(v)=>{let K=String(v);if(n(e.dialect))return`\`${K.replace(/`/g,"``")}\``;return`"${K.replace(/"/g,'""')}"`},A=`UPDATE ${y(String(h))}`,f=!1,Y=(v)=>{A=`${A} ${f?"AND":"WHERE"} ${v}`,f=!0};return{set(v){let K=Ee(String(h),[v])[0],q=Object.keys(K),R=q.length,J=Array.from({length:R});for(let k=0;k<R;k++){let I=q[k],U=K[I];if(it(U))lt(`set(${I})`);if(Fe(U))J[k]=`${y(I)} = ${U.raw}`;else if(Ge(U)){let W=Ye(U,d.length+1);J[k]=`${y(I)} = ${W.text}`,d.push(...W.parameters)}else J[k]=`${y(I)} = ${t(d.length+1)}`,d.push(U)}return A=`${A} SET ${J.join(", ")}`,g=N(A,d),this},where(v,K,q){if(K!==void 0&&(typeof v==="string"||Fe(v)||Ge(v))){let R=$e(K,"updateTable.where"),J;if(typeof v==="string")J=y(v);else if(Fe(v))J=v.raw;else{let U=Ye(v,d.length+1);J=U.text,d.push(...U.parameters)}if(R.toLowerCase()==="in"||R.toLowerCase()==="not in"){let U=Array.isArray(q)?q:[q],W=s(U.length,d.length+1);return Y(`${J} ${R.toUpperCase()} (${W})`),d.push(...U),g=N(A,d),this}let k=Ue(J,R,q,"updateTable.where");if(k)return Y(k),g=N(A,d),this;let I=d.length+1;return Y(`${J} ${R} ${t(I)}`),d.push(q),g=N(A,d),this}if(Array.isArray(v)){let[R,J,k]=v,I=$e(J,"updateTable.where");if(I.toLowerCase()==="in"||I.toLowerCase()==="not in"){let _=Array.isArray(k)?k:[k],G=s(_.length,d.length+1);return Y(`${y(String(R))} ${I.toUpperCase()} (${G})`),d.push(..._),g=N(A,d),this}let U=Ue(y(String(R)),I,k,"updateTable.where");if(U)return Y(U),g=N(A,d),this;let W=d.length+1;return Y(`${y(String(R))} ${I} ${t(W)}`),d.push(k),g=N(A,d),this}if(it(v))lt("updateTable.where(expr)");if(Fe(v))return Y(v.raw),g=N(A,d),this;if(Ge(v)){let R=Ye(v,d.length+1);return Y(R.text),d.push(...R.parameters),g=N(A,d),this}if(v&&typeof v==="object"){let R=Object.keys(v);if(R.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 J=R.map((k)=>pt(y(k),v[k],d));return Y(J.join(" AND ")),g=N(A,d),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${v===null?"null":typeof v}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(v){return Y(`${y(String(v))} IS NULL`),g=N(A,d),this},whereNotNull(v){return Y(`${y(String(v))} IS NOT NULL`),g=N(A,d),this},returning(...v){let K=this,q=()=>`${A} RETURNING ${v.join(", ")}`,R=()=>d.length>0?N(q(),d):N(q()),J=async()=>{let _=/\sWHERE\s/i.test(A),G=_?A.slice(A.search(/\sWHERE\s/i)+1):"",V=d.slice(d.length-(G.match(/\?|\$\d+/g)?.length??0)),ee=y("id"),M=await(V.length>0?N(`SELECT ${ee} FROM ${y(String(h))}${_?` ${G}`:""}`,V):N(`SELECT ${ee} FROM ${y(String(h))}${_?` ${G}`:""}`)).execute().catch(()=>[]),H=(Array.isArray(M)?M:[]).map((ce)=>ce?.id).filter((ce)=>ce!==void 0&&ce!==null);if(await ne(d.length>0?N(A,d):N(A),"update"),H.length===0)return[];let te=`SELECT ${v.join(", ")} FROM ${y(String(h))} WHERE ${ee} IN (${H.map(()=>"?").join(", ")})`,Z=await N(te,H).execute();return Array.isArray(Z)?Z:[]},k=()=>n(e.dialect)?J():ne(R(),"update"),I=async()=>{let _=await k();return Array.isArray(_)?_[0]:_},U=(_)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${_}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},W={where:(..._)=>(K.where(..._),W),andWhere:(..._)=>(K.where(..._),W),whereNull:(..._)=>(K.whereNull(..._),W),whereNotNull:(..._)=>(K.whereNotNull(..._),W),orWhere:U("orWhere"),orderBy:U("orderBy"),limit:U("limit"),offset:U("offset"),toSQL:()=>xe(R(),q()),execute:k,get:k,first:I,executeTakeFirst:I,async firstOrFail(){let _=await I();if(!_)throw Error("Update with RETURNING returned no rows");return _},async executeTakeFirstOrThrow(){let _=await I();if(!_)throw Error("Update with RETURNING returned no rows");return _}};return W},toSQL(){if(!g)g=d.length>0?N(A,d):N(A);return xe(g,A)},async execute(){let v=await ne(g,"update");return Qe(v)},async executeTakeFirst(){return{numUpdatedRows:Qe(await ne(g,"update"))}},async executeTakeFirstOrThrow(){let v=Qe(await ne(g,"update"));if(v===0)throw Error("No rows updated");return{numUpdatedRows:v}},returningAll(){return this.returning("*")}}},deleteFrom(h){let g=(R)=>{let J=String(R);if(n(e.dialect))return`\`${J.replace(/`/g,"``")}\``;return`"${J.replace(/"/g,'""')}"`},y=`DELETE FROM ${g(String(h))}`,A=null,f=[],Y=null,v=!1,K=(R)=>{y+=` ${v?"AND":"WHERE"} ${R}`,v=!0},q=()=>{if(A===null)A=f.length>0?N(y,f):N(y);return A};return{where(R,J,k){if(Y=R,typeof R==="string"&&J!==void 0){let I=$e(J,"deleteFrom.where");if(I.toLowerCase()==="in"||I.toLowerCase()==="not in"){let _=Array.isArray(k)?k:[k],G=s(_.length,f.length+1);return K(`${g(R)} ${I.toUpperCase()} (${G})`),f.push(..._),A=null,this}let U=Ue(g(R),I,k,"deleteFrom.where");if(U)return K(U),A=null,this;let W=f.length+1;return K(`${g(R)} ${I} ${t(W)}`),f.push(k),A=null,this}if(Array.isArray(R)){let[I,U,W]=R,_=$e(U,"deleteFrom.where");if(_.toLowerCase()==="in"||_.toLowerCase()==="not in"){let ee=Array.isArray(W)?W:[W],M=s(ee.length,f.length+1);return K(`${g(String(I))} ${_.toUpperCase()} (${M})`),f.push(...ee),A=null,this}let G=Ue(g(String(I)),_,W,"deleteFrom.where");if(G)return K(G),A=null,this;let V=f.length+1;return K(`${g(String(I))} ${_} ${t(V)}`),f.push(W),A=null,this}if(it(R))lt("deleteFrom.where(expr)");if(Fe(R))return K(R.raw),A=null,this;if(Ge(R)){let I=Ye(R,f.length+1);return K(I.text),f.push(...I.parameters),A=null,this}if(R&&typeof R==="object"){let I=Object.keys(R);if(I.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 U=I.map((W)=>pt(g(W),R[W],f));return K(U.join(" AND ")),A=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${R===null?"null":typeof R}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(R){return K(`${g(String(R))} IS NULL`),A=null,this},whereNotNull(R){return K(`${g(String(R))} IS NOT NULL`),A=null,this},returning(...R){let J=this,k=()=>`${y} RETURNING ${R.join(", ")}`,I=()=>f.length>0?N(k(),f):N(k()),U=async()=>{await be()?.beforeDelete?.({table:String(h),where:Y});let V=n(e.dialect)?await(async()=>{let ee=y.slice(y.search(/\sFROM\s/i)+1),M=`SELECT ${R.join(", ")} ${ee}`,H=await(f.length>0?N(M,f):N(M)).execute();return await ne(f.length>0?N(y,f):N(y),"delete"),Array.isArray(H)?H:[]})():await ne(I(),"delete");try{await be()?.afterDelete?.({table:String(h),where:Y,result:V})}catch{}return V},W=async()=>{let V=await U();return Array.isArray(V)?V[0]:V},_=(V)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${V}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},G={where:(...V)=>(J.where(...V),G),andWhere:(...V)=>(J.where(...V),G),whereNull:(...V)=>(J.whereNull(...V),G),whereNotNull:(...V)=>(J.whereNotNull(...V),G),orWhere:_("orWhere"),orderBy:_("orderBy"),limit:_("limit"),offset:_("offset"),toSQL:()=>xe(I(),k()),execute:()=>U(),get:()=>U(),first:W,executeTakeFirst:W,async firstOrFail(){let V=await W();if(!V)throw Error("Delete with RETURNING returned no rows");return V},async executeTakeFirstOrThrow(){let V=await W();if(!V)throw Error("Delete with RETURNING returned no rows");return V}};return G},toSQL(){return xe(q(),y)},async execute(){try{await be()?.beforeDelete?.({table:String(h),where:Y})}catch(J){throw J}let R=Qe(await ne(q(),"delete"));try{await be()?.afterDelete?.({table:String(h),where:Y,result:R})}catch{}return R},async executeTakeFirst(){return{numDeletedRows:Qe(await ne(q(),"delete"))}},async executeTakeFirstOrThrow(){let R=Qe(await ne(q(),"delete"));if(R===0)throw Error("No rows deleted");return{numDeletedRows:R}},returningAll(){return this.returning("*")}}},table(h){let g=this;return{insert(d){return g.insertInto(h).values(d)},update(d){return g.updateTable(h).set(d)},delete(){return g.deleteFrom(h)},select(...d){if(d.length===0)return g.selectFrom(h);return g.select(h,...d)}}},sql:B,raw(h,...g){if(typeof h==="string")return Wt(h,g);return B(h,...g)},simple(h,...g){return B(h,...g).simple()},async advisoryLock(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_advisory_lock($1)",[g]);await ne(d,"raw");return}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT GET_LOCK(?, -1) AS ok",[g]);await ne(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(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_try_advisory_lock($1) as ok",[g]),y=await ne(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT GET_LOCK(?, 0) AS ok",[g]),y=await ne(d,"raw");return Number(y?.[0]?.ok)===1}return!1},async advisoryUnlock(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_advisory_unlock($1) as ok",[g]),y=await ne(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT RELEASE_LOCK(?) AS ok",[g]),y=await ne(d,"raw");return Number(y?.[0]?.ok)===1}return!1},unsafe(h,g){return Jt(h,g),B.unsafe(h,g)},deferInsert:B.deferInsert?.bind(B),flushDeferredInserts:B.flushDeferredInserts?.bind(B),file(h,g){return B.file(h,g)},async reserve(){let h=await r.reserve(),g=i({sql:h,meta:w,schema:j,hooks:p?.hooks});return g.release=()=>h.release(),g},async close(h){await r.close(h)},async listen(h,g){},async unlisten(h){},async notify(h,g){},async copyTo(h,g){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(h,g,d){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let h=N("SELECT 1");return await ne(h,"select"),!0}catch{return!1}},async waitForReady(h){let g=Math.max(1,h?.attempts??10),d=Math.max(10,h?.delayMs??100);for(let y=0;y<g;y++){if(await this.ping())return;await new Promise((A)=>setTimeout(A,d))}throw Error("Database not ready after waiting")},async transaction(h,g){let y={...p?.txDefaults,...g},A=p?.sql??r,f=p?.inTransaction===!0,Y=f&&typeof A?.savepoint==="function"?"savepoint":"begin",v=async(J)=>{y.logger?.({type:"start",attempt:J});let k=Date.now();return await A[Y](async(I)=>{let U=i({sql:I,meta:w,schema:j,hooks:p?.hooks,inTransaction:!0});if(y?.isolation&&!f){let G=y.isolation,V=G==="read committed"?"READ COMMITTED":G==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(e.dialect==="postgres")await I.unsafe(`SET TRANSACTION ISOLATION LEVEL ${V}`);else if(n(e.dialect))await I.unsafe(`SET TRANSACTION ISOLATION LEVEL ${V}`);else if(G!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${G}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(y?.readOnly)if(e.dialect==="postgres")await I.unsafe("SET TRANSACTION READ ONLY");else if(n(e.dialect))await I.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let W=await h(U),_=Date.now()-k;return y.logger?.({type:"commit",attempt:J,durationMs:_}),W})},K=Math.max(0,y?.retries??0),q=0,R;for(;;)try{R=await v(q+1);break}catch(J){let k=Vt(J)||Gt(J,y.sqlStates);if(q<K&&k){q++,y?.onRetry?.(q,J);let I=rn(q,y.backoff);if(I>0)await Yt(I);continue}try{y.onRollback?.(J)}catch{}try{y.afterRollback?.()}catch{}throw J}return await y.afterCommit?.(),R},async savepoint(h){if(p?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let g=B;if(!g||typeof g.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await g.savepoint(async(d)=>{let y=i({sql:d,meta:w,schema:j,hooks:p?.hooks,inTransaction:!0});return await h(y)})},async beginDistributed(h,g){return await(p?.sql??r).beginDistributed(h,async(A)=>{let f=i({sql:A,meta:w,schema:j,hooks:p?.hooks});return await g(f)})},async commitDistributed(h){await r.commitDistributed(h)},async rollbackDistributed(h){await r.rollbackDistributed(h)},setTransactionDefaults(h){p={...p,txDefaults:{...p?.txDefaults,...h}}},transactional(h,g){return(...d)=>this.transaction((y)=>h(y,...d),g)},async insertOrIgnore(h,g){let d=Array.isArray(g)?g:[g];if(!d.length)return;let{colsSql:y,valuesSql:A,params:f}=ft(d),Y=De(String(h)),v=n(e.dialect)?`INSERT IGNORE INTO ${Y} (${y}) VALUES ${A}`:`INSERT INTO ${Y} (${y}) VALUES ${A} ON CONFLICT DO NOTHING`;return N(v,f).execute()},async insertGetId(h,g,d="id"){let{colsSql:y,valuesSql:A,params:f}=ft([g]),Y=De(String(h));if(n(e.dialect)){await N(`INSERT INTO ${Y} (${y}) VALUES ${A}`,f).execute();let[K]=await N("SELECT LAST_INSERT_ID() as id").execute();return K?.id}if(e.dialect==="sqlite"){let K=await N(`INSERT INTO ${Y} (${y}) VALUES ${A}`,f).execute();if(K?.lastInsertRowid!=null)return K.lastInsertRowid;let[q]=await N("SELECT last_insert_rowid() as id").execute();return q?.id}let[v]=await N(`INSERT INTO ${Y} (${y}) VALUES ${A} RETURNING ${De(String(d))} as id`,f).execute();return v?.id},async updateOrInsert(h,g,d){let y=De(String(h)),A=Object.keys(g),f=1,Y=A.map((k)=>`${De(k)} = ${t(f++)}`).join(" AND "),v=A.map((k)=>g[k]);if((await N(`SELECT 1 FROM ${y} WHERE ${Y} LIMIT 1`,v).execute()).length){let k=Object.keys(d),I=1,U=k.map((G)=>`${De(G)} = ${t(I++)}`).join(", "),W=A.map((G)=>`${De(G)} = ${t(I++)}`).join(" AND "),_=[...k.map((G)=>d[G]),...A.map((G)=>g[G])];return await N(`UPDATE ${y} SET ${U} WHERE ${W}`,_).execute(),!0}let{colsSql:q,valuesSql:R,params:J}=ft([{...g,...d}]);return await N(`INSERT INTO ${y} (${q}) VALUES ${R}`,J).execute(),!0},async upsert(h,g,d,y){let A=d.map((U)=>String(U)),f=(y??[]).map((U)=>String(U)),Y=g;if(!Y.length)return;let{colsSql:v,valuesSql:K,params:q}=ft(Y),R=De(String(h)),J=`INSERT INTO ${R} (${v}) VALUES ${K}`;if(n(e.dialect)){if(f.length===0)return N(`INSERT IGNORE INTO ${R} (${v}) VALUES ${K}`,q).execute();let U=f.map((W)=>`${De(W)} = VALUES(${De(W)})`).join(", ");return N(`${J} ON DUPLICATE KEY UPDATE ${U}`,q).execute()}let k=A.map(De).join(", ");if(f.length===0)return N(`${J} ON CONFLICT (${k}) DO NOTHING`,q).execute();let I=f.map((U)=>`${De(U)} = EXCLUDED.${De(U)}`).join(", ");return N(`${J} ON CONFLICT (${k}) DO UPDATE SET ${I}`,q).execute()},async save(h,g){let d=w?.primaryKeys[String(h)]??"id",y=g[d];if(y!=null)if(await this.selectFrom(h).find(y)){await this.updateTable(h).set(g).where({[d]:y}).execute();let f=await this.selectFrom(h).find(y);if(!f)throw Error("save() failed to retrieve updated row");return f}else return await this.create(h,g);return await this.create(h,g)},async remove(h,g){return await this.deleteFrom(h).where({id:g}).execute()},async find(h,g){return await this.selectFrom(h).find(g)},async findOrFail(h,g){return await this.selectFrom(h).findOrFail(g)},async findMany(h,g){return await this.selectFrom(h).findMany(g)},async latest(h,g){return await this.selectFrom(h).latest(g).first()},async oldest(h,g){return await this.selectFrom(h).oldest(g).first()},skip(h,g){return this.selectFrom(h).offset(g)},async rawQuery(h){let g=Date.now();try{be()?.onQueryStart?.({sql:h,kind:"raw"});let d=await B.unsafe(h);return be()?.onQueryEnd?.({sql:h,durationMs:Date.now()-g,kind:"raw"}),d}catch(d){throw be()?.onQueryError?.({sql:h,error:d,durationMs:Date.now()-g,kind:"raw"}),d}},async create(h,g){let d=w?.primaryKeys[String(h)]??"id";try{await be()?.beforeCreate?.({table:String(h),data:g})}catch(y){throw y}if(e.dialect==="postgres"){let y=B`INSERT INTO ${B(String(h))} ${B(g)} RETURNING ${B(String(d))} as id`,[A]=await y.execute();if(!A?.id)throw console.error(`create() failed to get insert ID for table ${String(h)}`),console.error("Inserted values:",g),Error(`create() failed to get insert ID for table ${String(h)}`);let f=await this.selectFrom(h).find(A.id);if(!f)throw console.error(`create() failed to retrieve inserted row for table ${String(h)} with id ${A.id}`),console.error("Inserted values:",g),Error(`create() failed to retrieve inserted row for table ${String(h)} with id ${A.id}`);try{await be()?.afterCreate?.({table:String(h),data:g,result:f})}catch{}return f}else{let y=await this.insertGetId(h,g,d);if(y==null)throw Error(`create() failed to get insert ID for table ${String(h)}`);let A=await this.selectFrom(h).find(y);if(!A)throw console.error(`create() failed to retrieve inserted row for table ${String(h)} with id ${y}`),console.error("Inserted values:",g),Error(`create() failed to retrieve inserted row for table ${String(h)} with id ${y}`);try{await be()?.afterCreate?.({table:String(h),data:g,result:A})}catch{}return A}},async createMany(h,g){if(!g?.length)return;let d=g[0],y=Object.keys(d),A=y.length,f=g.length,Y=Array.from({length:f*A}),v=n(e.dialect)?(R)=>`\`${String(R).replace(/`/g,"``")}\``:(R)=>`"${String(R).replace(/"/g,'""')}"`,K=`INSERT INTO ${v(String(h))}(${y.map(v).join(",")})VALUES`,q=0;for(let R=0;R<f;R++){if(R>0)K+=",";K+="(";let J=g[R];for(let k=0;k<A;k++){if(k>0)K+=",";K+=t(q+1),Y[q++]=J[y[k]]}K+=")"}return N(K,Y).execute()},async insertMany(h,g){if(!g?.length)return;let d=g[0],y=Object.keys(d),A=y.length,f=g.length,Y=f*A,v=Array(Y),K=e.dialect==="postgres",q;if(!K){let k=Array(A);for(let I=0;I<A;I++)k[I]="?";q=`(${k.join(",")})`}else q="";let R=Array(f+2);R[0]=`INSERT INTO ${h}(${y.join(",")})VALUES`;let J=0;if(!K){for(let k=0;k<f;k++){let I=g[k];R[k+1]=q;for(let U=0;U<A;U++)v[J++]=I[y[U]]}return N(R[0]+R.slice(1,f+1).join(","),v).execute()}for(let k=0;k<f;k++){let I=g[k],U=Array(A);for(let W=0;W<A;W++)U[W]=`$${J+1}`,v[J++]=I[y[W]];R[k+1]=`(${U.join(",")})`}return N(R[0]+R.slice(1,f+1).join(","),v).execute()},async updateMany(h,g,d){let y=Object.keys(d),A=y.length;if(A===0)return 0;let f=[],Y=Array.from({length:A});for(let K=0;K<A;K++)Y[K]=`${y[K]}=${t(K+1)}`,f.push(d[y[K]]);let v=`UPDATE ${h} SET ${Y.join(",")}`;if(Array.isArray(g)){let K=$e(String(g[1]),"updateMany");v+=` WHERE ${g[0]} ${K} ${t(f.length+1)}`,f.push(g[2])}else if(Fe(g))v+=` WHERE ${g.raw}`;else if(Ge(g)){let K=Ye(g,f.length+1);v+=` WHERE ${K.text}`,f.push(...K.parameters)}else if(g&&typeof g==="object"&&Object.keys(g).length>0){let K=Object.keys(g).map((q)=>pt(q,g[q],f));v+=` WHERE ${K.join(" AND ")}`}else if(g&&typeof g==="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 ${g===null?"null":typeof g}. Refusing to run an UPDATE with no WHERE \u2014 use updateTable(table).set(data).execute() if updating every row is intended.`);return N(v,f).execute()},async deleteMany(h,g){if(!Array.isArray(g)||g.length===0)return 0;let d=w?.primaryKeys[String(h)]??"id",y=g.length;if(e.dialect==="postgres"){let f=Array(y);for(let Y=0;Y<y;Y++)f[Y]=`$${Y+1}`;return N(`DELETE FROM ${h} WHERE ${d} IN (${f.join(",")})`,g).execute()}let A=Array(y);for(let f=0;f<y;f++)A[f]="?";return N(`DELETE FROM ${h} WHERE ${d} IN (${A.join(",")})`,g).execute()},async firstOrCreate(h,g,d){let y=await this.selectFrom(h).where(g).first();if(y)return y;return await this.create(h,{...g,...d})},async updateOrCreate(h,g,d){let y=await this.selectFrom(h).where(g).first();if(y){await this.updateTable(h).set(d).where(g).execute();let A=w?.primaryKeys[String(h)]??"id",f=y[A],Y=f!=null?await this.selectFrom(h).find(f):await this.selectFrom(h).where(g).first();if(!Y)throw Error("updateOrCreate() failed to retrieve updated row");return Y}return await this.create(h,{...g,...d})},async count(h,g){let d=g?B(String(g)):B`*`,y=B`SELECT COUNT(${d}) as c FROM ${B(String(h))}`,[A]=await y.execute();return Number(A?.c??0)},async sum(h,g){let d=B`SELECT SUM(${B(String(g))}) as s FROM ${B(String(h))}`,[y]=await d.execute();return Number(y?.s??0)},async avg(h,g){let d=B`SELECT AVG(${B(String(g))}) as a FROM ${B(String(h))}`,[y]=await d.execute();return Number(y?.a??0)},async min(h,g){let d=B`SELECT MIN(${B(String(g))}) as m FROM ${B(String(h))}`,[y]=await d.execute();return y?.m},async max(h,g){let d=B`SELECT MAX(${B(String(g))}) as m FROM ${B(String(h))}`,[y]=await d.execute();return y?.m},getRelationships(h){if(!w?.relations)return{};let g=w.relations[h];if(!g)return{};let d={};for(let[y,A]of Object.entries(g))if(A&&typeof A==="object"&&Object.keys(A).length>0)d[y]=A;return d},hasRelationship(h,g){if(!w?.relations)return!1;let d=w.relations[h];if(!d)return!1;return Object.values(d).some((y)=>y&&typeof y==="object"&&(g in y))},getRelationshipType(h,g){if(!w?.relations)return null;let d=w.relations[h];if(!d)return null;for(let[y,A]of Object.entries(d))if(A&&typeof A==="object"&&g in A)return y;return null},getRelationshipTarget(h,g){if(!w?.relations)return null;let d=w.relations[h];if(!d)return null;for(let[y,A]of Object.entries(d))if(A&&typeof A==="object"&&g in A){let f=A[g];if(typeof f==="string")return w.modelToTable[f]||f;else if(f&&typeof f==="object"){if("model"in f)return w.modelToTable[f.model]||f.model;if("target"in f)return w.modelToTable[f.target]||f.target}}return null}}}function Re(){mt.clear()}function Ae(p){mt.setMaxSize(p)}
|
|
2
|
+
import{n,e,t,s,_e,b,r,m,Ht,D,l,X,je,qe}from"./chunk-3hwsz4q7.js";import{Buffer as St}from"buffer";import{serialize as Mt}from"v8";function vt(p){return m(e.relations?.singularizeStrategy)(p)}function E(p,B,w,j={}){let re=j.singularize??vt,oe=p.relations?.[B]?.belongsToMany?.[w];if(oe==null)return null;let Ee=typeof oe==="object",pe=Ee?oe:null,be=Ee?pe.model:oe,He=p.modelToTable[be]||be,Ve,et;if(pe?.table)Ve=pe.table;else if(pe?.through){if(et=pe.through,Ve=p.modelToTable[pe.through],!Ve)throw Error(`[query-builder] belongsToMany relation '${w}' on '${B}' references unknown through model '${pe.through}'. Make sure '${pe.through}' is registered via defineModels({...}).`)}else{let Je=re(B),h=re(He);Ve=[Je,h].sort().join("_")}let tt=pe?.foreignKey??`${re(B)}_id`,ct=pe?.relatedKey??`${re(He)}_id`,ne={};if(pe?.pivot?.columns)Object.assign(ne,pe.pivot.columns);if(et&&j.models){let Je=j.models[et],h=Je?.definition??Je?.getDefinition?.()??Je,g=h?.attributes??{};for(let[d,y]of Object.entries(g)){if(d===tt||d===ct||d===(h?.primaryKey??"id"))continue;ne[d]={default:y?.default,nullable:y?.nullable,validation:y?.validation}}}let Qe=Boolean(pe?.pivot?.timestamps),xe=Object.keys(ne);return{pivotTable:Ve,fkParent:tt,fkRelated:ct,pivotColumns:xe,pivotColumnDefs:ne,pivotModelName:et,timestamps:Qe,relatedModelName:be,relatedTable:He,hasConfig:Ee}}function*In(p,B={}){let w=p.relations;if(!w)return;for(let[j,re]of Object.entries(w)){let N=re?.belongsToMany;if(!N)continue;for(let oe of Object.keys(N)){let Ee=E(p,j,oe,B);if(Ee)yield{parentTable:j,relationKey:oe,resolved:Ee}}}}function Fe(p){return typeof p==="object"&&p!==null&&"raw"in p&&typeof p.raw==="string"}function pt(p,B,w){if(Array.isArray(B)){let re=s(B.length,w.length+1),N=l(p,B,!1,re);return w.push(...B),N}let j=`${p} = ${t(w.length+1)}`;return w.push(B),j}function Ge(p){return typeof p==="object"&&p!==null&&"sql"in p&&typeof p.sql==="string"&&(!("parameters"in p)||Array.isArray(p.parameters))}function Wt(p,B){let[w,...j]=B;if(j.length>0||w!==void 0&&!Array.isArray(w))throw TypeError("[query-builder] db.raw(sql, bindings): pass the bindings as one array, db.raw('a = ? AND b = ?', [a, b]).");let re={sql:p,parameters:[...w??[]]};return Object.defineProperty(re,"then",{enumerable:!1,value:(N,oe)=>{let Ee=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 oe==="function")return oe(Ee);throw Ee}}),re}function it(p){return p instanceof Promise&&typeof p.execute==="function"&&typeof p.cancel==="function"}function lt(p){throw TypeError(`[query-builder] ${p}: 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 Ye(p,B){let w=p.parameters??(Array.isArray(p.values)?p.values:[]);if(e.dialect!=="postgres"||w.length===0)return{text:p.sql,parameters:w};let j=0,{text:re}=je(p.sql,()=>j<w.length?t(B+j++):void 0);if(j!==w.length)throw TypeError(`[query-builder] SQL expression declares ${w.length} parameters but contains only ${j} placeholders`);return{text:re,parameters:w}}function kt(p,B){if(B.length===2){let[w,j]=B;if(Array.isArray(j)&&typeof w==="number"&&j[w]===p)return!1;if(j instanceof Set&&w===p&&j.has(p))return!1;if(j instanceof Map&&j.get(w)===p)return!1}return B.some((w)=>w!==void 0&&!(Array.isArray(w)&&w.length===0))}function en(p,...B){if(typeof p==="string"){if(!(B.length===1&&Number.isInteger(B[0])&&B[0]>=0&&!p.includes("?"))&&kt(p,B))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:p}}let w=p[0];for(let j=0;j<B.length;j++)w+=Ke(B[j])+p[j+1];return{raw:w}}function De(p){return n(e.dialect)?`\`${p.replace(/`/g,"``")}\``:`"${p.replace(/"/g,'""')}"`}function ft(p,B=1){let w=Object.keys(p[0]??{}),j=[],re=B,N=p.map((oe)=>`(${w.map((pe)=>(j.push(oe[pe]),t(re++))).join(", ")})`);return{colsSql:w.map(De).join(", "),valuesSql:N.join(", "),params:j,nextIndex:re}}function ut(p){return Boolean(p&&(p.onSlowQuery||p.slowQueryThresholdMs!=null&&p.slowQueryThresholdMs>=0))}function c(p,B=e.dialect){if(!n(B))return p;let w=/^([A-Z_][\w$]*)(?:\.([A-Z_][\w$]*))?(?:\s+as\s+([A-Z_][\w$]*))?$/i.exec(p.trim());if(!w)return p;let[,j,re,N]=w,oe=re?`\`${j}\`.\`${re}\``:`\`${j}\``;return N?`${oe} AS \`${N}\``:oe}function Ct(p,B=e.dialect){if(!n(B)||p===null||p===void 0)return p;if(typeof p==="string"){let w=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(p);if(!w)return p;let[,j,re]=w;return`${j} ${re.length===5?`${re}:00`:re}`}if(!(p instanceof Date)||Number.isNaN(p.getTime()))return p;return p.toISOString().replace("T"," ").replace(/\.\d+Z$/,"")}function $t(p){if(typeof p==="string")return c(p);if(Fe(p))return p.raw;if(p&&typeof p==="object"){let B=p;if(typeof B.raw==="function")return String(B.raw());if(typeof B.sql==="string")return B.sql;let w=String(p);if(w!=="[object Object]")return w}throw TypeError(`[query-builder] select(): unsupported column ${String(p)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function Ft(p){let B=/\(|\)|\bORDER\s+BY\b/gi,w=0,j;while(j=B.exec(p))if(j[0]==="(")w++;else if(j[0]===")")w=Math.max(0,w-1);else if(w===0)return!0;return!1}var ye={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},Bt=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function F(p,B){if(!ye.IDENTIFIER.test(p)){let w=B?` in ${B}`:"";throw Error(`[query-builder] Invalid identifier${w}: '${p}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function $e(p,B){if(typeof p!=="string")throw TypeError(`[query-builder] ${B}: operator must be a string, got ${typeof p}`);let w=p.toLowerCase();if(!Bt.has(w))throw TypeError(`[query-builder] ${B}: refusing to use '${p}' as a SQL operator \u2014 not in the allowed set (${[...Bt].join(", ")})`);return p}function Ue(p,B,w,j){let re=B.toLowerCase();if(re!=="is"&&re!=="is not")return null;if(w!==null&&w!==void 0)throw TypeError(`[query-builder] ${j}: operator '${B}' only accepts NULL/undefined as value, got ${typeof w} (${String(w)})`);return`${p} IS ${re==="is not"?"NOT ":""}NULL`}function Pe(p,B){if(typeof p!=="string"||p.length===0)throw TypeError(`[query-builder] ${B}: identifier must be a non-empty string, got ${typeof p}`);if(p.length>129)throw TypeError(`[query-builder] ${B}: identifier '${p}' too long`);let w=p.split(".");if(w.length>2)throw TypeError(`[query-builder] ${B}: identifier '${p}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let j of w)if(!/^[A-Z_][A-Z0-9_]*$/i.test(j))throw TypeError(`[query-builder] ${B}: identifier segment '${j}' contains characters outside [A-Za-z0-9_]`)}function ze(p,B,w=[]){let j=typeof p==="object"&&p!==null?p.parameters??p.values:void 0;if(kt(p,w)||Array.isArray(j)&&j.length>0){let re=B.startsWith("whereRaw(")?", or use where(). Model.query().whereRaw(sql, ...bindings) is the builder that binds `?` values.":B.startsWith("orWhereRaw(")?", or use orWhere(). Model.query().orWhereRaw(sql, ...bindings) is the builder that binds `?` values.":".";throw TypeError(`[query-builder] ${B}: 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${re}`)}if(typeof p==="string")return Kt(B),p;if(p===null||p===void 0)throw TypeError(`[query-builder] ${B}: fragment must be a SqlFragment, got ${p}`);if(Fe(p))return p.raw;if(typeof p==="object"){let re=p;if(typeof re.raw==="string")return re.raw;if(typeof re.raw==="function"){let oe=re.raw();if(typeof oe==="string")return oe}if(typeof re.sql==="string")return re.sql;let N=String(p);if(N!=="[object Object]"&&N!=="[object Promise]")return N}throw TypeError(`[query-builder] ${B}: 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 Jt(p,B){if(!B||B.length===0)return;if(e.dialect!=="postgres")return;if(/\$\d/.test(p))return;let w=X(p),j=`${B.length} binding${B.length===1?"":"s"}`,re=w>0?`the query binds them with ${w} \`?\` placeholder${w===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(): ${j} supplied, but ${re}. 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 Dt=new Set;function Kt(p){if(Dt.has(p))return;Dt.add(p),console.warn(`[query-builder] ${p}: 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 Rt(p,B=e.dialect){return n(B)?p.replace(/\\/g,"\\\\").replace(/'/g,"''"):p.replace(/'/g,"''")}function Ke(p){if(p===null)return"NULL";if(typeof p==="number"&&Number.isFinite(p))return String(p);if(typeof p==="boolean")return p?"1":"0";if(typeof p==="string")return`'${Rt(p)}'`;if(p instanceof Date)return`'${p.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof p}`)}function _t(p,B){let w=Array.isArray(p)?p:p?[p]:[],j=[];if(w.length)j.push(`PARTITION BY ${w.join(", ")}`);if(B&&B.length)j.push(`ORDER BY ${B.map(([re,N])=>`${re} ${N==="desc"?"DESC":"ASC"}`).join(", ")}`);return j.length?`OVER (${j.join(" ")})`:"OVER ()"}class Ot{cache=new Map;maxSize=100;get(p){let B=this.cache.get(p);if(!B)return null;if(Date.now()>B.expiresAt)return this.cache.delete(p),null;return this.cache.delete(p),this.cache.set(p,B),B.data}set(p,B,w){if(this.cache.has(p))this.cache.delete(p);if(this.cache.size>=this.maxSize){let j=Date.now(),re=!1;for(let[N,oe]of this.cache)if(j>oe.expiresAt){if(this.cache.delete(N),re=!0,this.cache.size<this.maxSize)break}if(!re){let N=this.cache.keys().next().value;if(N!==void 0)this.cache.delete(N)}}this.cache.set(p,{data:B,expiresAt:Date.now()+w})}clear(){this.cache.clear()}setMaxSize(p){this.maxSize=Math.max(0,Math.floor(p));while(this.cache.size>this.maxSize){let B=this.cache.keys().next().value;if(B===void 0)break;this.cache.delete(B)}}}var mt=new Ot,Et=new WeakMap,jt=0;function Ut(p,B,w){let j=Et.get(p);if(j===void 0)j=++jt,Et.set(p,j);let re=w.map((N)=>ArrayBuffer.isView(N)?["view",St.isBuffer(N)?"Buffer":Object.prototype.toString.call(N),St.from(N.buffer,N.byteOffset,N.byteLength).toString("base64")]:["value",Mt(N).toString("base64")]);return`${j}\x00${B}\x00${JSON.stringify(re)}`}function Vt(p){let B=String(p?.message||"").toLowerCase();return B.includes("deadlock")||B.includes("serialization failure")||B.includes("could not serialize access")||B.includes("deadlock found when trying to get lock")||B.includes("lock wait timeout exceeded")||B.includes("database is locked")||B.includes("busy")}function Gt(p,B){if(!B||B.length===0)return!1;let w=p&&(p.code||p.sqlState||p.sqlstate);if(!w)return!1;return B.includes(w)}function Yt(p){return new Promise((B)=>setTimeout(B,p))}var bt=new Map,zt=500,Xt=[{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}],Zt=[{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}],tn=[{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 Xe(p){let B=bt.get(p);if(B!==void 0)return B;let w=nn(p);if(bt.size>=zt)bt.clear();return bt.set(p,w),w}function nn(p){let B=qe(p,Xt);if(B.length<=1)return p;let w=p.slice(0,B[0].start).trimEnd(),j={};for(let oe=0;oe<B.length;oe++){let Ee=B[oe].start,pe=oe+1<B.length?B[oe+1].start:p.length,be=p.slice(Ee,pe).trim();if(!j[B[oe].key])j[B[oe].key]=[];j[B[oe].key].push(be)}let N=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((oe)=>j[oe]).map((oe)=>j[oe].join(" ")).join(" ");return N?`${w} ${N}`:w}function rn(p,B){let w=Math.max(1,B?.baseMs??50),j=Math.max(1,B?.factor??2),re=Math.max(w,B?.maxMs??2000),N=Math.min(re,w*j**Math.max(0,p-1));if(B?.jitter)N=Math.min(re,N*(0.9+Math.random()*0.2));return Math.floor(N)}function i(p){let B=p?.sql??b(),w=p?.meta,j=p?.schema,re;function N(h,g){let d=B.unsafe(h,g);if(typeof d.sql!=="string")re??=new WeakMap,re.set(d,{sql:h,params:g?.slice()});return d}let oe,Ee=(h,g)=>{let d=w?.temporalColumns?.[h];if(!d||d.length===0||!n(e.dialect))return g;return g.map((y)=>{let A=null;for(let f of d){if(!(f in y))continue;let Y=Ct(y[f]);if(Y!==y[f])A=A??{...y},A[f]=Y}return A??y})};function pe(h){if(typeof h==="number")return h;let g=String(h),d=7;for(let y=0;y<g.length;y++)d=d*31+g.charCodeAt(y)|0;return Math.abs(d)}function be(){if(!p?.hooks)return e.hooks;return{...e.hooks,...p.hooks}}let He=new Map;function Ve(h){if(Array.isArray(h)){let[f,Y,v]=h;F(f,"where(column)");let K=String(f);switch(Y){case"in":if(Array.isArray(v)){let q=s(v.length);return N(`${K} IN (${q})`,v)}return N(`${K} IN (${t(1)})`,[v]);case"not in":if(Array.isArray(v)){let q=s(v.length);return N(`${K} NOT IN (${q})`,v)}return N(`${K} NOT IN (${t(1)})`,[v]);case"like":return N(`${K} LIKE ${t(1)}`,[v]);case"is":case"is not":{if(v!==null&&v!==void 0)throw TypeError(`[query-builder] where(..., '${Y}', ?): operator '${Y}' only accepts NULL/undefined as value, got ${typeof v} (${String(v)})`);return N(`${K} IS ${Y==="is not"?"NOT ":""}NULL`)}case"!=":return N(`${K} <> ${t(1)}`,[v]);case"<":case">":case"<=":case">=":case"=":return N(`${K} ${Y} ${t(1)}`,[v]);default:throw TypeError(`[query-builder] where(..., '${String(Y)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in h)return h.raw;let g=Object.keys(h);if(g.length===0)return N("");let d=[],y=[],A=1;for(let f of g){F(f,"where(object key)");let Y=h[f];if(Array.isArray(Y)){let v=s(Y.length,A);d.push(`${f} IN (${v})`),y.push(...Y),A+=Y.length}else d.push(`${f} = ${t(A++)}`),y.push(Y)}return N(d.join(" AND "),y)}function et(h,g,d){if(!d)return g;let y=Ve(d);return B`${g} WHERE ${y}`}function tt(h){let g=re?.get(h);if(g)return g.sql;let d=e.debug?.captureText;if(e.debug)e.debug.captureText=!0;let y=String(h);if(e.debug)e.debug.captureText=d;return y}function ct(h){let g=re?.get(h);if(g)return g.params;if(!h||typeof h!=="object")return;if(Array.isArray(h.values))return h.values;if(Array.isArray(h.parameters))return h.parameters;if(Array.isArray(h.params))return h.params;return}function ne(h,g,d){let y=be(),A=y?.slowQueryThresholdMs,f=A!=null&&A>=0,Y=Boolean(y?.onSlowQuery||f),v=y&&(y.onQueryStart||y.onQueryEnd||y.onQueryError||y.startSpan||Y),K=d?.timeoutMs&&d.timeoutMs>0||d?.signal;if(!v&&!K)return h.execute();let q=tt(h),R=ct(h),J=Date.now(),k;try{if(y?.onQueryStart?.({sql:q,params:R,kind:g}),y?.startSpan)k=y.startSpan({sql:q,params:R,kind:g})}catch{}let I=!1,U=(V,ee,M=Boolean(V))=>{if(I)return;I=!0;let H=Date.now()-J;try{if(M)y?.onQueryError?.({sql:q,params:R,error:V,durationMs:H,kind:g});else if(y?.onQueryEnd?.({sql:q,params:R,durationMs:H,rowCount:ee,kind:g}),f&&H>=A)if(y?.onSlowQuery)y.onSlowQuery({sql:q,params:R,durationMs:H,kind:g});else console.warn(`[query-builder] slow query (${H}ms >= ${A}ms): ${q}`)}catch{}try{k?.end(V)}catch{}};if(typeof h.executeSync==="function"){let V,ee,M=!1;try{V=h.executeSync()}catch(te){ee=te,M=!0}if(d?.signal?.aborted){try{h.cancel?.()}catch{}ee=Object.assign(Error("Query aborted"),{code:"EBQBABORT"}),M=!0}if(M)return U(ee,void 0,!0),Promise.reject(ee);let H=Array.isArray(V)?V.length:typeof V==="number"?V:void 0;return U(void 0,H),Promise.resolve(V)}let W=h.execute(),_=[W],G;if(d?.timeoutMs&&d.timeoutMs>0){let V=new Promise((ee,M)=>{G=setTimeout(()=>{try{h.cancel?.()}catch{}let H=Error(`Query timed out after ${d.timeoutMs}ms`);H.code="EBQBTIMEOUT",M(H)},d.timeoutMs)});_.push(V)}if(d?.signal){if(d.signal.aborted){try{h.cancel?.()}catch{}let ee=Error("Query aborted");return ee.code="EBQBABORT",U(ee),Promise.reject(ee)}let V=()=>{try{h.cancel?.()}catch{}};d.signal.addEventListener("abort",V,{once:!0}),W.finally(()=>{d.signal?.removeEventListener("abort",V)})}return Promise.race(_).then((V)=>{clearTimeout(G);let ee=Array.isArray(V)?V.length:typeof V==="number"?V:void 0;return U(void 0,ee),V}).catch((V)=>{throw clearTimeout(G),U(V),V})}function Qe(h){if(typeof h==="number")return Number.isFinite(h)?h:0;if(typeof h==="bigint")return Number(h);if(!h||typeof h!=="object")return 0;let g=h;for(let d of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(g[d]!==void 0&&g[d]!==null)return Qe(g[d]);if(Array.isArray(h))return h.reduce((d,y)=>d+Qe(y),0);return 0}function xe(h,g){let d=g??tt(h);return{sql:d,toString:()=>d,execute:()=>h.execute(),values:()=>h.values(),raw:()=>h.raw()}}function Je(h,g){let d=B,y=g&&g.length>0?`SELECT ${g.join(", ")} FROM ${String(h)}`:`SELECT * FROM ${String(h)}`,A=[],f=[],Y=!1,v=!1,K=!1,q=null,R=()=>{if(q===null){let a=Xe(W());q=f.length>0?N(a,f):N(a)}return q},J=(a="",o="",u=[])=>N(`${a}${Xe(W())}${o}`,[...f,...u]),k=(a,o)=>{A.push({conn:a,sql:o}),q=null},I=(a,o)=>{k(a==="OR"?"OR":"AND",o)},U=(a)=>{let o=qe(a,Zt,1);return o.length>0?o[0].start:-1},W=(a)=>{let o=D(a?[...A,a]:A);if(!o)return y;if(Y)return`${y} ${v?"AND":"WHERE"} ${o}`;let u=U(y);return u>=0?`${y.slice(0,u)}WHERE ${o} ${y.slice(u)}`:`${y} WHERE ${o}`},_=(a,o,u,T)=>{let S=typeof u?.__sqlState==="function"?u.__sqlState():void 0,O;if(S){let C=f.length;O=C>0&&e.dialect==="postgres"?S.sql.replace(/\$(\d+)/g,(L,Q)=>`$${Number(Q)+C}`):S.sql,f.push(...S.params)}else O=String(u.toSQL());k(a,`${o} ${T?"NOT IN":"IN"} (${O})`)},G=(a,o)=>{let u=Je(h);o(u);let T=u.__whereState?.();if(!T||!T.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let S=f.length,O=S>0&&e.dialect==="postgres"?T.body.replace(/\$(\d+)/g,(C,L)=>`$${Number(L)+S}`):T.body;f.push(...T.params),k(a,`(${O})`)},V=(a,o,u,T,S,O)=>{if(typeof T==="string"&&S!==void 0){F(String(T),`${u}(column)`),$e(S,`${u}(operator)`);let C=Ue(String(T),String(S),O,u);if(C)return k(o,C),a;let L=f.length+1;return f.push(O),k(o,`${String(T)} ${String(S)} ${t(L)}`),a}if(Array.isArray(T)){let[C,L,Q]=T,x=String(C);F(x,`${u}(column)`);let P=$e(L,`${u}(operator)`);if(P==="in"||P==="not in"){let z=Array.isArray(Q)?Q:[Q],ae=s(z.length,f.length+1),we=l(c(x),z,P==="not in",ae);f.push(...z),k(o,we)}else{let z=Ue(x,P,Q,u);if(z)return k(o,z),a;let ae=f.length+1;f.push(Q),k(o,`${x} ${P} ${t(ae)}`)}return a}if(typeof T==="function")return G(o,T),a;if(it(T))lt(`${u}(expr)`);if(Ge(T)){let C=Ye(T,f.length+1);return f.push(...C.parameters),k(o,C.text),a}if(T&&typeof T==="object"&&!("raw"in T)){let C=[];for(let L of Object.keys(T)){F(L,`${u}(column)`);let Q=T[L];if(Array.isArray(Q)){let x=s(Q.length,f.length+1);C.push(l(c(L),Q,!1,x)),f.push(...Q)}else{let x=f.length+1;C.push(`${L} = ${t(x)}`),f.push(Q)}}if(C.length>0)k(o,C.length>1?`(${C.join(" AND ")})`:C[0]);return a}if(T&&typeof T.raw<"u")return k(o,T.raw),a;return a},ee=(a,o)=>{if(A.length>0)y=W(),A.length=0;Y=!0;let u=o.__rawState?.();if(u){let T=f.length,S=e.dialect==="postgres"?u.sql.replace(/\$(\d+)/g,(O,C)=>`$${Number(C)+T}`):u.sql;y+=` ${a} ${S}`,f.push(...u.params),v=o.__hasPredicate?.()??ye.WHERE.test(S)}else{let T=String(o.toSQL());y+=` ${a} ${T}`,v=o.__hasPredicate?.()??ye.WHERE.test(T)}q=null},M=(a)=>{let o=qe(y,tn,1),u=o.length>0?o[0].start:-1;y=u>=0?`${y.slice(0,u)}${a} ${y.slice(u)}`:`${y} ${a}`,q=null},H=new Set,te,Z,ce=!1,me=!1,Ie=!1,Le=new Map,ve=new Set,dt=60000,he=(a)=>m(e.relations.singularizeStrategy)(a),Ce=(a)=>{if(!w)return null;return E(w,String(h),a,{singularize:he,models:w.models})},nt=(a)=>{if(!a||typeof a!=="object"||ve.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},rt=(a)=>{if(ve.size===0||!a)return a;if(Array.isArray(a))for(let o=0;o<a.length;o++)nt(a[o]);else nt(a);return a},st=(a)=>{if(!w)return;if(H.has(a.pivotTable))return;let o=String(h),u=w.primaryKeys[o]??"id";F(a.pivotTable,"wherePivot auto-join (pivot table)"),F(a.fkParent,"wherePivot auto-join (parent FK)"),F(o,"wherePivot auto-join (parent table)"),F(u,"wherePivot auto-join (parent PK)"),q=d`${R()} 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}`,H.add(a.pivotTable)},at=(a)=>{if(ye.SELECT_STAR.test(y))y=y.replace(ye.SELECT_STAR,`SELECT *, ${a}`);else if(ye.SELECT.test(y))y=y.replace(ye.SELECT_FROM,`SELECT $1, ${a} FROM`);let o=String(R());if(ye.SELECT_STAR.test(o)){let u=o.replace(ye.SELECT_STAR,`SELECT *, ${a}`);q=N(u)}else if(ye.SELECT.test(o)){if(ye.SELECT_FROM.exec(o)){let T=o.replace(ye.SELECT_FROM,`SELECT $1, ${a} FROM`);q=N(T)}}},Me=(a,o,u,T)=>{at(`${a} ${_t(u,T)} AS ${o}`)},yt=(a,o,u,T)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)");let S=`${a.endsWith("s")?a.slice(0,-1):a}_id`;F(S,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${o} WHERE ${o}.${S} = ${a}.${u}`;if(T){let L=T({where:(Q,x,P)=>(F(Q,"relationship subquery condition"),`${o}.${Q} ${$e(x,"whereHas callback")} ${Ke(P)}`)});if(L)O+=` AND ${L}`}return O},Tt=(a,o,u,T)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)");let S=`${o.endsWith("s")?o.slice(0,-1):o}_id`;F(S,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${o} WHERE ${o}.${u} = ${a}.${S}`;if(T){let L=T({where:(Q,x,P)=>(F(Q,"relationship subquery condition"),`${o}.${Q} ${$e(x,"whereHas callback")} ${Ke(P)}`)});if(L)O+=` AND ${L}`}return O},ht=(a,o,u,T,S,O)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)"),F(T,"relationship subquery (target primary key)");let C=O&&w?E(w,a,O,{singularize:he,models:w.models}):null,L=he(a),Q=he(o),x=C?.pivotTable??[L,Q].sort().join("_"),P=C?.fkParent??`${L}_id`,z=C?.fkRelated??`${Q}_id`;F(x,"relationship subquery (pivot table)"),F(P,"relationship subquery (foreign key A)"),F(z,"relationship subquery (foreign key B)");let ae=`SELECT 1 FROM ${x} JOIN ${o} ON ${o}.${T} = ${x}.${z} WHERE ${x}.${P} = ${a}.${u}`;if(S){let se=S({where:(Se,ke,Oe)=>(F(Se,"relationship subquery condition"),`${o}.${Se} ${$e(ke,"whereHas callback")} ${Ke(Oe)}`)});if(se)ae+=` AND ${se}`}return ae},Nt=(a,o,u)=>{F(a,"withCount (parent table)"),F(o,"withCount (target table)"),F(u,"withCount (primary key)");let T=`${a.endsWith("s")?a.slice(0,-1):a}_id`;return F(T,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${o} WHERE ${o}.${T} = ${a}.${u})`},At=(a,o,u,T)=>{F(a,"withCount (parent table)"),F(o,"withCount (target table)"),F(u,"withCount (primary key)");let S=T&&w?E(w,a,T,{singularize:he,models:w.models}):null,O=he(a),C=he(o),L=S?.pivotTable??[O,C].sort().join("_"),Q=S?.fkParent??`${O}_id`;return F(L,"withCount (pivot table)"),F(Q,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${L} WHERE ${L}.${Q} = ${a}.${u})`},gt=(a,o,u)=>{if(!w)return;F(u,`with${a[0]}${a.slice(1).toLowerCase()} (column)`);let T=String(h),S=w.relations?.[T];if(!S)return;let O=Object.entries(S).find(([se,Se])=>Se&&typeof Se==="object"&&(o in Se));if(!O)return;let[C,L]=O,Q=L[o],x=typeof Q==="string"?Q:Q?.model||Q?.target||Q,P=w.modelToTable[x]||x,z=w.primaryKeys[T]??"id";F(P,`with${a} (target table)`);let ae=`${a}(${P}.${u})`,we;if(C==="hasMany"||C==="hasOne"){let se=`${T.endsWith("s")?T.slice(0,-1):T}_id`;F(se,`with${a} (foreign key)`),we=`(SELECT ${ae} FROM ${P} WHERE ${P}.${se} = ${T}.${z})`}else if(C==="belongsToMany"){let se=w?E(w,T,o,{singularize:he,models:w.models}):null,Se=he(T),ke=he(P),Oe=se?.pivotTable??[Se,ke].sort().join("_"),Be=se?.fkParent??`${Se}_id`,ie=se?.fkRelated??`${ke}_id`,ot=w.primaryKeys[P]??"id";F(Oe,`with${a} (pivot table)`),F(Be,`with${a} (foreign key)`),F(ie,`with${a} (related key)`),we=`(SELECT ${ae} FROM ${Oe} JOIN ${P} ON ${P}.${ot} = ${Oe}.${ie} WHERE ${Oe}.${Be} = ${T}.${z})`}else return;at(`${we} AS ${o}_${a.toLowerCase()}_${u}`)},wt=()=>{if(Le.size===0)return;let a=[];for(let[o,u]of Le.entries()){let T=Ce(o);if(!T)continue;for(let O of u)F(O,"withPivot");let S=u.map((O)=>`${T.pivotTable}.${O} AS pivot_${O}`);a.push(...S)}if(a.length>0){let o=a.join(", ");at(o)}};return new Proxy({distinct(){return y=y.replace(/^SELECT\s+/i,"SELECT DISTINCT "),q=null,this},distinctOn(...a){let o=a.map(String).join(", ");return y=y.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${o}) `),q=null,this},selectRaw(a,...o){let u=ze(a,"selectRaw(fragment)",o),T=y.indexOf(" FROM ");if(T!==-1)y=`${y.substring(0,T)}, ${u}${y.substring(T)}`;else y+=`, ${u}`;return q=null,this},rowNumber(a="row_number",o,u){let T=[];if(o){let L=Array.isArray(o)?o:[o];T.push(`PARTITION BY ${L.join(", ")}`)}if(u&&u.length)T.push(`ORDER BY ${u.map(([L,Q])=>`${L} ${Q==="desc"?"DESC":"ASC"}`).join(", ")}`);let O=`ROW_NUMBER() ${T.length?`OVER (${T.join(" ")})`:"OVER ()"} AS ${a}`,C=y.indexOf(" FROM ");if(C!==-1)y=`${y.substring(0,C)}, ${O}${y.substring(C)}`;else y+=`, ${O}`;return q=null,this},denseRank(a="dense_rank",o,u){let T=Array.isArray(o)?o:o?[o]:[],S=[];if(T.length)S.push(`PARTITION BY ${T.join(", ")}`);if(u&&u.length)S.push(`ORDER BY ${u.map(([Q,x])=>`${Q} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let C=`DENSE_RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${a}`,L=y.indexOf(" FROM ");if(L!==-1)y=`${y.substring(0,L)}, ${C}${y.substring(L)}`;else y+=`, ${C}`;return q=null,this},rank(a="rank",o,u){let T=Array.isArray(o)?o:o?[o]:[],S=[];if(T.length)S.push(`PARTITION BY ${T.join(", ")}`);if(u&&u.length)S.push(`ORDER BY ${u.map(([Q,x])=>`${Q} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let C=`RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${a}`,L=y.indexOf(" FROM ");if(L!==-1)y=`${y.substring(0,L)}, ${C}${y.substring(L)}`;else y+=`, ${C}`;return q=null,this},over(a,o,u={}){return Me(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 Me(`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 Me(`LEAD(${u.join(", ")})`,o.alias??`${a}_lead`,o.partitionBy,o.orderBy),this},sumOver(a,o={}){return Me(`SUM(${a})`,o.alias??`${a}_sum`,o.partitionBy,o.orderBy),this},avgOver(a,o={}){return Me(`AVG(${a})`,o.alias??`${a}_avg`,o.partitionBy,o.orderBy),this},countOver(a="*",o={}){return Me(`COUNT(${a})`,o.alias??"count_over",o.partitionBy,o.orderBy),this},minOver(a,o={}){return Me(`MIN(${a})`,o.alias??`${a}_min`,o.partitionBy,o.orderBy),this},maxOver(a,o={}){return Me(`MAX(${a})`,o.alias??`${a}_max`,o.partitionBy,o.orderBy),this},firstValue(a,o={}){return Me(`FIRST_VALUE(${a})`,o.alias??`${a}_first`,o.partitionBy,o.orderBy),this},lastValue(a,o={}){return Me(`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($t),T=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(y),S=T?T[1]:"",O=y.indexOf(" FROM ");if(O!==-1)y=`SELECT ${S}${u.join(", ")}${y.substring(O)}`;else y=`SELECT ${S}${u.join(", ")} FROM ${h}`;return q=null,this},addSelect(...a){if(!a.length)return this;let o=a.map($t),u=y.indexOf(" FROM ");if(u!==-1)y=`${y.substring(0,u)}, ${o.join(", ")}${y.substring(u)}`;else y+=`, ${o.join(", ")}`;return q=null,this},with(...a){if(!w||!a||a.length===0)return this;let o=[];for(let x of a){if(!x)continue;if(typeof x==="string")o.push({name:x});else if(typeof x==="object"&&!Array.isArray(x))for(let[P,z]of Object.entries(x))if(typeof z==="function")o.push({name:P,callback:z});else o.push({name:P})}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 T=String(h),S=new Set,O=new Set,C=new Map,L=(x)=>{let P=w.relations?.[x];if(!P)return[];return[...Object.keys(P.hasOne||{}),...Object.keys(P.hasMany||{}),...Object.keys(P.belongsTo||{}),...Object.keys(P.belongsToMany||{}),...Object.keys(P.hasOneThrough||{}),...Object.keys(P.hasManyThrough||{}),...Object.keys(P.morphOne||{}),...Object.keys(P.morphMany||{}),...Object.keys(P.morphToMany||{}),...Object.keys(P.morphedByMany||{})]},Q=(x,P,z=0,ae)=>{let we=e.relations.maxDepth??10;if(z>=we)throw Error(`[query-builder] Maximum relationship depth (${we}) exceeded at '${P}'. Consider using separate queries or increasing maxDepth.`);let se=w.relations?.[x];if(!se)return x;let Se=(le)=>{if(e.softDeletes?.enabled&&e.softDeletes?.defaultFilter){let ue=e.softDeletes.column||"deleted_at";return` AND ${le}.${ue} IS NULL`}return""},ke=(le)=>{if(!ae)return"";let ue=[],ge=(de,Ne,We)=>{F(String(de),"with() constraint column");let Ze=$e(Ne,"with() constraint operator");ue.push(`${le}.${String(de)} ${Ze} ${Ke(We)}`)},Te=(de)=>()=>{throw Error(`[query-builder] with('${P}', ...): ${de} 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.)`)},fe={where:(de,Ne,We)=>{if(Array.isArray(de))ge(de[0],de[1],de[2]);else if(de&&typeof de==="object")for(let Ze of Object.keys(de))ge(Ze,"=",de[Ze]);else if(Ne!==void 0&&We!==void 0)ge(de,Ne,We);else if(Ne!==void 0)ge(de,"=",Ne);return fe},whereIn:(de,Ne)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IN (${Ne.map(Ke).join(", ")})`),fe),whereNull:(de)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IS NULL`),fe),whereNotNull:(de)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IS NOT NULL`),fe),orderBy:Te("orderBy()"),limit:Te("limit()"),offset:Te("offset()"),take:Te("take()")};return ae(fe),ue.length?` AND ${ue.join(" AND ")}`:""},Oe=()=>{let le=(Te)=>{let fe=Te?.[P];return fe?w.modelToTable[fe]:void 0},ue=(Te)=>{let fe=Te?.[P],de=typeof fe==="string"?fe:fe?.model;return de?w.modelToTable[de]:void 0},ge=(Te)=>{let fe=Te?.[P];return fe?.target?w.modelToTable[fe.target]:void 0};return le(se?.hasOne)||le(se?.hasMany)||le(se?.belongsTo)||ue(se?.belongsToMany)||ge(se?.hasOneThrough)||ge(se?.hasManyThrough)||le(se?.morphOne)||le(se?.morphMany)||le(se?.morphToMany)||le(se?.morphedByMany)},Be=Oe()??(w.modelToTable[P]||w.tableToModel[P]?w.modelToTable[P]??P:P),ie=String(Be);if(!Be||!Oe()&&!w.modelToTable[P]&&!w.tableToModel[P]){let le=L(x);if(le.length>0&&!le.includes(P)){let ue=` Available relationships: ${le.join(", ")}`;throw Error(`[query-builder] Relationship '${P}' not found on table '${x}'.${ue}`)}}if(e.relations.detectCycles!==!1){let le=`${x}->${ie}`;if(S.has(le))throw Error(`[query-builder] Circular relationship detected: ${le}. This would cause an infinite loop.`);S.add(le)}if(!ie||ie===x)return x;let ot=se?.hasOneThrough?.[P]||se?.hasManyThrough?.[P];if(ot){let{through:le,target:ue}=ot,ge=w.modelToTable[le]||le,Te=w.modelToTable[ue]||ue,fe=w.primaryKeys[x]??"id",de=w.primaryKeys[ge]??"id",Ne=`${he(x)}_id`,We=`${he(ge)}_id`;return M(`LEFT JOIN ${ge} ON ${ge}.${Ne} = ${x}.${fe} LEFT JOIN ${Te} ON ${Te}.${We} = ${ge}.${de}`),H.add(ge),H.add(Te),Te}if(Boolean(se?.belongsToMany?.[P])){let le=E(w,x,P,{singularize:he,models:w.models}),ue=le?.pivotTable??[he(x),he(ie)].sort().join("_"),ge=w.primaryKeys[x]??"id",Te=w.primaryKeys[ie]??"id",fe=le?.fkParent??`${he(x)}_id`,de=le?.fkRelated??`${he(ie)}_id`;return M(`LEFT JOIN ${ue} ON ${ue}.${fe} = ${x}.${ge} LEFT JOIN ${ie} ON ${ie}.${Te} = ${ue}.${de}${ke(ie)}`),H.add(ue),H.add(ie),ie}if(Boolean(se?.morphToMany?.[P])){let le=P,ue=`${he(ie)}_${le}`,ge=w.primaryKeys[x]??"id",Te=w.primaryKeys[ie]??"id",fe=`${le}_type`,de=`${le}_id`,Ne=`${he(ie)}_id`,We=Ke(w.tableToModel[x]||x);return M(`LEFT JOIN ${ue} ON ${ue}.${de} = ${x}.${ge} AND ${ue}.${fe} = ${We} LEFT JOIN ${ie} ON ${ie}.${Te} = ${ue}.${Ne}`),H.add(ue),H.add(ie),ie}if(Boolean(se?.morphedByMany?.[P])){let le=se.morphedByMany?.[P]||P,ue=w.modelToTable[le]||le,ge=he(x),Te=`${he(ue)}_${ge}`,fe=w.primaryKeys[x]??"id",de=w.primaryKeys[ue]??"id",Ne=`${ge}_type`,We=`${ge}_id`,Ze=`${he(ue)}_id`,Qt=Ke(w.tableToModel[ue]||ue);return M(`LEFT JOIN ${Te} ON ${Te}.${Ze} = ${x}.${fe} LEFT JOIN ${ue} ON ${ue}.${de} = ${Te}.${We} AND ${Te}.${Ne} = ${Qt}`),H.add(Te),H.add(ue),ue}if(Boolean(se?.belongsTo?.[P])){let le=`${he(ie)}_id`,ue=w.primaryKeys[ie]??"id";return M(`LEFT JOIN ${ie} ON ${x}.${le} = ${ie}.${ue}${ke(ie)}`),H.add(ie),ie}let It=Boolean(se?.morphOne?.[P]),xt=Boolean(se?.morphMany?.[P]);if(It||xt){let le=`${P}_type`,ue=`${P}_id`,ge=w.primaryKeys[x]??"id",Te=Ke(w.tableToModel[x]||x);return M(`LEFT JOIN ${ie} ON ${ie}.${ue} = ${x}.${ge} AND ${ie}.${le} = ${Te}`),H.add(ie),ie}let Lt=`${he(x)}_id`,Pt=w.primaryKeys[x]??"id",qt=`${Se(ie)}${ke(ie)}`;return M(`LEFT JOIN ${ie} ON ${ie}.${Lt} = ${x}.${Pt}${qt}`),H.add(ie),ie};for(let x of o){let P=x.name.trim();if(x.callback)C.set(P,x.callback);let z=P.split("."),ae=T,we=0;for(let se of z){if(!se||se.trim().length===0)continue;let Se=se.trim(),ke=C.get(Se);ae=Q(ae,Se,we,ke)||ae,we++}O.add(P)}if(Le.size>0){let x=[];for(let[P,z]of Le.entries()){let ae=Ce(P);if(!ae)continue;let we=z.map((se)=>`${ae.pivotTable}.${se} AS pivot_${se}`);x.push(...we)}if(x.length>0){let P=x.join(", ");at(P)}}return q=null,this},whereHas(a,o){if(!w)return this;let u=String(h),T=w.relations?.[u];if(!T)throw Error(`[query-builder] No relationships defined for table '${u}'`);let S=Object.entries(T).find(([z,ae])=>ae&&typeof ae==="object"&&(a in ae));if(!S)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[O,C]=S,L=C[a],Q=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[Q]||Q,P;if(O==="hasMany"||O==="hasOne"){let z=w.primaryKeys[u]??"id";P=yt(u,x,z,o)}else if(O==="belongsTo"){let z=w.primaryKeys[x]??"id";P=Tt(u,x,z,o)}else if(O==="belongsToMany"){let z=w.primaryKeys[u]??"id",ae=w.primaryKeys[x]??"id";P=ht(u,x,z,ae,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereHas`);return I("WHERE",`EXISTS (${P})`),this},whereDoesntHave(a,o){if(!w)return this;let u=String(h),T=w.relations?.[u];if(!T)throw Error(`[query-builder] No relationships defined for table '${u}'`);let S=Object.entries(T).find(([z,ae])=>ae&&typeof ae==="object"&&(a in ae));if(!S)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[O,C]=S,L=C[a],Q=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[Q]||Q,P;if(O==="hasMany"||O==="hasOne"){let z=w.primaryKeys[u]??"id";P=yt(u,x,z,o)}else if(O==="belongsTo"){let z=w.primaryKeys[x]??"id";P=Tt(u,x,z,o)}else if(O==="belongsToMany"){let z=w.primaryKeys[u]??"id",ae=w.primaryKeys[x]??"id";P=ht(u,x,z,ae,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereDoesntHave`);return I("WHERE",`NOT EXISTS (${P})`),this},has(a){if(!w)return this;let o=String(h),u=w.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let T=Object.entries(u).find(([P,z])=>z&&typeof z==="object"&&(a in z));if(!T)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[S,O]=T,C=O[a],L=typeof C==="string"?C:C?.model||C?.target||C,Q=w.modelToTable[L]||L,x;if(S==="hasMany"||S==="hasOne"){let P=w.primaryKeys[o]??"id";x=yt(o,Q,P)}else if(S==="belongsTo"){let P=w.primaryKeys[Q]??"id";x=Tt(o,Q,P)}else if(S==="belongsToMany"){let P=w.primaryKeys[o]??"id",z=w.primaryKeys[Q]??"id";x=ht(o,Q,P,z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for has`);return I("WHERE",`EXISTS (${x})`),this},doesntHave(a){if(!w)return this;let o=String(h),u=w.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let T=Object.entries(u).find(([P,z])=>z&&typeof z==="object"&&(a in z));if(!T)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[S,O]=T,C=O[a],L=typeof C==="string"?C:C?.model||C?.target||C,Q=w.modelToTable[L]||L,x;if(S==="hasMany"||S==="hasOne"){let P=w.primaryKeys[o]??"id";x=yt(o,Q,P)}else if(S==="belongsTo"){let P=w.primaryKeys[Q]??"id";x=Tt(o,Q,P)}else if(S==="belongsToMany"){let P=w.primaryKeys[o]??"id",z=w.primaryKeys[Q]??"id";x=ht(o,Q,P,z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for doesntHave`);return I("WHERE",`NOT EXISTS (${x})`),this},withCount(...a){if(!w||!a||a.length===0)return this;let o=String(h);for(let u of a){let T=w.relations?.[o];if(!T)continue;let S=Object.entries(T).find(([we,se])=>se&&typeof se==="object"&&(u in se));if(!S)continue;let[O,C]=S,L=C[u],Q=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[Q]||Q,P=w.primaryKeys[o]??"id",z;if(O==="hasMany"||O==="hasOne")z=Nt(o,x,P);else if(O==="belongsToMany")z=At(o,x,P,u);else continue;let ae=`${u}_count`;at(`${z} AS ${ae}`)}return this},withSum(a,o){return gt("SUM",a,o),this},withAvg(a,o){return gt("AVG",a,o),this},withMax(a,o){return gt("MAX",a,o),this},withMin(a,o){return gt("MIN",a,o),this},applyPivotColumns(){return wt(),this},withPivot(a,...o){if(!w)return this;let u=String(h),T=Ce(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${u}'`);let S=o&&o.length>0?o:T.hasConfig?T.pivotColumns:[];if(S.length===0)return this;if(Le.set(a,S),T.hasConfig)ve.add(a);return wt(),this},wherePivot(a,o,u,T){if(!w)return this;let S=Ce(a);if(!S)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(S.pivotTable,"wherePivot (pivot table)"),F(o,"wherePivot (column)"),st(S);let O=T===void 0?"=":String(u),C=T===void 0?u:T,L=f.length+1,Q=`${S.pivotTable}.${o} ${O} ${t(L)}`;if(f.push(C),k("AND",Q),S.hasConfig)ve.add(a);return this},wherePivotIn(a,o,u){if(!w||!Array.isArray(u))return this;let T=Ce(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(T.pivotTable,"wherePivotIn (pivot table)"),F(o,"wherePivotIn (column)"),st(T);let S=s(u.length,f.length+1),O=l(`${T.pivotTable}.${o}`,u,!1,S);if(f.push(...u),k("AND",O),T.hasConfig)ve.add(a);return this},wherePivotNotIn(a,o,u){if(!w||!Array.isArray(u)||u.length===0)return this;let T=Ce(a);if(!T)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);F(T.pivotTable,"wherePivotNotIn (pivot table)"),F(o,"wherePivotNotIn (column)"),st(T);let S=s(u.length,f.length+1),O=`${T.pivotTable}.${o} NOT IN (${S})`;if(f.push(...u),k("AND",O),T.hasConfig)ve.add(a);return this},wherePivotNull(a,o){if(!w)return this;let u=Ce(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);if(F(u.pivotTable,"wherePivotNull (pivot table)"),F(o,"wherePivotNull (column)"),st(u),k("AND",`${u.pivotTable}.${o} IS NULL`),u.hasConfig)ve.add(a);return this},wherePivotNotNull(a,o){if(!w)return this;let u=Ce(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(h)}'`);if(F(u.pivotTable,"wherePivotNotNull (pivot table)"),F(o,"wherePivotNotNull (column)"),st(u),k("AND",`${u.pivotTable}.${o} IS NOT NULL`),u.hasConfig)ve.add(a);return this},where(a,o,u){if(typeof a==="string"&&o!==void 0){F(String(a),"where(column)"),$e(o,"where(operator)");let T=String(o).toLowerCase();if(T==="in"||T==="not in"){let C=Array.isArray(u)?u:[u],L=s(C.length,f.length+1),Q=l(c(String(a)),C,T==="not in",L);return f.push(...C),k("AND",Q),this}let S=Ue(c(String(a)),T,u,"where");if(S)return k("AND",S),this;let O=f.length+1;return f.push(u),k("AND",`${c(String(a))} ${String(o)} ${t(O)}`),this}if(Array.isArray(a)){let[T,S,O]=a,C=String(T);F(C,"where(column)");let L=$e(S,"where(operator)");if(L==="in"||L==="not in"){let Q=Array.isArray(O)?O:[O],x=s(Q.length,f.length+1),P=l(c(C),Q,L==="not in",x);f.push(...Q),k("AND",P)}else{let Q=Ue(c(C),L,O,"where");if(Q)return k("AND",Q),this;let x=f.length+1;f.push(O),k("AND",`${c(C)} ${L} ${t(x)}`)}return this}if(it(a))lt("where(expr)");if(Ge(a)){let T=Ye(a,f.length+1);return f.push(...T.parameters),k("AND",T.text),this}if(a&&typeof a==="object"&&!Fe(a)){let T=a,S=Object.keys(T),O=[];for(let C of S){F(C,"where(column)");let L=T[C];if(Array.isArray(L)){let Q=s(L.length,f.length+1);O.push(l(c(C),L,!1,Q)),f.push(...L)}else{let Q=f.length+1;O.push(`${c(C)} = ${t(Q)}`),f.push(L)}}if(O.length>0)k("AND",O.length>1?`(${O.join(" AND ")})`:O[0]);return this}if(Fe(a))return k("AND",a.raw),this;if(typeof a==="function")return G("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 F(String(a),"whereNull(column)"),k("AND",`${String(a)} IS NULL`),this},whereNotNull(a){return F(String(a),"whereNotNull(column)"),k("AND",`${String(a)} IS NOT NULL`),this},orWhereNull(a){return F(String(a),"orWhereNull(column)"),k("OR",`${String(a)} IS NULL`),this},orWhereNotNull(a){return F(String(a),"orWhereNotNull(column)"),k("OR",`${String(a)} IS NOT NULL`),this},whereBetween(a,o,u){F(String(a),"whereBetween(column)");let T=f.length+1;return f.push(o,u),k("AND",`${String(a)} BETWEEN ${t(T)} AND ${t(T+1)}`),this},orWhereBetween(a,o,u){F(String(a),"orWhereBetween(column)");let T=f.length+1;return f.push(o,u),k("OR",`${String(a)} BETWEEN ${t(T)} AND ${t(T+1)}`),this},whereExists(a){return k("AND",`EXISTS (${a.toSQL()})`),this},orWhereExists(a){return k("OR",`EXISTS (${a.toSQL()})`),this},whereGroup(a){return G("AND",a),this},orWhereGroup(a){return G("OR",a),this},__whereState(){return{body:D(A),params:[...f]}},__sqlState(){return{sql:Xe(W()),params:[...f]}},whereJsonContains(a,o){F(String(a),"whereJsonContains(column)");let u=e.dialect,T=f.length+1;if(u==="postgres"){let O=typeof o==="number"||typeof o==="boolean"?`to_jsonb(${t(T)})`:t(T);if(e.sql?.jsonContainsMode==="function")k("AND",`jsonb_contains(${a}, ${O})`);else k("AND",`${a} @> ${O}`);f.push(o)}else if(n(u))k("AND",`JSON_CONTAINS(${a}, ${t(T)})`),f.push(JSON.stringify(o));else if(Array.isArray(o)){let S=o.map((O,C)=>`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(T+C)})`);k("AND",`(${S.join(" AND ")})`);for(let O of o)f.push(O)}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 k("AND",`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(T)})`),f.push(o);return this},whereJsonPath(a,o,u){if($e(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 T=e.dialect,S=f.length+1;if(T==="postgres")k("AND",`${a} ${o} ${t(S)}`);else if(n(T))k("AND",`JSON_EXTRACT(${a}) ${o} ${t(S)}`);else k("AND",`json_extract(${a}) ${o} ${t(S)}`);return f.push(u),this},whereLike(a,o,u=!1){let T=t(f.length+1);return I("WHERE",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},whereILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("WHERE",`${String(a)} ILIKE ${u}`);else I("WHERE",`LOWER(${String(a)}) LIKE LOWER(${u})`);return f.push(o),q=null,this},orWhereLike(a,o,u=!1){let T=t(f.length+1);return I("OR",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},orWhereILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("OR",`${String(a)} ILIKE ${u}`);else I("OR",`LOWER(${String(a)}) LIKE LOWER(${u})`);return f.push(o),q=null,this},whereNotLike(a,o,u=!1){let T=t(f.length+1);return I("WHERE",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},whereNotILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("WHERE",`${String(a)} NOT ILIKE ${u}`);else I("WHERE",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return f.push(o),q=null,this},orWhereNotLike(a,o,u=!1){let T=t(f.length+1);return I("OR",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?T:`LOWER(${T})`}`),f.push(o),q=null,this},orWhereNotILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")I("OR",`${String(a)} NOT ILIKE ${u}`);else I("OR",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return f.push(o),q=null,this},whereAny(a,o,u){if(a.length===0)return k("AND",`(${Ht})`),this;let T=f.length+1,S=a.map((O,C)=>`${O} ${o} ${t(T+C)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`(${S.join(" OR ")})`),this},whereAll(a,o,u){if(a.length===0)return this;let T=f.length+1,S=a.map((O,C)=>`${O} ${o} ${t(T+C)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`(${S.join(" AND ")})`),this},whereNone(a,o,u){if(a.length===0)return this;let T=f.length+1,S=a.map((O,C)=>`${O} ${o} ${t(T+C)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`NOT (${S.join(" OR ")})`),this},whereNotBetween(a,o,u){F(String(a),"whereNotBetween(column)");let T=f.length+1;return f.push(o,u),k("AND",`${a} NOT BETWEEN ${t(T)} AND ${t(T+1)}`),this},whereDate(a,o,u){F(a,"whereDate(column)");let T=u instanceof Date?u.toISOString():typeof u==="string"?u:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof u}`)})(),S=f.length+1;return f.push(T),k("AND",`${a} ${o} ${t(S)}`),this},whereRaw(a,...o){return k("AND",ze(a,"whereRaw(fragment)",o)),this},orWhereRaw(a,...o){return k("OR",ze(a,"orWhereRaw(fragment)",o)),this},whereColumn(a,o,u){return F(a,"whereColumn(left)"),F(u,"whereColumn(right)"),k("AND",`${a} ${o} ${u}`),this},orWhereColumn(a,o,u){return F(a,"orWhereColumn(left)"),F(u,"orWhereColumn(right)"),k("OR",`${a} ${o} ${u}`),this},whereIn(a,o){if(F(String(a),"whereIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!1,u);f.push(...o),k("AND",T)}else _("AND",a,o,!1);return this},orWhereIn(a,o){if(F(String(a),"orWhereIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!1,u);f.push(...o),k("OR",T)}else _("OR",a,o,!1);return this},whereNotIn(a,o){if(F(String(a),"whereNotIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!0,u);f.push(...o),k("AND",T)}else _("AND",a,o,!0);return this},orWhereNotIn(a,o){if(F(String(a),"orWhereNotIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),T=l(a,o,!0,u);f.push(...o),k("OR",T)}else _("OR",a,o,!0);return this},whereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return k("AND",`(${o})`),this},orWhereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return k("OR",`(${o})`),this},andWhere(a,o,u){return V(this,"AND","andWhere",a,o,u)},orWhere(a,o,u){return V(this,"OR","orWhere",a,o,u)},orderBy(a,o="asc"){let u=o==="asc"?"ASC":"DESC",T=c(String(a));return y=ye.ORDER_BY.test(y)?`${y}, ${T} ${u}`:`${y} ORDER BY ${T} ${u}`,q=null,this},orderByDesc(a){return y=ye.ORDER_BY.test(y)?`${y}, ${a} DESC`:`${y} ORDER BY ${a} DESC`,q=null,this},inRandomOrder(){let a=e.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return y=ye.ORDER_BY.test(y)?`${y}, ${a}`:`${y} ORDER BY ${a}`,q=null,this},reorder(a,o="asc"){return y=y.replace(/ORDER BY[\s\S]*$/i,""),y+=` ORDER BY ${a} ${o==="asc"?"ASC":"DESC"}`,q=null,this},latest(a){let o=a??e.timestamps.defaultOrderColumn;return y=ye.ORDER_BY.test(y)?`${y}, ${o} DESC`:`${y} ORDER BY ${o} DESC`,q=null,this},oldest(a){let o=a??e.timestamps.defaultOrderColumn;return y=ye.ORDER_BY.test(y)?`${y}, ${o} ASC`:`${y} ORDER BY ${o} ASC`,q=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=ye.LIMIT.test(y)?y.replace(ye.LIMIT,` LIMIT ${a}`):`${y} LIMIT ${a}`,q=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=ye.OFFSET.test(y)?y.replace(ye.OFFSET,` OFFSET ${a}`):`${y} OFFSET ${a}`,q=null,this},join(a,o,u,T){return F(a,"join(table)"),Pe(o,"join(onLeft)"),Pe(T,"join(onRight)"),$e(u,"join(operator)"),M(`JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},joinSub(a,o,u,T,S){return F(o,"joinSub(alias)"),Pe(u,"joinSub(onLeft)"),Pe(S,"joinSub(onRight)"),$e(T,"joinSub(operator)"),M(`JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${T} ${S}`),H.add(o),this},innerJoin(a,o,u,T){return F(a,"innerJoin(table)"),Pe(o,"innerJoin(onLeft)"),Pe(T,"innerJoin(onRight)"),$e(u,"innerJoin(operator)"),M(`INNER JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},leftJoin(a,o,u,T){return F(a,"leftJoin(table)"),Pe(o,"leftJoin(onLeft)"),Pe(T,"leftJoin(onRight)"),$e(u,"leftJoin(operator)"),M(`LEFT JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},leftJoinSub(a,o,u,T,S){return F(o,"leftJoinSub(alias)"),Pe(u,"leftJoinSub(onLeft)"),Pe(S,"leftJoinSub(onRight)"),$e(T,"leftJoinSub(operator)"),M(`LEFT JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${T} ${S}`),H.add(o),this},rightJoin(a,o,u,T){return F(a,"rightJoin(table)"),Pe(o,"rightJoin(onLeft)"),Pe(T,"rightJoin(onRight)"),$e(u,"rightJoin(operator)"),M(`RIGHT JOIN ${a} ON ${o} ${u} ${T}`),H.add(a),this},crossJoin(a){return F(a,"crossJoin(table)"),M(`CROSS JOIN ${a}`),H.add(a),this},crossJoinSub(a,o){return F(o,"crossJoinSub(alias)"),M(`CROSS JOIN (${String(a.toSQL())}) AS ${o}`),H.add(o),this},selectAllRelations(){if(!j)return this;let a=String(h),o=Object.keys(j[a]?.columns??{}),u=[];if(o.length>0)u.push(d`${d(a)}.*`);for(let T of H){let S=Object.keys(j[T]?.columns??{});for(let O of S){let C=e.aliasing.relationColumnAliasFormat==="camelCase"?`${T}_${O}`.replace(/_([a-z])/g,(L,Q)=>Q.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${T}.${O}`:`${T}_${O}`;u.push(d`${d(`${T}.${O}`)} AS ${d(C)}`)}}if(u.length>0){let T=o.length>0?`${a}.*`:"",S=[];for(let L of H){let Q=Object.keys(j[L]?.columns??{});for(let x of Q){let P=e.aliasing.relationColumnAliasFormat==="camelCase"?`${L}_${x}`.replace(/_([a-z])/g,(z,ae)=>ae.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${L}.${x}`:`${L}_${x}`;S.push(`${L}.${x} AS ${P}`)}}let O=[T,...S].filter(Boolean).join(", "),C=y.indexOf(" FROM ");if(C!==-1)y=`SELECT ${O}${y.substring(C)}`;else y=`SELECT ${O} FROM ${a}`;q=null}return this},groupBy(...a){if(a.length)y=ye.GROUP_BY.test(y)?`${y}, ${a.map((o)=>c(String(o))).join(", ")}`:`${y} GROUP BY ${a.map((o)=>c(String(o))).join(", ")}`,q=null;return this},groupByRaw(a,...o){let u=ze(a,"groupByRaw(fragment)",o);return y=ye.GROUP_BY.test(y)?`${y}, ${u}`:`${y} GROUP BY ${u}`,q=null,this},having(a){let o=K?"AND":"HAVING";if(Array.isArray(a)){let u=f.length+1;y=`${y} ${o} ${a[0]} ${a[1]} ${t(u)}`,f.push(a[2]),K=!0,q=null}else if(a&&typeof a==="object"&&!("raw"in a)){let u=Object.keys(a),T=u.length;if(T){let S=f.length,O=Array.from({length:T});for(let C=0;C<T;C++){let L=u[C];O[C]=`${L} = ${t(S+C+1)}`,f.push(a[L])}y=`${y} ${o} ${O.join(" AND ")}`,K=!0,q=null}}else if(a&&typeof a.raw<"u")y+=` ${o} ${a.raw}`,K=!0,q=null;return this},havingRaw(a,...o){let u=ze(a,"havingRaw(fragment)",o);return y+=` ${K?"AND":"HAVING"} ${u}`,K=!0,q=null,this},orderByRaw(a,...o){let u=ze(a,"orderByRaw(fragment)",o);return y=ye.ORDER_BY.test(y)?`${y}, ${u}`:`${y} ORDER BY ${u}`,q=null,this},$call(a){return a(this),this},union(a){return ee("UNION",a),this},unionAll(a){return ee("UNION ALL",a),this},intersect(a){return ee("INTERSECT",a),this},intersectAll(a){return ee("INTERSECT ALL",a),this},except(a){return ee("EXCEPT",a),this},exceptAll(a){return ee("EXCEPT ALL",a),this},forPage(a,o){let u=Math.max(1,Math.floor(a)),T=Math.max(1,Math.floor(o));return y+=` LIMIT ${T} OFFSET ${(u-1)*T}`,q=null,this},toSQL(){let a=Xe(W());return{sql:a,toString:()=>a,execute:()=>R().execute(),values:()=>R().values(),raw:()=>R().raw()}},async value(a){let o=J(""," LIMIT 1"),u=await ne(o,"select",{signal:Z,timeoutMs:te}),[T]=u;return T?.[a]},async pluck(a,o){let u=await ne(R(),"select",{signal:Z,timeoutMs:te});if(o){let T={};for(let S of u){let O=String(S?.[o]);if(Object.prototype.hasOwnProperty.call(T,O))throw Error(`[query-builder] pluck(${a}, ${o}): duplicate key '${O}' \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.`);T[O]=S?.[a]}return T}return u.map((T)=>T?.[a])},async exists(){let a=J("SELECT EXISTS (",") as e"),o=await ne(a,"select",{signal:Z,timeoutMs:te}),[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=Xe(W()),ae=[...f],we=await u.tx.unsafe(`SELECT COUNT(*) as c FROM (${z}) as sub`,ae),se=Number(we?.[0]?.c??0),Se=Math.max(1,Math.ceil(se/a)),ke=Math.max(1,Math.min(o,Se)),Oe=(ke-1)*a;return{data:await u.tx.unsafe(`${z} LIMIT ${a} OFFSET ${Oe}`,ae),meta:{perPage:a,page:ke,total:se,lastPage:Se}}}let T=J("SELECT COUNT(*) as c FROM (",") as sub"),S=await ne(T,"select",{signal:Z,timeoutMs:te}),[O]=S,C=Number(O?.c??0),L=Math.max(1,Math.ceil(C/a)),Q=Math.max(1,Math.min(o,L)),x=(Q-1)*a;return{data:await ne(J("",` LIMIT ${t(f.length+1)} OFFSET ${t(f.length+2)}`,[a,x]),"select",{signal:Z,timeoutMs:te}),meta:{perPage:a,page:Q,total:C,lastPage:L}}},async simplePaginate(a,o=1){let u=Math.max(1,o),T=(u-1)*a,S=await ne(J("",` LIMIT ${t(f.length+1)} OFFSET ${t(f.length+2)}`,[a+1,T]),"select",{signal:Z,timeoutMs:te}),O=S.length>a;return{data:O?S.slice(0,a):S,meta:{perPage:a,page:u,hasMore:O}}},async cursorPaginate(a,o,u="id",T="asc"){if(!Number.isInteger(a)||a<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${a}`);let S=(Array.isArray(u)?u:[u]).map(String);for(let Be of S)F(Be,"cursorPaginate(column)");let O=T==="asc"?">":"<",C=T==="asc"?"ASC":"DESC",L=[...f],Q="";if(o!==void 0&&o!==null)if(Array.isArray(u)){let Be=o.map((ie)=>(L.push(ie),t(L.length)));Q=`(${S.join(", ")}) ${O} (${Be.join(", ")})`}else L.push(o),Q=`${S[0]} ${O} ${t(L.length)}`;let x=Xe(Q?W({conn:"AND",sql:Q}):W()),P=S.map((Be)=>`${Be} ${C}`).join(", ");if(Ft(x))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${P} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let z=L.length>0?N(`${x} ORDER BY ${P} LIMIT ${a+1}`,L):N(`${x} ORDER BY ${P} LIMIT ${a+1}`),ae=await ne(z,"select",{signal:Z,timeoutMs:te}),we=ae.length>a,se=ae.slice(0,a),Se=se[se.length-1],ke=we&&Se?Array.isArray(u)?u.map((Be)=>Se[Be]):Se[u]:null,Oe=se.length?Array.isArray(u)?u.map((Be)=>se[0]?.[Be]):se[0]?.[u]:null;return{data:se,meta:{perPage:a,nextCursor:ke??null,prevCursor:Oe}}},async chunk(a,o){let u=1;while(!0){let{data:T,meta:S}=await this.paginate(a,u);if(T.length===0)break;if(await o(T),u>=S.lastPage)break;u+=1}},async chunkById(a,o="id",u){let T;while(!0){let{data:S,meta:O}=await this.cursorPaginate(a,T,o,"asc");if(S.length===0)break;if(u)await u(S);if(T=O.nextCursor,!T)break}},async eachById(a,o="id",u){await this.chunkById(a,o,async(T)=>{for(let S of T)await u?.(S)})},withTimeout(a){return te=Math.max(1,Math.floor(a)),this},abort(a){return Z=a,this},withTrashed(){return ce=!0,me=!1,this},onlyTrashed(){ce=!0,me=!0;let a=e.softDeletes?.column||"deleted_at";return k("AND",`${h}.${a} IS NOT NULL`),this},scope(a,o){let u=String(h),S=w?.scopes?.[u]?.[a];if(S)return S(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(R())),this},dd(){throw console.log(String(R())),Error("Dump and Die")},cache(a=60000){return dt=a,Ie=!0,this},async explain(){let a=J("EXPLAIN ");return await ne(a,"select",{signal:Z,timeoutMs:te})},simple(){return R().simple()},toText(){return W()},async get(){let a=be(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||ut(a));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!o){let L=B._prepareStatement;if(L){let Q=L(W());return rt(f.length>0?Q.all(...f):Q.all())}}let u=W();if(q=f.length>0?N(u,f):N(u),!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!o){let L=R()._stmt,Q=R()._params;if(L)return rt(Q&&Q.length>0?L.all(...Q):L.all());return rt(await R().execute())}if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z)return rt(await ne(R(),"select"));let T=R();if(e.softDeletes?.enabled&&e.softDeletes.defaultFilter&&!ce){let L=e.softDeletes.column,Q=String(h);if((j?Boolean(j[Q]?.columns?.[L]):!0)&&!ye.DELETED_AT.test(W()))I("WHERE",`${String(L)} IS ${me?"NOT ":""}NULL`),T=R()}let S=Ie&&!p?.inTransaction,O=S?Ut(B,W(),f):"";if(S){let L=mt.get(O);if(L)return L}let C=await ne(T,"select",{signal:Z,timeoutMs:te});if(S)mt.set(O,C,dt);return rt(C)},async executeTakeFirst(){let a=await ne(R(),"select",{signal:Z,timeoutMs:te});return nt(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=be(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||ut(a));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!o){let S=B._prepareStatement;if(S){let O=W(),C=O.includes(" LIMIT ")?O:`${O} LIMIT 1`,L=S(C),Q=f.length>0?L.all(...f):L.all();return nt(Q[0])}}let u=await ne(J(""," LIMIT 1"),"select",{signal:Z,timeoutMs:te}),[T]=u;return nt(T)},async firstOrFail(){let a=await this.first();if(!a)throw Error("Record not found");return a},async find(a){let o=w?.primaryKeys[String(h)]??"id",u=await ne(J("",` WHERE ${De(o)} = ${t(f.length+1)} LIMIT 1`,[a]),"select",{signal:Z,timeoutMs:te}),[T]=u;return T},async findOrFail(a){let o=await this.find(a);if(!o)throw Error("Record not found");return o},async findMany(a){let o=w?.primaryKeys[String(h)]??"id";return await ne(J("",` WHERE ${l(De(String(o)),a,!1,s(a.length,f.length+1))}`,a),"select",{signal:Z,timeoutMs:te})},async*lazy(){let a,o=w?.primaryKeys[String(h)]??"id";while(!0){let T=await(a==null?d`${R()} ORDER BY ${d(String(o))} ASC LIMIT 100`:d`${R()} WHERE ${d(String(o))} > ${a} ORDER BY ${d(String(o))} ASC LIMIT 100`).execute();if(T.length===0)break;for(let S of T)yield S;if(a=T[T.length-1]?.[o],a==null)break}},async*lazyById(){let a=w?.primaryKeys[String(h)]??"id",o;while(!0){let T=await(o==null?d`${R()} ORDER BY ${d(String(a))} ASC LIMIT 100`:d`${R()} WHERE ${d(String(a))} > ${o} ORDER BY ${d(String(a))} ASC LIMIT 100`).execute();if(T.length===0)break;for(let S of T)yield S;if(o=T[T.length-1]?.[a],o==null)break}},pipe(a){return a(this)},async count(){let a=W(),o=a.indexOf(" FROM "),u=/ GROUP BY /i.test(a),T;if(u)T=`SELECT COUNT(*) as c FROM (${a}) AS _bqb_count_sub`;else if(o!==-1)T=`SELECT COUNT(*) as c${a.substring(o)}`;else T=`SELECT COUNT(*) as c FROM ${h}`;let S=be(),O=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||ut(S));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!O){let x=B._prepareStatement;if(x){let P=x(T),z=f.length>0?P.all(...f):P.all();return Number(z[0]?.c??0)}}let C=f.length>0?N(T,f):N(T),L=await ne(C,"select",{signal:Z,timeoutMs:te}),[Q]=L;return Number(Q?.c??0)},async avg(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT AVG(${a}) as a${o.substring(u)}`:`SELECT AVG(${a}) as a FROM ${h}`,S=be(),O=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||ut(S));if(!e.softDeletes?.enabled&&!Ie&&!te&&!Z&&!O){let x=B._prepareStatement;if(x){let P=x(T),z=f.length>0?P.all(...f):P.all();return Number(z[0]?.a??0)}}let C=f.length>0?N(T,f):N(T),L=await ne(C,"select",{signal:Z,timeoutMs:te}),[Q]=L;return Number(Q?.a??0)},async sum(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT SUM(${a}) as s${o.substring(u)}`:`SELECT SUM(${a}) as s FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await ne(S,"select",{signal:Z,timeoutMs:te}),[C]=O;return Number(C?.s??0)},async max(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT MAX(${a}) as m${o.substring(u)}`:`SELECT MAX(${a}) as m FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await ne(S,"select",{signal:Z,timeoutMs:te}),[C]=O;return C?.m},async min(a){let o=W(),u=o.indexOf(" FROM "),T=u!==-1?`SELECT MIN(${a}) as m${o.substring(u)}`:`SELECT MIN(${a}) as m FROM ${h}`,S=f.length>0?N(T,f):N(T),O=await ne(S,"select",{signal:Z,timeoutMs:te}),[C]=O;return C?.m},lockForUpdate(){return y+=" FOR UPDATE",q=null,this},sharedLock(){let a=e.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return y+=` ${a}`,q=null,this},withCTE(a,o){return F(a,"withCTE(name)"),y=`WITH ${a} AS (${String(o.toSQL())}) ${y}`,q=null,this},withRecursive(a,o){return F(a,"withRecursive(name)"),y=`WITH RECURSIVE ${a} AS (${String(o.toSQL())}) ${y}`,q=null,this},execute(){return ne(R(),"select",{signal:Z,timeoutMs:te})},values(){return R().values()},toParams(){return[...f]},__rawState(){return{sql:Xe(W()),params:[...f]}},__hasPredicate(){return A.length>0||v},raw(){return R().raw()},get rows(){return},get row(){return},cancel(){try{R().cancel()}catch{}}},{get(a,o,u){let T=Reflect.get(a,o,u);if(T!==void 0)return T;if(typeof o==="string"&&(o.startsWith("where")||o.startsWith("orWhere")||o.startsWith("andWhere"))){let S=o.startsWith("orWhere"),O=o.startsWith("andWhere"),C=`${String(h)}|${o}`,L=He.get(C);if(L===void 0){let x=o.replace(/^(?:or|and)?where/i,"");if(!x)He.set(C,""),L="";else{let P=x.charAt(0).toLowerCase()+x.slice(1),z=x.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ae=j?Object.keys(j[String(h)]?.columns??{}):[];L=[z,P,P.toLowerCase()].find((we)=>ae.includes(we))??z,He.set(C,L)}}if(L==="")return()=>u;let Q=L;return(x)=>{if(Array.isArray(x)){let P=s(x.length,f.length+1);I(S?"OR":O?"AND":"WHERE",`${Q} IN (${P})`),f.push(...x)}else{let P=t(f.length+1);I(S?"OR":O?"AND":"WHERE",`${Q} = ${P}`),f.push(x)}return u}}return Reflect.get(a,o,u)}})}return{configure(h){return _e(h),this},id(h){if(!ye.IDENTIFIER.test(h))throw Error(`[query-builder] Invalid identifier: '${h}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return B(String(h))},ids(...h){for(let g of h)if(!ye.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 B(h)},select(h,...g){return Je(h,g)},selectFrom(h){return Je(h)},selectFromSub(h,g){function d(R){return()=>{throw Error(`[query-builder] selectFromSub(...).${R}() is not supported. Apply ${R}() 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.")}}F(String(g),"selectFromSub(alias)");let y=typeof h.__rawState==="function"?h.__rawState():null,A=h.toSQL(),f=y?.sql??(typeof A==="string"?A:A?.sql??String(A)),Y=y?.params??(Array.isArray(A?.values)?A.values:[]),v=`SELECT * FROM (${f}) AS ${String(g)}`,K=(R,J,k,I)=>{let U=[...R],W=(G,V,ee)=>{F(G,"selectFromSub where(column)");let M=$e(V,"selectFromSub where(operator)");if(M==="in"||M==="not in"){let te=Array.isArray(ee)?ee:[ee],Z=s(te.length,U.length+1);return U.push(...te),`${G} ${M.toUpperCase()} (${Z})`}let H=t(U.length+1);return U.push(ee),`${G} ${M} ${H}`},_;if(typeof J==="string"&&k!==void 0)_=W(J,k,I);else if(Array.isArray(J)&&J.length===3)_=W(J[0],J[1],J[2]);else if(J&&typeof J==="object"){let G=Object.entries(J).map(([V,ee])=>W(V,"=",ee));_=G.length>1?`(${G.join(" AND ")})`:G[0]}else return{clause:null,params:R};return{clause:_,params:U}};function q(R,J,k,I=""){let U=D(J),W=U?`${R} WHERE ${U}${I}`:`${R}${I}`,_=()=>k.length>0?N(W,k):N(W),G=(M,H,te,Z)=>{let ce=K(k,H,te,Z);return ce.clause===null?q(R,J,k,I):q(R,[...J,{conn:M,sql:ce.clause}],ce.params,I)},V=(M,H)=>{let te=[],Z=[...k],ce=(Le)=>(ve,dt,he)=>{let Ce=K(Z,ve,dt,he);if(Ce.clause!==null)te.push({conn:Le,sql:Ce.clause}),Z=Ce.params;return me},me={where:ce("AND"),andWhere:ce("AND"),orWhere:ce("OR")};H(me);let Ie=D(te);if(!Ie)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return q(R,[...J,{conn:M,sql:`(${Ie})`}],Z,I)},ee={distinct(){return q(R.replace(/^SELECT\s+/i,"SELECT DISTINCT "),J,k,I)},distinctOn(...M){let H=M.map(String).join(", ");return q(R.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${H}) `),J,k,I)},selectRaw(M,...H){let te=ze(M,"selectFromSub.selectRaw(fragment)",H),Z=R.indexOf(" FROM "),ce=Z!==-1?`${R.slice(0,Z)}, ${te}${R.slice(Z)}`:`${R}, ${te}`;return q(ce,J,k,I)},$call(M){return M(this)??this},where(M,H,te){return G("AND",M,H,te)},andWhere(M,H,te){return G("AND",M,H,te)},orWhere(M,H,te){return G("OR",M,H,te)},whereGroup(M){return V("AND",M)},orWhereGroup(M){return V("OR",M)},orderBy(M,H="asc"){F(String(M),"selectFromSub.orderBy(column)");let te=H==="asc"?"ASC":"DESC",Z=ye.ORDER_BY.test(I)?`${I}, ${M} ${te}`:`${I} ORDER BY ${M} ${te}`;return q(R,J,k,Z)},limit(M){if(!Number.isInteger(M)||M<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${M}`);let H=ye.LIMIT.test(I)?I.replace(ye.LIMIT,` LIMIT ${M}`):`${I} LIMIT ${M}`;return q(R,J,k,H)},offset(M){if(!Number.isInteger(M)||M<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${M}`);let H=ye.OFFSET.test(I)?I.replace(ye.OFFSET,` OFFSET ${M}`):`${I} OFFSET ${M}`;return q(R,J,k,H)},toSQL(){return xe(_(),W)},async execute(){return ne(_(),"select")},async executeTakeFirst(){let M=await ne(_(),"select");return Array.isArray(M)?M[0]:M},async executeTakeFirstOrThrow(){let M=await ne(_(),"select"),H=Array.isArray(M)?M[0]:M;if(!H)throw Error("Record not found");return H},async get(){return ne(_(),"select")},async first(){let M=await ne(_(),"select");return Array.isArray(M)?M[0]:M},async firstOrFail(){let M=await ne(_(),"select"),H=Array.isArray(M)?M[0]:M;if(!H)throw Error("No rows found");return H},async count(){let M=k.length>0?N(`SELECT COUNT(*) as c FROM (${W}) as sub`,k):N(`SELECT COUNT(*) as c FROM (${W}) as sub`),H=await ne(M,"select");return Number(H?.[0]?.c??0)},async exists(){let M=k.length>0?N(`SELECT EXISTS(${W}) as e`,k):N(`SELECT EXISTS(${W}) as e`),H=await ne(M,"select");return Boolean(H?.[0]?.e)},async doesntExist(){return!await ee.exists()},values(){return _().values()},raw(){return _().raw()},cancel(){try{_().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:(M)=>M(ee),when:d("when"),tap:()=>ee,dump:()=>ee,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>_().simple(),toText:()=>W,toParams:()=>[...k],withTimeout:()=>ee,abort:()=>ee,lockForUpdate:()=>ee,sharedLock:()=>ee,withCTE:()=>ee,withRecursive:()=>ee,cache:()=>ee,clone:()=>ee,withTrashed:()=>ee,onlyTrashed:()=>ee,scope:()=>ee,get rows(){return[]},get row(){return}};return ee}return q(v,[],Y)},insertInto(h){let g,d="",y=[],A=[],f=!1,Y=()=>K?[]:{changes:0,lastInsertRowid:0},v=()=>{let I=async()=>{return},U=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>v(),andWhere:()=>v(),orWhere:()=>v(),orderBy:()=>v(),limit:()=>v(),offset:()=>v(),toSQL:()=>xe(null,""),execute:async()=>[],get:async()=>[],first:I,executeTakeFirst:I,firstOrFail:U,executeTakeFirstOrThrow:U}},K=e.dialect==="postgres",q=(I)=>{let W=I.flat(2).map(String).filter(Boolean),_=W.length>0&&!W.includes("*")?W.map((ee)=>R(ee)).join(", "):"*",G=async()=>{let ee=await ne(N(d,y),"insert"),M=Number(ee?.lastInsertRowid??0),H=Math.max(1,Number(ee?.affectedRows??1)),te=A.filter((me)=>me!==void 0&&me!==null),Z=M>0?N(`SELECT ${_} FROM ${R(String(h))} WHERE ${R("id")} >= ? AND ${R("id")} < ? ORDER BY ${R("id")} ASC`,[M,M+H]):te.length>0?N(`SELECT ${_} FROM ${R(String(h))} WHERE ${R("id")} IN (${te.map(()=>"?").join(", ")}) ORDER BY ${R("id")} ASC`,te):null;if(!Z)return[];let ce=await Z.execute();return Array.isArray(ce)?ce:[]},V=async()=>(await G())[0];return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>xe(N(d,y),d),execute:G,get:G,first:V,executeTakeFirst:V,async firstOrFail(){let ee=await V();if(!ee)throw Error("Insert with RETURNING returned no rows");return ee},async executeTakeFirstOrThrow(){let ee=await V();if(!ee)throw Error("Insert with RETURNING returned no rows");return ee}}},R=K?(I)=>`"${String(I).replace(/"/g,'""')}"`:n(e.dialect)?(I)=>`\`${String(I).replace(/`/g,"``")}\``:(I)=>`"${String(I).replace(/"/g,'""')}"`,J=K?"postgres":n(e.dialect)?"mysql":"sqlite",k=K?(I)=>`$${I+1}`:(I)=>"?";return{values(I){let U=Ee(String(h),Array.isArray(I)?I:[I]),W=U.length;if(A=U.map((Z)=>Z?.id),W===0)return f=!0,g=null,d="",y.length=0,this;f=!1;let _=U[0],G=Object.keys(_),V=G.length,ee=W*V;y.length=ee;let M=W===1&&V>0&&typeof h==="string",H=M?oe?.get(h):void 0,te=H?.quoteStyle===J&&H.columns.length===V;if(te){for(let Z=0;Z<V;Z++)if(H.columns[Z]!==G[Z]){te=!1;break}}if(te){d=H.sql;for(let Z=0;Z<V;Z++)y[Z]=_[G[Z]]}else if(W===1)if(!K){let Z=R(G[0]),ce="?";y[0]=_[G[0]];for(let me=1;me<V;me++)Z+=`,${R(G[me])}`,ce+=",?",y[me]=_[G[me]];d=`INSERT INTO ${R(h)}(${Z})VALUES(${ce})`}else{let Z=G.map((ce)=>R(ce)).join(",");d=`INSERT INTO ${R(h)}(${Z})VALUES(`;for(let ce=0;ce<V;ce++){if(ce>0)d+=",";d+=k(ce),y[ce]=_[G[ce]]}d+=")"}else{let Z=G.map((me)=>R(me)).join(",");d=`INSERT INTO ${R(h)}(${Z})VALUES`;let ce=0;for(let me=0;me<W;me++){let Ie=U[me];if(me===0)d+="(";else d+="),(";for(let Le=0;Le<V;Le++){if(Le>0)d+=",";d+=k(ce),y[ce++]=Ie[G[Le]]}}d+=")"}if(M&&!te&&d.length<=8192){if(oe??=new Map,oe.size>=32&&!oe.has(h)){let Z=oe.keys().next().value;if(Z!==void 0)oe.delete(Z)}oe.set(h,{columns:G,quoteStyle:J,sql:d})}if(!B._prepareStatement)g=N(d,y);return this},returning(...I){if(f)return v();if(n(e.dialect))return q(I);let U=`${d} RETURNING ${I.join(", ")}`,W=N(U,y),_=async()=>{let G=await ne(W,"insert");return Array.isArray(G)?G[0]:G};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>xe(W,U),execute:()=>ne(W,"insert"),get:()=>ne(W,"insert"),first:_,executeTakeFirst:_,async firstOrFail(){let G=await _();if(!G)throw Error("Insert with RETURNING returned no rows");return G},async executeTakeFirstOrThrow(){let G=await _();if(!G)throw Error("Insert with RETURNING returned no rows");return G}}},toSQL(){if(f)return xe(null,"");if(!g)g=N(d,y);return xe(g,d)},execute(){if(f)return Promise.resolve(Y());let I=be();if(!(I&&(I.onQueryStart||I.onQueryEnd||I.onQueryError||I.startSpan||I.beforeCreate||I.afterCreate||ut(I)))){let W=B._prepareStatement;if(W){let _=W(d);return y.length>0?_.run(...y):_.run()}}if(!g)g=N(d,y);return ne(g,"insert")},async executeTakeFirst(){if(f)return Y();if(!g)g=N(d,y);return await ne(g,"insert")},async executeTakeFirstOrThrow(){if(f)throw Error("Insert failed");if(!g)g=N(d,y);let I=await ne(g,"insert");if(!I)throw Error("Insert failed");return I},returningAll(){return this.returning("*")}}},updateTable(h){let g,d=[],y=(v)=>{let K=String(v);if(n(e.dialect))return`\`${K.replace(/`/g,"``")}\``;return`"${K.replace(/"/g,'""')}"`},A=`UPDATE ${y(String(h))}`,f=!1,Y=(v)=>{A=`${A} ${f?"AND":"WHERE"} ${v}`,f=!0};return{set(v){let K=Ee(String(h),[v])[0],q=Object.keys(K),R=q.length,J=Array.from({length:R});for(let k=0;k<R;k++){let I=q[k],U=K[I];if(it(U))lt(`set(${I})`);if(Fe(U))J[k]=`${y(I)} = ${U.raw}`;else if(Ge(U)){let W=Ye(U,d.length+1);J[k]=`${y(I)} = ${W.text}`,d.push(...W.parameters)}else J[k]=`${y(I)} = ${t(d.length+1)}`,d.push(U)}return A=`${A} SET ${J.join(", ")}`,g=N(A,d),this},where(v,K,q){if(K!==void 0&&(typeof v==="string"||Fe(v)||Ge(v))){let R=$e(K,"updateTable.where"),J;if(typeof v==="string")J=y(v);else if(Fe(v))J=v.raw;else{let U=Ye(v,d.length+1);J=U.text,d.push(...U.parameters)}if(R.toLowerCase()==="in"||R.toLowerCase()==="not in"){let U=Array.isArray(q)?q:[q],W=s(U.length,d.length+1);return Y(`${J} ${R.toUpperCase()} (${W})`),d.push(...U),g=N(A,d),this}let k=Ue(J,R,q,"updateTable.where");if(k)return Y(k),g=N(A,d),this;let I=d.length+1;return Y(`${J} ${R} ${t(I)}`),d.push(q),g=N(A,d),this}if(Array.isArray(v)){let[R,J,k]=v,I=$e(J,"updateTable.where");if(I.toLowerCase()==="in"||I.toLowerCase()==="not in"){let _=Array.isArray(k)?k:[k],G=s(_.length,d.length+1);return Y(`${y(String(R))} ${I.toUpperCase()} (${G})`),d.push(..._),g=N(A,d),this}let U=Ue(y(String(R)),I,k,"updateTable.where");if(U)return Y(U),g=N(A,d),this;let W=d.length+1;return Y(`${y(String(R))} ${I} ${t(W)}`),d.push(k),g=N(A,d),this}if(it(v))lt("updateTable.where(expr)");if(Fe(v))return Y(v.raw),g=N(A,d),this;if(Ge(v)){let R=Ye(v,d.length+1);return Y(R.text),d.push(...R.parameters),g=N(A,d),this}if(v&&typeof v==="object"){let R=Object.keys(v);if(R.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 J=R.map((k)=>pt(y(k),v[k],d));return Y(J.join(" AND ")),g=N(A,d),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${v===null?"null":typeof v}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(v){return Y(`${y(String(v))} IS NULL`),g=N(A,d),this},whereNotNull(v){return Y(`${y(String(v))} IS NOT NULL`),g=N(A,d),this},returning(...v){let K=this,q=()=>`${A} RETURNING ${v.join(", ")}`,R=()=>d.length>0?N(q(),d):N(q()),J=async()=>{let _=/\sWHERE\s/i.test(A),G=_?A.slice(A.search(/\sWHERE\s/i)+1):"",V=d.slice(d.length-(G.match(/\?|\$\d+/g)?.length??0)),ee=y("id"),M=await(V.length>0?N(`SELECT ${ee} FROM ${y(String(h))}${_?` ${G}`:""}`,V):N(`SELECT ${ee} FROM ${y(String(h))}${_?` ${G}`:""}`)).execute().catch(()=>[]),H=(Array.isArray(M)?M:[]).map((ce)=>ce?.id).filter((ce)=>ce!==void 0&&ce!==null);if(await ne(d.length>0?N(A,d):N(A),"update"),H.length===0)return[];let te=`SELECT ${v.join(", ")} FROM ${y(String(h))} WHERE ${ee} IN (${H.map(()=>"?").join(", ")})`,Z=await N(te,H).execute();return Array.isArray(Z)?Z:[]},k=()=>n(e.dialect)?J():ne(R(),"update"),I=async()=>{let _=await k();return Array.isArray(_)?_[0]:_},U=(_)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${_}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},W={where:(..._)=>(K.where(..._),W),andWhere:(..._)=>(K.where(..._),W),whereNull:(..._)=>(K.whereNull(..._),W),whereNotNull:(..._)=>(K.whereNotNull(..._),W),orWhere:U("orWhere"),orderBy:U("orderBy"),limit:U("limit"),offset:U("offset"),toSQL:()=>xe(R(),q()),execute:k,get:k,first:I,executeTakeFirst:I,async firstOrFail(){let _=await I();if(!_)throw Error("Update with RETURNING returned no rows");return _},async executeTakeFirstOrThrow(){let _=await I();if(!_)throw Error("Update with RETURNING returned no rows");return _}};return W},toSQL(){if(!g)g=d.length>0?N(A,d):N(A);return xe(g,A)},async execute(){let v=await ne(g,"update");return Qe(v)},async executeTakeFirst(){return{numUpdatedRows:Qe(await ne(g,"update"))}},async executeTakeFirstOrThrow(){let v=Qe(await ne(g,"update"));if(v===0)throw Error("No rows updated");return{numUpdatedRows:v}},returningAll(){return this.returning("*")}}},deleteFrom(h){let g=(R)=>{let J=String(R);if(n(e.dialect))return`\`${J.replace(/`/g,"``")}\``;return`"${J.replace(/"/g,'""')}"`},y=`DELETE FROM ${g(String(h))}`,A=null,f=[],Y=null,v=!1,K=(R)=>{y+=` ${v?"AND":"WHERE"} ${R}`,v=!0},q=()=>{if(A===null)A=f.length>0?N(y,f):N(y);return A};return{where(R,J,k){if(Y=R,typeof R==="string"&&J!==void 0){let I=$e(J,"deleteFrom.where");if(I.toLowerCase()==="in"||I.toLowerCase()==="not in"){let _=Array.isArray(k)?k:[k],G=s(_.length,f.length+1);return K(`${g(R)} ${I.toUpperCase()} (${G})`),f.push(..._),A=null,this}let U=Ue(g(R),I,k,"deleteFrom.where");if(U)return K(U),A=null,this;let W=f.length+1;return K(`${g(R)} ${I} ${t(W)}`),f.push(k),A=null,this}if(Array.isArray(R)){let[I,U,W]=R,_=$e(U,"deleteFrom.where");if(_.toLowerCase()==="in"||_.toLowerCase()==="not in"){let ee=Array.isArray(W)?W:[W],M=s(ee.length,f.length+1);return K(`${g(String(I))} ${_.toUpperCase()} (${M})`),f.push(...ee),A=null,this}let G=Ue(g(String(I)),_,W,"deleteFrom.where");if(G)return K(G),A=null,this;let V=f.length+1;return K(`${g(String(I))} ${_} ${t(V)}`),f.push(W),A=null,this}if(it(R))lt("deleteFrom.where(expr)");if(Fe(R))return K(R.raw),A=null,this;if(Ge(R)){let I=Ye(R,f.length+1);return K(I.text),f.push(...I.parameters),A=null,this}if(R&&typeof R==="object"){let I=Object.keys(R);if(I.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 U=I.map((W)=>pt(g(W),R[W],f));return K(U.join(" AND ")),A=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${R===null?"null":typeof R}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(R){return K(`${g(String(R))} IS NULL`),A=null,this},whereNotNull(R){return K(`${g(String(R))} IS NOT NULL`),A=null,this},returning(...R){let J=this,k=()=>`${y} RETURNING ${R.join(", ")}`,I=()=>f.length>0?N(k(),f):N(k()),U=async()=>{await be()?.beforeDelete?.({table:String(h),where:Y});let V=n(e.dialect)?await(async()=>{let ee=y.slice(y.search(/\sFROM\s/i)+1),M=`SELECT ${R.join(", ")} ${ee}`,H=await(f.length>0?N(M,f):N(M)).execute();return await ne(f.length>0?N(y,f):N(y),"delete"),Array.isArray(H)?H:[]})():await ne(I(),"delete");try{await be()?.afterDelete?.({table:String(h),where:Y,result:V})}catch{}return V},W=async()=>{let V=await U();return Array.isArray(V)?V[0]:V},_=(V)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${V}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},G={where:(...V)=>(J.where(...V),G),andWhere:(...V)=>(J.where(...V),G),whereNull:(...V)=>(J.whereNull(...V),G),whereNotNull:(...V)=>(J.whereNotNull(...V),G),orWhere:_("orWhere"),orderBy:_("orderBy"),limit:_("limit"),offset:_("offset"),toSQL:()=>xe(I(),k()),execute:()=>U(),get:()=>U(),first:W,executeTakeFirst:W,async firstOrFail(){let V=await W();if(!V)throw Error("Delete with RETURNING returned no rows");return V},async executeTakeFirstOrThrow(){let V=await W();if(!V)throw Error("Delete with RETURNING returned no rows");return V}};return G},toSQL(){return xe(q(),y)},async execute(){try{await be()?.beforeDelete?.({table:String(h),where:Y})}catch(J){throw J}let R=Qe(await ne(q(),"delete"));try{await be()?.afterDelete?.({table:String(h),where:Y,result:R})}catch{}return R},async executeTakeFirst(){return{numDeletedRows:Qe(await ne(q(),"delete"))}},async executeTakeFirstOrThrow(){let R=Qe(await ne(q(),"delete"));if(R===0)throw Error("No rows deleted");return{numDeletedRows:R}},returningAll(){return this.returning("*")}}},table(h){let g=this;return{insert(d){return g.insertInto(h).values(d)},update(d){return g.updateTable(h).set(d)},delete(){return g.deleteFrom(h)},select(...d){if(d.length===0)return g.selectFrom(h);return g.select(h,...d)}}},sql:B,raw(h,...g){if(typeof h==="string")return Wt(h,g);return B(h,...g)},simple(h,...g){return B(h,...g).simple()},async advisoryLock(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_advisory_lock($1)",[g]);await ne(d,"raw");return}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT GET_LOCK(?, -1) AS ok",[g]);await ne(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(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_try_advisory_lock($1) as ok",[g]),y=await ne(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT GET_LOCK(?, 0) AS ok",[g]),y=await ne(d,"raw");return Number(y?.[0]?.ok)===1}return!1},async advisoryUnlock(h){if(e.dialect==="postgres"){let g=pe(h),d=N("SELECT pg_advisory_unlock($1) as ok",[g]),y=await ne(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let g=`bqb:${String(h)}`,d=N("SELECT RELEASE_LOCK(?) AS ok",[g]),y=await ne(d,"raw");return Number(y?.[0]?.ok)===1}return!1},unsafe(h,g){return Jt(h,g),B.unsafe(h,g)},deferInsert:B.deferInsert?.bind(B),flushDeferredInserts:B.flushDeferredInserts?.bind(B),file(h,g){return B.file(h,g)},async reserve(){let h=await r.reserve(),g=i({sql:h,meta:w,schema:j,hooks:p?.hooks});return g.release=()=>h.release(),g},async close(h){await r.close(h)},async listen(h,g){},async unlisten(h){},async notify(h,g){},async copyTo(h,g){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(h,g,d){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let h=N("SELECT 1");return await ne(h,"select"),!0}catch{return!1}},async waitForReady(h){let g=Math.max(1,h?.attempts??10),d=Math.max(10,h?.delayMs??100);for(let y=0;y<g;y++){if(await this.ping())return;await new Promise((A)=>setTimeout(A,d))}throw Error("Database not ready after waiting")},async transaction(h,g){let y={...p?.txDefaults,...g},A=p?.sql??r,f=p?.inTransaction===!0,Y=f&&typeof A?.savepoint==="function"?"savepoint":"begin",v=async(J)=>{y.logger?.({type:"start",attempt:J});let k=Date.now();return await A[Y](async(I)=>{let U=i({sql:I,meta:w,schema:j,hooks:p?.hooks,inTransaction:!0});if(y?.isolation&&!f){let G=y.isolation,V=G==="read committed"?"READ COMMITTED":G==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(e.dialect==="postgres")await I.unsafe(`SET TRANSACTION ISOLATION LEVEL ${V}`);else if(n(e.dialect))await I.unsafe(`SET TRANSACTION ISOLATION LEVEL ${V}`);else if(G!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${G}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(y?.readOnly)if(e.dialect==="postgres")await I.unsafe("SET TRANSACTION READ ONLY");else if(n(e.dialect))await I.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let W=await h(U),_=Date.now()-k;return y.logger?.({type:"commit",attempt:J,durationMs:_}),W})},K=Math.max(0,y?.retries??0),q=0,R;for(;;)try{R=await v(q+1);break}catch(J){let k=Vt(J)||Gt(J,y.sqlStates);if(q<K&&k){q++,y?.onRetry?.(q,J);let I=rn(q,y.backoff);if(I>0)await Yt(I);continue}try{y.onRollback?.(J)}catch{}try{y.afterRollback?.()}catch{}throw J}return await y.afterCommit?.(),R},async savepoint(h){if(p?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let g=B;if(!g||typeof g.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await g.savepoint(async(d)=>{let y=i({sql:d,meta:w,schema:j,hooks:p?.hooks,inTransaction:!0});return await h(y)})},async beginDistributed(h,g){return await(p?.sql??r).beginDistributed(h,async(A)=>{let f=i({sql:A,meta:w,schema:j,hooks:p?.hooks});return await g(f)})},async commitDistributed(h){await r.commitDistributed(h)},async rollbackDistributed(h){await r.rollbackDistributed(h)},setTransactionDefaults(h){p={...p,txDefaults:{...p?.txDefaults,...h}}},transactional(h,g){return(...d)=>this.transaction((y)=>h(y,...d),g)},async insertOrIgnore(h,g){let d=Array.isArray(g)?g:[g];if(!d.length)return;let{colsSql:y,valuesSql:A,params:f}=ft(d),Y=De(String(h)),v=n(e.dialect)?`INSERT IGNORE INTO ${Y} (${y}) VALUES ${A}`:`INSERT INTO ${Y} (${y}) VALUES ${A} ON CONFLICT DO NOTHING`;return N(v,f).execute()},async insertGetId(h,g,d="id"){let{colsSql:y,valuesSql:A,params:f}=ft([g]),Y=De(String(h));if(n(e.dialect)){await N(`INSERT INTO ${Y} (${y}) VALUES ${A}`,f).execute();let[K]=await N("SELECT LAST_INSERT_ID() as id").execute();return K?.id}if(e.dialect==="sqlite"){let K=await N(`INSERT INTO ${Y} (${y}) VALUES ${A}`,f).execute();if(K?.lastInsertRowid!=null)return K.lastInsertRowid;let[q]=await N("SELECT last_insert_rowid() as id").execute();return q?.id}let[v]=await N(`INSERT INTO ${Y} (${y}) VALUES ${A} RETURNING ${De(String(d))} as id`,f).execute();return v?.id},async updateOrInsert(h,g,d){let y=De(String(h)),A=Object.keys(g),f=1,Y=A.map((k)=>`${De(k)} = ${t(f++)}`).join(" AND "),v=A.map((k)=>g[k]);if((await N(`SELECT 1 FROM ${y} WHERE ${Y} LIMIT 1`,v).execute()).length){let k=Object.keys(d),I=1,U=k.map((G)=>`${De(G)} = ${t(I++)}`).join(", "),W=A.map((G)=>`${De(G)} = ${t(I++)}`).join(" AND "),_=[...k.map((G)=>d[G]),...A.map((G)=>g[G])];return await N(`UPDATE ${y} SET ${U} WHERE ${W}`,_).execute(),!0}let{colsSql:q,valuesSql:R,params:J}=ft([{...g,...d}]);return await N(`INSERT INTO ${y} (${q}) VALUES ${R}`,J).execute(),!0},async upsert(h,g,d,y){let A=d.map((U)=>String(U)),f=(y??[]).map((U)=>String(U)),Y=g;if(!Y.length)return;let{colsSql:v,valuesSql:K,params:q}=ft(Y),R=De(String(h)),J=`INSERT INTO ${R} (${v}) VALUES ${K}`;if(n(e.dialect)){if(f.length===0)return N(`INSERT IGNORE INTO ${R} (${v}) VALUES ${K}`,q).execute();let U=f.map((W)=>`${De(W)} = VALUES(${De(W)})`).join(", ");return N(`${J} ON DUPLICATE KEY UPDATE ${U}`,q).execute()}let k=A.map(De).join(", ");if(f.length===0)return N(`${J} ON CONFLICT (${k}) DO NOTHING`,q).execute();let I=f.map((U)=>`${De(U)} = EXCLUDED.${De(U)}`).join(", ");return N(`${J} ON CONFLICT (${k}) DO UPDATE SET ${I}`,q).execute()},async save(h,g){let d=w?.primaryKeys[String(h)]??"id",y=g[d];if(y!=null)if(await this.selectFrom(h).find(y)){await this.updateTable(h).set(g).where({[d]:y}).execute();let f=await this.selectFrom(h).find(y);if(!f)throw Error("save() failed to retrieve updated row");return f}else return await this.create(h,g);return await this.create(h,g)},async remove(h,g){return await this.deleteFrom(h).where({id:g}).execute()},async find(h,g){return await this.selectFrom(h).find(g)},async findOrFail(h,g){return await this.selectFrom(h).findOrFail(g)},async findMany(h,g){return await this.selectFrom(h).findMany(g)},async latest(h,g){return await this.selectFrom(h).latest(g).first()},async oldest(h,g){return await this.selectFrom(h).oldest(g).first()},skip(h,g){return this.selectFrom(h).offset(g)},async rawQuery(h){let g=Date.now();try{be()?.onQueryStart?.({sql:h,kind:"raw"});let d=await B.unsafe(h);return be()?.onQueryEnd?.({sql:h,durationMs:Date.now()-g,kind:"raw"}),d}catch(d){throw be()?.onQueryError?.({sql:h,error:d,durationMs:Date.now()-g,kind:"raw"}),d}},async create(h,g){let d=w?.primaryKeys[String(h)]??"id";try{await be()?.beforeCreate?.({table:String(h),data:g})}catch(y){throw y}if(e.dialect==="postgres"){let y=B`INSERT INTO ${B(String(h))} ${B(g)} RETURNING ${B(String(d))} as id`,[A]=await y.execute();if(!A?.id)throw console.error(`create() failed to get insert ID for table ${String(h)}`),console.error("Inserted values:",g),Error(`create() failed to get insert ID for table ${String(h)}`);let f=await this.selectFrom(h).find(A.id);if(!f)throw console.error(`create() failed to retrieve inserted row for table ${String(h)} with id ${A.id}`),console.error("Inserted values:",g),Error(`create() failed to retrieve inserted row for table ${String(h)} with id ${A.id}`);try{await be()?.afterCreate?.({table:String(h),data:g,result:f})}catch{}return f}else{let y=await this.insertGetId(h,g,d);if(y==null)throw Error(`create() failed to get insert ID for table ${String(h)}`);let A=await this.selectFrom(h).find(y);if(!A)throw console.error(`create() failed to retrieve inserted row for table ${String(h)} with id ${y}`),console.error("Inserted values:",g),Error(`create() failed to retrieve inserted row for table ${String(h)} with id ${y}`);try{await be()?.afterCreate?.({table:String(h),data:g,result:A})}catch{}return A}},async createMany(h,g){if(!g?.length)return;let d=g[0],y=Object.keys(d),A=y.length,f=g.length,Y=Array.from({length:f*A}),v=n(e.dialect)?(R)=>`\`${String(R).replace(/`/g,"``")}\``:(R)=>`"${String(R).replace(/"/g,'""')}"`,K=`INSERT INTO ${v(String(h))}(${y.map(v).join(",")})VALUES`,q=0;for(let R=0;R<f;R++){if(R>0)K+=",";K+="(";let J=g[R];for(let k=0;k<A;k++){if(k>0)K+=",";K+=t(q+1),Y[q++]=J[y[k]]}K+=")"}return N(K,Y).execute()},async insertMany(h,g){if(!g?.length)return;let d=g[0],y=Object.keys(d),A=y.length,f=g.length,Y=f*A,v=Array(Y),K=e.dialect==="postgres",q;if(!K){let k=Array(A);for(let I=0;I<A;I++)k[I]="?";q=`(${k.join(",")})`}else q="";let R=Array(f+2);R[0]=`INSERT INTO ${h}(${y.join(",")})VALUES`;let J=0;if(!K){for(let k=0;k<f;k++){let I=g[k];R[k+1]=q;for(let U=0;U<A;U++)v[J++]=I[y[U]]}return N(R[0]+R.slice(1,f+1).join(","),v).execute()}for(let k=0;k<f;k++){let I=g[k],U=Array(A);for(let W=0;W<A;W++)U[W]=`$${J+1}`,v[J++]=I[y[W]];R[k+1]=`(${U.join(",")})`}return N(R[0]+R.slice(1,f+1).join(","),v).execute()},async updateMany(h,g,d){let y=Object.keys(d),A=y.length;if(A===0)return 0;let f=[],Y=Array.from({length:A});for(let K=0;K<A;K++)Y[K]=`${y[K]}=${t(K+1)}`,f.push(d[y[K]]);let v=`UPDATE ${h} SET ${Y.join(",")}`;if(Array.isArray(g)){let K=$e(String(g[1]),"updateMany");v+=` WHERE ${g[0]} ${K} ${t(f.length+1)}`,f.push(g[2])}else if(Fe(g))v+=` WHERE ${g.raw}`;else if(Ge(g)){let K=Ye(g,f.length+1);v+=` WHERE ${K.text}`,f.push(...K.parameters)}else if(g&&typeof g==="object"&&Object.keys(g).length>0){let K=Object.keys(g).map((q)=>pt(q,g[q],f));v+=` WHERE ${K.join(" AND ")}`}else if(g&&typeof g==="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 ${g===null?"null":typeof g}. Refusing to run an UPDATE with no WHERE \u2014 use updateTable(table).set(data).execute() if updating every row is intended.`);return N(v,f).execute()},async deleteMany(h,g){if(!Array.isArray(g)||g.length===0)return 0;let d=w?.primaryKeys[String(h)]??"id",y=g.length;if(e.dialect==="postgres"){let f=Array(y);for(let Y=0;Y<y;Y++)f[Y]=`$${Y+1}`;return N(`DELETE FROM ${h} WHERE ${d} IN (${f.join(",")})`,g).execute()}let A=Array(y);for(let f=0;f<y;f++)A[f]="?";return N(`DELETE FROM ${h} WHERE ${d} IN (${A.join(",")})`,g).execute()},async firstOrCreate(h,g,d){let y=await this.selectFrom(h).where(g).first();if(y)return y;return await this.create(h,{...g,...d})},async updateOrCreate(h,g,d){let y=await this.selectFrom(h).where(g).first();if(y){await this.updateTable(h).set(d).where(g).execute();let A=w?.primaryKeys[String(h)]??"id",f=y[A],Y=f!=null?await this.selectFrom(h).find(f):await this.selectFrom(h).where(g).first();if(!Y)throw Error("updateOrCreate() failed to retrieve updated row");return Y}return await this.create(h,{...g,...d})},async count(h,g){let d=g?B(String(g)):B`*`,y=B`SELECT COUNT(${d}) as c FROM ${B(String(h))}`,[A]=await y.execute();return Number(A?.c??0)},async sum(h,g){let d=B`SELECT SUM(${B(String(g))}) as s FROM ${B(String(h))}`,[y]=await d.execute();return Number(y?.s??0)},async avg(h,g){let d=B`SELECT AVG(${B(String(g))}) as a FROM ${B(String(h))}`,[y]=await d.execute();return Number(y?.a??0)},async min(h,g){let d=B`SELECT MIN(${B(String(g))}) as m FROM ${B(String(h))}`,[y]=await d.execute();return y?.m},async max(h,g){let d=B`SELECT MAX(${B(String(g))}) as m FROM ${B(String(h))}`,[y]=await d.execute();return y?.m},getRelationships(h){if(!w?.relations)return{};let g=w.relations[h];if(!g)return{};let d={};for(let[y,A]of Object.entries(g))if(A&&typeof A==="object"&&Object.keys(A).length>0)d[y]=A;return d},hasRelationship(h,g){if(!w?.relations)return!1;let d=w.relations[h];if(!d)return!1;return Object.values(d).some((y)=>y&&typeof y==="object"&&(g in y))},getRelationshipType(h,g){if(!w?.relations)return null;let d=w.relations[h];if(!d)return null;for(let[y,A]of Object.entries(d))if(A&&typeof A==="object"&&g in A)return y;return null},getRelationshipTarget(h,g){if(!w?.relations)return null;let d=w.relations[h];if(!d)return null;for(let[y,A]of Object.entries(d))if(A&&typeof A==="object"&&g in A){let f=A[g];if(typeof f==="string")return w.modelToTable[f]||f;else if(f&&typeof f==="object"){if("model"in f)return w.modelToTable[f.model]||f.model;if("target"in f)return w.modelToTable[f.target]||f.target}}return null}}}function Re(){mt.clear()}function Ae(p){mt.setMaxSize(p)}
|
|
3
3
|
export{E,In,en,c,Ct,Rt,i,Re,Ae};
|
package/dist/db.d.ts
CHANGED
|
@@ -79,6 +79,7 @@ export declare function resolvePoolOptions(pool?: PoolConfig): {
|
|
|
79
79
|
idleTimeout?: number
|
|
80
80
|
connectionTimeout?: number
|
|
81
81
|
maxLifetime?: number
|
|
82
|
+
prepare?: boolean
|
|
82
83
|
};
|
|
83
84
|
/**
|
|
84
85
|
* Returns a Bun SQL instance configured for the current dialect and database settings.
|
package/dist/src/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Z,ee,te,ne,I,re,ie,se,ae,L,oe,K,F,le,ce,j,ue,de,ct,Ue,ut,C,fe,o,me,he,ge,pe,h,dt,ft,mt,Ve,He,ht,w,R,Qe,A,ye,be,q,Te,W,we,U,V,M,H,Se,De,Ee,$e,Q,xe,ve,S,g,Dn,En,$n,gt,pt,yt,bt,Tt,xn,wt,Qt,vn,kn,Cn,Rn,St,An,Mn,Nn,ke,d,Dt,Et,$t,xt,vt,Gt,G,J,Ce,Jt,On,Pn,kt,Ge,zt,y,Je,Yt,ze,Xt,Bn,Zt,_n}from"../chunk-
|
|
2
|
+
import{Z,ee,te,ne,I,re,ie,se,ae,L,oe,K,F,le,ce,j,ue,de,ct,Ue,ut,C,fe,o,me,he,ge,pe,h,dt,ft,mt,Ve,He,ht,w,R,Qe,A,ye,be,q,Te,W,we,U,V,M,H,Se,De,Ee,$e,Q,xe,ve,S,g,Dn,En,$n,gt,pt,yt,bt,Tt,xn,wt,Qt,vn,kn,Cn,Rn,St,An,Mn,Nn,ke,d,Dt,Et,$t,xt,vt,Gt,G,J,Ce,Jt,On,Pn,kt,Ge,zt,y,Je,Yt,ze,Xt,Bn,Zt,_n}from"../chunk-284e3ka8.js";import{E,In,en,c,Ct,Rt,i,Re,Ae}from"../chunk-ygwkzhkh.js";import{At,u,z,x,Mt,Ye,v,Me,Xe,Ze,Ne,Nt,f,Y,Oe,et,Ot,tt,tn,nn}from"../chunk-9wck98bv.js";import{Pt,Bt,_t,It,Ln,Kn,Fn,Lt,Kt,jn,qn,rn,sn,an,on,ln,Ft,cn,un}from"../chunk-dj2eazhq.js";import{n,nt,e,P,rt,t,s,B,_e,dn,it,fn,a,Ie,jt,qt,mn,Le,Wt,Wn,Ut,Vt,k,_,hn,Fe,T,gn,pn,m,at}from"../chunk-3hwsz4q7.js";import{yn,bn,Tn,p,ot,lt,wn,We,Sn}from"../chunk-93ny6tvm.js";export{Lt as BelongsToManyRelationBuilder,ot as BrowserQueryBuilder,p as BrowserQueryError,Ut as DEFAULT_SQLITE_PRAGMAS,z as DynamoDBClient,At as DynamoDBDriverImpl,g as DynamoDBItemBuilder,Oe as DynamoDBMigrationDriver,Y as DynamoDBMigrationTracker,S as DynamoDBQueryBuilder,St as DynamoDBToolingAdapter,tt as EntityQueryBuilder,$t as GENERATED_MARKER,a as LibSQLError,f as MIGRATIONS_TABLE,Ye as Model,o as MySQLDriver,me as PostgresDriver,pe as SQLiteDriver,Zt as Seeder,he as SingleStoreDriver,gt as SingleTableManager,xn as SingleTablePatterns,yt as SingleTableQueryBuilder,pt as SingleTableRepository,y as UTC_CLOCK_DEFAULT,ge as VitessDriver,k as applySqliteBootstrapPragmas,Ve as auditSchemaDrift,Sn as browserAuth,lt as browserQuery,ke as buildDatabaseSchema,Ne as buildDynamoDBMigrationPlan,G as buildMigrationPlan,Dt as buildSchemaMeta,ee as cacheClear,ne as cacheConfig,te as cacheStats,Ge as canonicalStorageType,Je as canonicalizeDefault,xe as checkSchema,Bt as clearLocalModels,ln as clearModelRegistry,Re as clearQueryCache,e as config,yn as configureBrowser,Mt as configureModels,Ln as configureOrm,Ze as convertSchemaToDefinition,wn as createBrowserDb,We as createBrowserModel,x as createClient,nn as createDynamo,$n as createDynamoDBClient,u as createDynamoDBDriver,En as createDynamoDBItemBuilder,Dn as createDynamoDBQueryBuilder,An as createDynamoDBToolingAdapter,Pt as createFakerCompatLayer,Wt as createLibSQLSQL,et as createMigrationDriver,Kt as createModel,i as createQueryBuilder,Tt as createRepository,bt as createSingleTableManager,jn as createTableFromModel,L as dbInfo,K as dbOptimize,oe as dbStats,F as dbWipe,qt as decodeLibSQLValue,nt as defaultConfig,dn as defineConfig,cn as defineModel,Bn as defineModels,_n as defineSeeder,ae as dumpDatabase,tn as dynamo,jt as encodeLibSQLValue,Rt as escapeStringLiteral,R as executeMigration,Qe as executeMigrationWithReport,le as explain,U as explainAllQueries,ie as exportData,_t as extractChanges,It as extractInsertId,Xe as extractModelSchema,Me as extractTableDefinition,dt as familyOfDeclared,ft as familyOfSqlType,ce as file,He as formatSchemaDrift,De as freshDatabase,Mn as generateAccessPatterns,V as generateDiagram,ze as generateDiffOperations,Xt as generateDiffSql,Pn as generateDiffSqlString,w as generateMigration,ut as generateModelSource,Jt as generateSql,Ce as generateSqlFiles,On as generateSqlString,sn as getAllModels,bn as getBrowserConfig,B as getConfig,Fn as getDatabase,h as getDialectDriver,rn as getModel,an as getModelRegistry,t as getPlaceholder,s as getPlaceholders,on as hasModel,kt as hashMigrationPlan,v as hashTableDefinition,se as importData,pn as inflectSingular,j as inspectTable,de as introspect,C as introspectDatabase,Tn as isBrowser,Nt as isDefinitionEqual,xt as isGeneratedMigrationSql,Wn as isLibSQLConnection,it as isLibSQLUrl,Gt as isLosslessTypeChange,n as isMysqlLike,zt as isNarrowingChange,In as iterateAllPivots,Et as lastCreatedMigrationFiles,d as loadModels,fe as makeModel,Se as makeSeeder,Cn as marshallObject,ye as migrateGenerate,Te as migrateList,Ot as migrateModels,be as migrateRollback,q as migrateStatus,vt as migrationBody,Ue as modelNameForTable,W as modelShow,rt as normalizeDialectName,Yt as normalizeIndexPredicate,K as optimizeDatabase,Qt as parseStacksModels,we as ping,U as queryExplainAll,c as quoteColumnForDialect,en as raw,un as registerBrowserModels,Ft as registerModel,V as relationDiagram,Kn as releaseOrm,hn as resetConnection,A as resetDatabase,P as resolveDialect,wt as resolveKeyPattern,fn as resolveLibSQLEndpoint,_ as resolveLibSQLTarget,E as resolvePivot,Vt as resolveSqlitePragmas,Z as runBenchmark,H as runSeeder,M as runSeeders,mt as satisfies,ht as saveMigrationSnapshot,qn as seedModel,_e as setConfig,Ae as setQueryCacheMaxSize,W as showModel,m as singularizerFor,Ee as sql,ct as sqlTypeToAttr,Nn as stacksModelToEntity,I as startConsole,gn as stripTrailingS,ue as tableInfo,T as tableNameFor,Ct as temporalLiteral,re as tinker,at as toDialectPlaceholders,vn as toDynamoDBItem,Le as toHranaStatement,Ie as toLibSQLError,mn as toLibSQLRows,kn as toModelInstance,Fe as toTableName,Rn as unmarshallItem,$e as unsafe,Q as validateSchema,ve as waitReady,F as wipeDatabase,J as writeMigrationFiles};
|
package/dist/src/runtime.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{n,nt,e,P,rt,t,s,B,_e,dn,Ut,Vt,k,_,hn}from"../chunk-
|
|
2
|
+
import{n,nt,e,P,rt,t,s,B,_e,dn,Ut,Vt,k,_,hn}from"../chunk-3hwsz4q7.js";import{en,c,Ct,Rt,i,Re,Ae}from"../chunk-ygwkzhkh.js";export{Ut as DEFAULT_SQLITE_PRAGMAS,k as applySqliteBootstrapPragmas,Re as clearQueryCache,e as config,i as createQueryBuilder,nt as defaultConfig,dn as defineConfig,Rt as escapeStringLiteral,B as getConfig,t as getPlaceholder,s as getPlaceholders,n as isMysqlLike,rt as normalizeDialectName,c as quoteColumnForDialect,en as raw,hn as resetConnection,P as resolveDialect,_ as resolveLibSQLTarget,Vt as resolveSqlitePragmas,_e as setConfig,Ae as setQueryCacheMaxSize,Ct as temporalLiteral};
|
package/dist/types.d.ts
CHANGED
package/package.json
CHANGED
package/dist/chunk-g7qvmctn.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{ht,w,R,Qe,A}from"./chunk-3b13fc8j.js";import"./chunk-vyqr0w2z.js";import"./chunk-9wck98bv.js";import"./chunk-rzfnhh9f.js";import"./chunk-bpwg9p8b.js";import"./chunk-93ny6tvm.js";export{R as executeMigration,Qe as executeMigrationWithReport,w as generateMigration,A as resetDatabase,ht as saveMigrationSnapshot};
|