bun-query-builder 0.3.16 → 0.3.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import"../chunk-jypmc6m3.js";import"../chunk-wvae8521.js";import"../chunk-1hd398hq.js";import"../chunk-yg6pfvs0.js";import"../chunk-2v1zv4hb.js";import{ne,re,ie,se,F,ae,oe,le,ce,j,ue,q,W,de,fe,U,me,he,A,ge,S,N,M,we,Se,V,De,H,Ee,Q,G,P,J,$e,xe,ve,ke,z,Ce,Re}from"../chunk-6e2p3963.js";import{EventEmitter as Le}from"events";import v from"process";import ye from"process";import X from"process";import T from"process";import I from"process";import qe from"tty";import kt,{stdin as Gt,stdout as Ht}from"process";import{existsSync as Bt}from"fs";import D from"fs/promises";import Me from"os";import K from"path";import x from"process";function Y(e){return e.replace(/[<[].+/,"").trim()}function Ne(e){let t=/<([^>]+)>/g,i=/\[([^\]]+)\]/g,s=[],n=(d)=>{let a=!1,r=d[1];if(r.startsWith("..."))r=r.slice(3),a=!0;else if(r.endsWith("..."))r=r.slice(0,-3),a=!0;return{required:d[0].startsWith("<"),value:r.trim(),variadic:a}},o;while(o=t.exec(e))s.push(n(o));let m;while(m=i.exec(e))s.push(n(m));return s}function Pe(e){let t={alias:{},boolean:[]};for(let[i,s]of e.entries()){if(s.names.length>1)t.alias[s.names[0]]=s.names.slice(1);if(s.isBoolean)if(s.negated){if(!e.some((o,m)=>m!==i&&o.names.some((d)=>s.names.includes(d))&&typeof o.required==="boolean"))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t}function Oe(e){return e.reduce((t,i)=>t.length>=i.length?t:i,"")}function L(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function B(e){return e.replace(/([a-z])-([a-z])/g,(t,i,s)=>i+s.toUpperCase())}function We(e,t,i){let s=0,n=t.length,o=e,m;for(;s<n;++s)m=o[t[s]],o=o[t[s]]=s===n-1?i:m!=null?m:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]}function Fe(e,t){for(let i of Object.keys(t)){let s=t[i];if(e[i]===void 0)continue;if(s.shouldTransform){if(e[i]=Array.prototype.concat.call([],e[i]),typeof s.transformFunction==="function")e[i]=e[i].map(s.transformFunction)}}}function ze(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function k(e){return e.split(".").map((t,i)=>i===0?B(t):t).join(".")}class E extends Error{exitCode=2;isUsageError=!0;usage;constructor(e,t){super(e);if(this.name=this.constructor.name,t!==void 0)this.usage=t;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
3
+ import"../chunk-bqywz1ww.js";import"../chunk-wvae8521.js";import"../chunk-tvxbkxqm.js";import"../chunk-723pr7bj.js";import"../chunk-2v1zv4hb.js";import{ne,re,ie,se,F,ae,oe,le,ce,j,ue,q,W,de,fe,U,me,he,A,ge,S,N,M,we,Se,V,De,H,Ee,Q,G,P,J,$e,xe,ve,ke,z,Ce,Re}from"../chunk-q4drbrbw.js";import{EventEmitter as Le}from"events";import v from"process";import ye from"process";import X from"process";import T from"process";import I from"process";import qe from"tty";import kt,{stdin as Gt,stdout as Ht}from"process";import{existsSync as Bt}from"fs";import D from"fs/promises";import Me from"os";import K from"path";import x from"process";function Y(e){return e.replace(/[<[].+/,"").trim()}function Ne(e){let t=/<([^>]+)>/g,i=/\[([^\]]+)\]/g,s=[],n=(d)=>{let a=!1,r=d[1];if(r.startsWith("..."))r=r.slice(3),a=!0;else if(r.endsWith("..."))r=r.slice(0,-3),a=!0;return{required:d[0].startsWith("<"),value:r.trim(),variadic:a}},o;while(o=t.exec(e))s.push(n(o));let m;while(m=i.exec(e))s.push(n(m));return s}function Pe(e){let t={alias:{},boolean:[]};for(let[i,s]of e.entries()){if(s.names.length>1)t.alias[s.names[0]]=s.names.slice(1);if(s.isBoolean)if(s.negated){if(!e.some((o,m)=>m!==i&&o.names.some((d)=>s.names.includes(d))&&typeof o.required==="boolean"))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t}function Oe(e){return e.reduce((t,i)=>t.length>=i.length?t:i,"")}function L(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function B(e){return e.replace(/([a-z])-([a-z])/g,(t,i,s)=>i+s.toUpperCase())}function We(e,t,i){let s=0,n=t.length,o=e,m;for(;s<n;++s)m=o[t[s]],o=o[t[s]]=s===n-1?i:m!=null?m:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]}function Fe(e,t){for(let i of Object.keys(t)){let s=t[i];if(e[i]===void 0)continue;if(s.shouldTransform){if(e[i]=Array.prototype.concat.call([],e[i]),typeof s.transformFunction==="function")e[i]=e[i].map(s.transformFunction)}}}function ze(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function k(e){return e.split(".").map((t,i)=>i===0?B(t):t).join(".")}class E extends Error{exitCode=2;isUsageError=!0;usage;constructor(e,t){super(e);if(this.name=this.constructor.name,t!==void 0)this.usage=t;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
4
4
 
5
5
  Stack trace:
6
6
  ${this.stack}`;return this.message}}function Ue(e){if(e instanceof E)return!0;return!!e&&typeof e==="object"&&e.name==="ClappError"&&typeof e.message==="string"}function Ge(){let{env:e}=ye,{TERM:t,TERM_PROGRAM:i}=e;if(ye.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||i==="Terminus-Sublime"||i==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var R="\x1B",b=`${R}[`;var Ie={to(e,t){if(!t)return`${b}${e+1}G`;return`${b}${t+1};${e+1}H`},move(e,t){let i="";if(e<0)i+=`${b}${-e}D`;else if(e>0)i+=`${b}${e}C`;if(t<0)i+=`${b}${-t}A`;else if(t>0)i+=`${b}${t}B`;return i},up:(e=1)=>`${b}${e}A`,down:(e=1)=>`${b}${e}B`,forward:(e=1)=>`${b}${e}C`,backward:(e=1)=>`${b}${e}D`,nextLine:(e=1)=>`${b}E`.repeat(e),prevLine:(e=1)=>`${b}F`.repeat(e),left:`${b}G`,hide:`${b}?25l`,show:`${b}?25h`,save:`${R}7`,restore:`${R}8`};var Vt={screen:`${b}2J`,up:(e=1)=>`${b}1J`.repeat(e),down:(e=1)=>`${b}J`.repeat(e),line:`${b}2K`,lineEnd:`${b}K`,lineStart:`${b}1K`,lines(e){let t="";for(let i=0;i<e;i++)t+=this.line+(i<e-1?Ie.up():"");if(e)t+=Ie.left;return t}},Lt={screen:`${R}c`};function He(e,t){let i=[];for(let s=0;s<=t.length;s++)i[s]=[s];for(let s=0;s<=e.length;s++)i[0][s]=s;for(let s=1;s<=t.length;s++)for(let n=1;n<=e.length;n++)if(t.charAt(s-1)===e.charAt(n-1))i[s][n]=i[s-1][n-1];else i[s][n]=Math.min(i[s-1][n-1]+1,i[s][n-1]+1,i[s-1][n]+1);return i[t.length][e.length]}function Be(e,t,i=2,s=3){return t.map((n)=>({cmd:n,distance:He(e,n)})).filter(({distance:n})=>n<=i).sort((n,o)=>n.distance-o.distance).slice(0,s).map(({cmd:n})=>n)}function Ke(e,t={}){let i={_:[]},s=t.alias||{},n=new Set(t.boolean||[]),o={};for(let a of Object.keys(s))for(let r of s[a])o[r]=a;for(let a of n)if(s[a])for(let r of s[a])n.add(r);function m(a,r){if(a===void 0)return r;if(typeof r==="boolean")return r;return Array.isArray(a)?[...a,r]:[a,r]}function d(a,r){let c=o[a]||a,h=m(i[c],r);if(i[c]=h,s[c])for(let l of s[c])i[l]=h;if(o[a]&&s[o[a]])for(let l of s[o[a]])i[l]=h;i[a]=h}for(let a=0;a<e.length;a++){let r=e[a];if(r==="--"){i._.push(...e.slice(a+1));break}if(r.startsWith("--")){let c=r.indexOf("=");if(c!==-1){let h=B(r.slice(2,c)),l=r.slice(c+1);d(h,l)}else{let h=r.slice(2);if(h.startsWith("no-")){let f=B(h.slice(3));d(f,!1);continue}let l=B(h),y=o[l]||l;if(n.has(y)||n.has(l))d(l,!0);else{let f=e[a+1];if(f!==void 0&&!f.startsWith("-"))d(l,f),a++;else d(l,!0)}}}else if(r.startsWith("-")&&r.length>1){let c=r.slice(1);for(let h=0;h<c.length;h++){let l=c[h],y=o[l]||l;if(h===c.length-1&&!n.has(y)&&!n.has(l)){let f=e[a+1];if(f!==void 0&&!f.startsWith("-"))d(l,f),a++;else d(l,!0)}else d(l,!0)}}else i._.push(r)}return i}class Te{rawName;description;name;names;isBoolean;required;config;negated;variadic;constructor(e,t,i){if(this.rawName=e,this.description=t,this.config=Object.assign({},i),e=e.replace(/\.\*/g,""),this.negated=!1,this.variadic=/[<[](?:\.\.\.[^\]>]+|[^\]>]+\.\.\.)[\]>]/.test(e),this.names=Y(e).split(",").map((s)=>{let n=s.trim().replace(/^-{1,2}/,"");if(n.startsWith("no-"))this.negated=!0,n=n.replace(/^no-/,"");return k(n)}).sort((s,n)=>s.length>n.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var Dt=X.argv,Ye=`${X.platform}-${X.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,_e=T.argv,Qe=`${T.platform}-${T.arch} node-${T.version}`;class Z{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,i,s){this.rawName=e,this.description=t,this.config=i,this.cli=s,this.options=[],this.aliasNames=[],this.name=Y(e);let n=Y(e),o=n.indexOf(":");if(o>0)this.namespace=n.substring(0,o),this.name=n.substring(o+1);if(this.args=Ne(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!i)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,i){let s=new Te(e,t,i);return this.options.push(s),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof ee}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){let t=k(e.split(".")[0]);return!!this.options.find((i)=>i.names.some((s)=>k(s)===t))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:i,options:s,helpCallback:n}=this.cli.globalCommand,o=[{body:`${e}${i?`/${i}`:""}`}];if(o.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let r=Oe(t.map((f)=>f.rawName)),c=new Map,h=[];for(let f of t)if(f.namespace){if(!c.has(f.namespace))c.set(f.namespace,[]);c.get(f.namespace).push(f)}else h.push(f);let l="";if(h.sort((f,_)=>f.rawName<_.rawName?-1:f.rawName>_.rawName?1:0),h.length>0)l+=h.map((f)=>` ${L(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(O.yellow("Did you mean one of these?")),i.forEach((s)=>console.log(` ${O.dim("\u2022")} ${this.name} ${s}`)),console.log("")}console.log(O.dim("Run"),`${this.name} --help`,O.dim("to see all available commands")),v.exit(1)}async parse(e=_e,t={}){let{run:i=!0,exitOnError:s=!1}=t;if(s)try{return await this.parse(e,{run:i})}catch(a){throw this.handleUsageError(a),a}if(this.rawArgs=e,!this.name)this.name=e[1]?ze(e[1]):"cli";let n=!0,o=e.slice(2),m=o[0];if(m&&!m.startsWith("-")){for(let a of this.commands)if(a.isMatched(m)){let r=this.mri(o,a);n=!1;let c={...r,args:r.args.slice(1)};this.setParsedInfo(c,a,m),this.emit(`command:${m}`,a);break}if(n){let a=o[1];if(a&&!a.startsWith("-")){let r=`${m}:${a}`;for(let c of this.commands)if(c.isMatched(r)){let h=this.mri(o,c);n=!1;let l={...h,args:h.args.slice(2)};this.setParsedInfo(l,c,r),this.emit(`command:${r}`,c);break}}}}if(n){for(let a of this.commands)if(a.name===""){n=!1;let r=this.mri(o,a);this.setParsedInfo(r,a),this.emit("command:!",a);break}}if(n){let a=this.mri(e.slice(2));this.setParsedInfo(a)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction||this.options.interaction===!1)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji||this.options.emoji===!1)this.useEmoji=!1;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache||this.options.cache===!1)this.isNoCache=!0;if(this.options.help&&this.showHelpOnExit)this.outputHelp(),i=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),i=!1,this.unsetMatchedCommand();let d={args:this.args,options:this.options};if(i)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return d}mri(e,t){let i=[...this.globalCommand.options,...t?t.options:[]],s=Pe(i),n=[],o=e.indexOf("--");if(o>-1)n=e.slice(o+1),e=e.slice(0,o);let m=Ke(e,s),d={_:m._};for(let l of Object.keys(m))if(l!=="_")d[k(l)]=m[l];let a=d._,r={"--":n},c=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,h=Object.create(null);for(let l of i){if(!c&&l.config.default!==void 0)for(let y of l.names)r[y]=l.config.default;if(Array.isArray(l.config.type)){if(h[l.name]===void 0)h[l.name]={shouldTransform:!0,transformFunction:l.config.type[0]}}}for(let l of Object.keys(d))if(l!=="_"){let y=l.split(".");We(r,y,d[l]),Fe(r,h)}for(let l of i){if(!l.variadic)continue;for(let y of l.names){let f=r[y];if(f===void 0||Array.isArray(f))continue;if(l.config.default!==void 0&&f===l.config.default)continue;r[y]=[f]}}return{args:a,options:r}}async run(e=_e){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!Ue(e)||e.isUsageError===!1)return;let t=e.message||"command-line error",i=this.name?`${this.name}: `:"",s=/--help/.test(t)?"":e.usage?`
30
30
  Usage: ${e.usage}`:`
31
31
  Run \`${this.name??"cli"} --help\` for usage.`;v.stderr.write(`${i}${t}${s}
32
- `),v.exit(e.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:i}=this;if(!i||!i.commandAction)return;i.checkUnknownOptions(),i.checkOptionValue(),i.checkRequiredArgs();let s=[];i.args.forEach((d,a)=>{if(d.variadic)s.push(e.slice(a));else s.push(e[a])}),s.push(t);let n={command:i,args:s,options:t};for(let d of i.beforeHooks)await d(n);let o,m=async()=>{let d=i.commandAction.apply(this,s);if(d instanceof Promise)o=await d;else o=d;return o};if(i.middleware.length>0){let d=0,a=async()=>{if(d<i.middleware.length){let r=i.middleware[d++];await r({...n,next:a})}else await m()};await a()}else await m();for(let d of i.afterHooks)await d(n);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return v.removeAllListeners("SIGINT"),v.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class je{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 je;function et(){if("FORCE_COLOR"in I.env)return I.env.FORCE_COLOR!=="0";if("NO_COLOR"in I.env||I.env.TERM==="dumb")return!1;if(I.platform==="win32")return!0;return qe.isatty(1)&&qe.isatty(2)}var Ae=et();function g(e,t){if(!Ae)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=Ae,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=K.join(e,".config","clapp");this.configPath=K.join(t,"telemetry.json")}async isEnabled(){if(x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true")return!1;if(x.env.NO_TELEMETRY==="1"||x.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let s={event:e,...t,timestamp:Date.now(),platform:Me.platform(),nodeVersion:x.version};if(this.events.push(s),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Bt(this.configPath)){let e=await D.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=K.dirname(this.configPath);await D.mkdir(t,{recursive:!0}),await D.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 pe="0.3.16";var u=new te("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 he(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 A({tables:i});console.log(`import { defineModel } from 'bun-query-builder'
32
+ `),v.exit(e.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:i}=this;if(!i||!i.commandAction)return;i.checkUnknownOptions(),i.checkOptionValue(),i.checkRequiredArgs();let s=[];i.args.forEach((d,a)=>{if(d.variadic)s.push(e.slice(a));else s.push(e[a])}),s.push(t);let n={command:i,args:s,options:t};for(let d of i.beforeHooks)await d(n);let o,m=async()=>{let d=i.commandAction.apply(this,s);if(d instanceof Promise)o=await d;else o=d;return o};if(i.middleware.length>0){let d=0,a=async()=>{if(d<i.middleware.length){let r=i.middleware[d++];await r({...n,next:a})}else await m()};await a()}else await m();for(let d of i.afterHooks)await d(n);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return v.removeAllListeners("SIGINT"),v.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class je{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 je;function et(){if("FORCE_COLOR"in I.env)return I.env.FORCE_COLOR!=="0";if("NO_COLOR"in I.env||I.env.TERM==="dumb")return!1;if(I.platform==="win32")return!0;return qe.isatty(1)&&qe.isatty(2)}var Ae=et();function g(e,t){if(!Ae)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=Ae,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=K.join(e,".config","clapp");this.configPath=K.join(t,"telemetry.json")}async isEnabled(){if(x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true")return!1;if(x.env.NO_TELEMETRY==="1"||x.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let s={event:e,...t,timestamp:Date.now(),platform:Me.platform(),nodeVersion:x.version};if(this.events.push(s),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Bt(this.configPath)){let e=await D.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=K.dirname(this.configPath);await D.mkdir(t,{recursive:!0}),await D.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 pe="0.3.18";var u=new te("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 he(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 A({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 ve(e,t,i)});u.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await Ee()});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 Re(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 ke(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 fe(e,t)});u.command("migrate <dir>","Generate SQL migrations from models").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--apply","Execute the generated SQL against the database").option("--full","Force full migration SQL instead of incremental diff").option("--from-db","Diff the models against the live database instead of the model snapshot").option("--strict","Fail when the migrated schema does not match the models").example("query-builder migrate ./app/Models --dialect postgres").example("query-builder migrate ./app/Models --from-db --strict").action(async(e,t)=>{try{await S(e,{dialect:t.dialect,state:t.state,apply:t.apply,full:t.full,fromDb:t.fromDb}),await N(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 de(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 Q(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 G({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 M(e,{dialect:t.dialect,state:t.state}),console.log("-- Generating fresh migrations..."),await S(e,{dialect:t.dialect,state:t.state,full:t.full}),console.log("-- Executing migrations..."),await N()}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 M(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 J(e.class,{verbose:e.verbose});else await P({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 J(e.class,{verbose:e.verbose});else await P({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 $e(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 xe({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 ge(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 H(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 V()}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 De()}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 Se({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 we(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 j()}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 ue()}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 W({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 q({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 F()}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 ae()}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 U(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 me(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 re()}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 ie()}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 se({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 ne({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 z(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 Ce(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 oe(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 le(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 ce({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(pe)});u.version(pe);u.help();u.parse();
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{pt,S,N,Je,M}from"./chunk-q4drbrbw.js";import"./chunk-tvxbkxqm.js";import"./chunk-2v1zv4hb.js";import"./chunk-723pr7bj.js";import"./chunk-bqywz1ww.js";import"./chunk-wvae8521.js";export{N as executeMigration,Je as executeMigrationWithReport,S as generateMigration,M as resetDatabase,pt as saveMigrationSnapshot};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Ve}from"./chunk-wvae8521.js";import{p,n,e,R,K,T,qe,m,x,l,lt,te}from"./chunk-jypmc6m3.js";function O(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function Me(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 Ie(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 re(t){if(typeof t==="number")return{length:t};return t}function ge(t){if(typeof t==="number")return{max:t};return t}function Fe(t){return typeof t==="function"}function We(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 X(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[We(s)];if(Fe(a))return a.bind(o);return}})}function _t(t){let r=(c)=>{let y=Array.isArray(c)?c:[],A=Math.floor(Math.random()*y.length);return y[A]},o=()=>t.string,s=()=>t.number,i=()=>t.random,a=X(t.string,{alpha:(c)=>o()?.alpha?.(re(c)),alphanumeric:(c)=>o()?.alphanumeric?.(re(c)),numeric:(c)=>o()?.numeric?.(re(c)),sample:(c)=>o()?.sample?.(re(c)),hexadecimal:(c)=>o()?.hexadecimal?.(re(c))}),d=X(t.number,{int:(c)=>s()?.int?.(ge(c)),float:(c)=>{let y=ge(c);return Ke(Number(s()?.float?.(y)??0),y)}}),u=X(t.helpers,{arrayElement:r,arrayElements:(c,y)=>{let A=[...Array.isArray(c)?c:[]],k=typeof y==="number"?y:Math.max(1,Math.floor(Math.random()*A.length));for(let _=A.length-1;_>0;_-=1){let v=Math.floor(Math.random()*(_+1));[A[_],A[v]]=[A[v],A[_]]}return A.slice(0,Math.min(k,A.length))},shuffle:(c)=>{let y=[...Array.isArray(c)?c:[]];for(let A=y.length-1;A>0;A-=1){let k=Math.floor(Math.random()*(A+1));[y[A],y[k]]=[y[k],y[A]]}return y},maybe:(c,y)=>{let A=typeof y?.probability==="number"?y.probability:0.5;return Math.random()<A?c():void 0},slugify:(c)=>String(c??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),w={string:a,number:d,helpers:u,datatype:{boolean:(c)=>{let y=typeof c==="number"?c:c?.probability;if(typeof y==="number")return Math.random()<y;return Boolean(i()?.boolean?.())},number:(c)=>Number(s()?.int?.(ge(c))??0),float:(c)=>Ke(Number(s()?.float?.(c)??0),c),uuid:()=>crypto.randomUUID(),string:(c)=>String(o()?.alphanumeric?.({length:c??10})??""),hexadecimal:(c)=>String(o()?.hexadecimal?.(re(c))??""),array:(c)=>Array.from({length:c??3},()=>o()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:o()?.alphanumeric?.({length:8})})},location:X(t.address),address:X(t.address),vehicle:X(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:X(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(c,y){if(y in w)return w[y];let A=c[y];if(A&&typeof A==="object")return X(A);return A}})}function E(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,...typeof r.relationName==="string"?{relationName:r.relationName}:{}}}return null}function B(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(E).filter((o)=>o!==null)}function Z(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var Pe=/^[A-Z_][A-Z0-9_]*$/i;function z(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(!Pe.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Oe(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||!Pe.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 Re(t,r){if(r.length!==1)return r;let o=r[0];if(Array.isArray(o))return[...o];if(o===void 0&&te(t)===0)return[];return r}var ue=null,ke=new Map;function Ue(t,r){ke.set(t,r),se.clear()}function It(){ke.clear(),se.clear()}function F(t){if(!ue)try{ue=import.meta.require("./chunk-bm85q6et.js").getModel}catch{ue=()=>{return}}return ue(t)??ke.get(t)}var de=new Map,He=500;function _e(t){let r=de.get(t);if(r!==void 0)return r;let o=lt(t,"postgres");if(de.size>=He)de.clear();return de.set(t,o),o}function Lt(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 Kt(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 we{sqliteDb;dialect="sqlite";constructor(t){this.sqliteDb=t}all(t,r){return Promise.resolve(this.sqliteDb.query(t).all(...p(r)))}get(t,r){return Promise.resolve(this.sqliteDb.query(t).get(...p(r))??void 0)}run(t,r){let o=this.sqliteDb.run(t,p(r));return Promise.resolve({changes:o.changes,lastInsertId:o.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class De{dialect;constructor(t){this.dialect=t}conn(){return T()}text(t){return this.dialect==="postgres"?_e(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:Lt(o),lastInsertId:Kt(o)}}async insert(t,r,o){if(this.dialect==="postgres"){let a=await this.conn().unsafe(`${_e(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=Kt(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:Lt(s)||1,lastInsertId:i}}}var V=null,me=!1,H=null,oe=null,ce=null,fe=null;function Fn(t){if(t.database instanceof Te)V=t.database,me=!1;else V=new Te(t.database||":memory:",{create:!0}),me=!0,R(V);H=null,oe=null}function jn(){let t=me,r=V;if(V=null,me=!1,H=null,oe=null,ce=null,fe=null,t&&r)try{r.close()}catch{}}var xe=!1;function P(){if(V){if(!H||oe!==V)H=new we(V),oe=V,ce="sqlite",fe=null;return H}let t=e.dialect,r=e.database?.database??null,o=`${r??""}|${K()?.url??""}`;if(H&&oe===null&&ce===t&&fe===o)return H;if(oe=null,ce=t,fe=o,t==="sqlite"&&K())H=new De(t);else if(t==="sqlite"){if(!r&&!xe)xe=!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});R(s),H=new we(s)}else H=new De(t);return H}function qn(){let t=P();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,Ae=1000;function ze(t,r,o){let s=t.attributes,i=new Map(Object.entries(s).map(([a,d])=>[S(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 f=typeof u;if(f!=="string"&&f!=="number"&&f!=="boolean"&&f!=="bigint")return!1}return!0}function Ge(t,r){return typeof r==="bigint"?r.toString():r}function Ee(t){return 2**Math.floor(Math.log2(t))}var W="deleted_at",ve=500,be="__btm_rel__";function ne(t){let r=t.traits;return Boolean(r?.useSoftDeletes||r?.softDeletable)}function ee(t){let r=t.traits;return Boolean(r?.useTimestamps||r?.timestampable)}var Ce=new WeakMap;function Xe(t){let r=Ce.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 Ce.set(t,o),o}function Be(t){let r={};for(let[o,s]of Object.entries(t))r[S(o)]=s;return r}function Ye(t){for(let r in t)if(S(r)!==r)return Be(t);return t}function Ze(t,r){if(t[r])return t[r];let o=S(r);if(t[o])return t[o];for(let s of Object.keys(t))if(S(s)===o)return t[s];return}class j{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_exists;_relations={};constructor(t,r,o){this._definition=t,this._exists=o,this._attributes=Ye({...r}),this._original=null;let s=Xe(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 f=je(t,d);if(!f||f.type!=="belongsToMany")throw Error(`[orm] relation '${d}' did not resolve to a belongsToMany on '${t.name}'`);let w=F(f.relatedModelName),c=w?.getDefinition?.()||w?.definition;if(!c)throw Error(`[orm] related model '${f.relatedModelName}' is not registered`);return new Ft(i,t,f,c)};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[S(t)]}getAttribute(t){return this._attributes[S(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[S(t)]=r}only(t){let r={};for(let o of t)r[o]=this._attributes[S(o)];return r}except(t){let r=new Set(t.map((s)=>S(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=S(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()[S(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=Ze(r,o),a=!i&&S(o).endsWith("_id");if(i?.fillable&&!i?.guarded||a){if(this._original===null)this._original={...this._attributes};this._attributes[S(o)]=s}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Be(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,f]of Object.entries(o)){if(f.guarded&&!this._forced.has(S(u)))continue;let w=S(u);if(this._attributes[w]!==void 0)s[w]=this._attributes[w]}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(ee(this._definition)){let u=Z(),f=this._attributes.created_at;s.created_at=f===void 0||f===null?u:f,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[S(r)]=o(this._attributes)}async save(){let t=P(),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(ee(this._definition)){let u=Z();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=P(),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 j(this._definition,s,!0)}async delete(){let t=P(),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),ne(this._definition)){let i=Z();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[i,o]),this._attributes[W]=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 P().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await o?.afterDelete?.(this),!0}async restore(){if(!ne(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 P().run(`UPDATE ${this._definition.table} SET ${W} = ? WHERE ${t} = ?`,[null,r]),this._attributes[W]=null,this._original=null,this}trashed(){return this._attributes[W]!=null}async refresh(){let t=P(),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 j(this._definition,r,!1)}toArray(){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.toArray());else if(s)r[o]=s.toArray();else r[o]=null;return r}toJSON(){return this.toArray()}}var Ne=new Map,$e=new Map,se=new Map,Je=1000;function q(t){return S(t)}function S(t){let r=Ne.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),Ne.set(t,r),r}function Y(t){let r=$e.get(t);if(r!==void 0)return r;return r=qe(t),$e.set(t,r),r}var he=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],et=[...he,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Se(t,r){let o=t[r];if(!o)return[];if(Array.isArray(o))return o.map((s)=>{let i=E(s);return i?.relationName??i?.model??""}).filter(Boolean);if(typeof o==="object")return Object.keys(o);if(typeof o==="string")return[o];return[]}function tt(t,r){let o=t.name??t.table??"model",i=et.filter((d)=>Se(t,d).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((d)=>!he.includes(d));if(i.length>0)return`[orm] '${o}' declares '${r}' as ${i.join("/")}, which eager loading does not support yet. Supported kinds: ${he.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let a=he.flatMap((d)=>Se(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 je(t,r){let{name:o,table:s}=t,i=t.primaryKey||"id";function a(D){if(!D)return null;if(Array.isArray(D)){for(let g of D){let M=E(g);if(M&&(M.relationName??M.model).toLowerCase()===r.toLowerCase())return M.model}return null}if(typeof D==="object"){for(let[g,M]of Object.entries(D))if(g===r||g.toLowerCase()===r.toLowerCase())return typeof M==="string"?M:M?.model||M?.target||g}return null}function d(){let D=t.belongsTo;if(!D)return null;let g=r.toLowerCase(),M=(b)=>{if(typeof b==="string")return{model:b};if(b&&typeof b==="object"&&typeof b.model==="string")return{model:b.model,foreignKey:b.foreignKey};return null};if(Array.isArray(D)){for(let b of D){let h=M(b);if(h&&(E(b)?.relationName??h.model).toLowerCase()===g)return h}return null}if(typeof D==="object"){for(let[b,h]of Object.entries(D))if(b===r||b.toLowerCase()===g)return M(h)}return null}function u(){let D=t.belongsToMany;if(!D)return null;if(Array.isArray(D)){for(let g of D)if(typeof g==="string"){if(g.toLowerCase()===r.toLowerCase())return{entry:g}}else if(g&&typeof g==="object"&&g.model){if(g.model.toLowerCase()===r.toLowerCase())return{entry:g}}return null}if(typeof D==="object"){for(let[g,M]of Object.entries(D))if(g===r||g.toLowerCase()===r.toLowerCase())return{entry:M}}return null}function f(D){let g=t[D];if(!g)return null;let M=r.toLowerCase();if(Array.isArray(g)){for(let b of g){let h=typeof b==="string"?b:String(b?.model??"");if(!h||h.toLowerCase()!==M)continue;let N=typeof b==="object"?b?.morphName:void 0;return{model:h,morphName:String(N??`${S(o)}able`)}}return null}if(typeof g==="object")for(let[b,h]of Object.entries(g)){let N=typeof h==="string"?h:String(h?.model??"");if(b.toLowerCase()!==M&&N.toLowerCase()!==M)continue;let I=typeof h==="object"?h?.morphName:void 0;return{model:N,morphName:String(I??b)}}return null}for(let D of["morphMany","morphOne"]){let g=f(D);if(!g)continue;let b=F(g.model)?.getTable?.()||Y(g.model);return{type:D,relatedModelName:g.model,relatedTable:b,foreignKey:`${g.morphName}_id`,localKey:i,morphTypeColumn:`${g.morphName}_type`,morphTypeValue:s}}let w=a(t.hasMany);if(w){let g=F(w)?.getTable?.()||Y(w),M=S(o)+"_id";return{type:"hasMany",relatedModelName:w,relatedTable:g,foreignKey:M,localKey:i}}let c=a(t.hasOne);if(c){let g=F(c)?.getTable?.()||Y(c),M=S(o)+"_id";return{type:"hasOne",relatedModelName:c,relatedTable:g,foreignKey:M,localKey:i}}let y=d();if(y){let D=y.model,g=F(D),M=g?.getTable?.()||Y(D),b=g?.getDefinition?.()?.primaryKey||"id",h=y.foreignKey||`${S(D)}_id`;return{type:"belongsTo",relatedModelName:D,relatedTable:M,foreignKey:h,localKey:b}}let A=u();if(A){let D=typeof A.entry==="object",g=D?A.entry.model:A.entry,b=F(g)?.getTable?.()||Y(g),h=D?A.entry:null,N,I;if(h?.table)N=h.table;else if(h?.through){I=h.through;let L=F(h.through);if(!L)throw Error(`[orm] belongsToMany relation '${r}' on '${o}' references unknown through model '${h.through}'. Make sure '${h.through}' is registered.`);N=L.getTable?.()||L.getDefinition?.()?.table||Y(h.through)}else{let L=le(s),Q=le(b);N=[L,Q].sort().join("_")}let U=h?.foreignKey||`${le(s)}_id`,J=h?.relatedKey||`${le(b)}_id`,G=[];if(h?.pivot?.columns)for(let L of Object.keys(h.pivot.columns))G.push(L);if(I){let L=F(I),Q=L?.getDefinition?.()||L?.definition,ye=Q?.attributes??{},Le=Q?.primaryKey??"id";for(let ae of Object.keys(ye)){if(ae===U||ae===J||ae===Le)continue;if(!G.includes(ae))G.push(ae)}}return{type:"belongsToMany",relatedModelName:g,relatedTable:b,foreignKey:U,localKey:i,pivotTable:N,pivotFkParent:U,pivotFkRelated:J,pivotColumns:G,pivotModelName:I,pivotTimestamps:Boolean(h?.pivot?.timestamps)}}let k=(D,g)=>{if(!D||typeof D!=="object"||Array.isArray(D))return null;let M=D[r]??D[Object.keys(D).find((Q)=>Q.toLowerCase()===r.toLowerCase())??""];if(!M||typeof M!=="object")return null;let{through:b,target:h}=M;if(!b||!h)return null;let N=F(b),I=N?.getDefinition?.()||N?.definition,U=N?.getTable?.()||I?.table||Y(b),J=I?.primaryKey||"id",L=F(h)?.getTable?.()||Y(h);return{type:g,relatedModelName:h,relatedTable:L,foreignKey:`${S(o)}_id`,localKey:i,throughTable:U,throughForeignKey:`${S(o)}_id`,throughLocalKey:J,targetForeignKey:`${le(U)}_id`}},_=k(t.hasManyThrough,"hasManyThrough");if(_)return _;let v=k(t.hasOneThrough,"hasOneThrough");if(v)return v;return null}function pe(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 le(t){return m(e.relations?.singularizeStrategy)(t)}class Ft{_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(Oe(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 ${be}${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,f]of Object.entries(s))if(u.startsWith(be))i[u.slice(be.length)]=f;else if(u!==r&&u!==o)a[u]=f;let d=new j(this._relatedDef,i,!0);return d.pivot=a,d})}async get(){let t=P(),{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=P(),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 Z()}async attach(t,r={}){let o=P(),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 f=Object.keys(u),w=f.map(()=>"?").join(", "),c=`INSERT INTO ${this.pivotTable} (${f.join(", ")}) VALUES (${w})`,y=f.map((A)=>u[A]);await o.run(c,y),a++}return a}async detach(t){let r=P(),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=P(),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((f)=>`${f} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${a} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,u=[...i.map((f)=>s[f]),this.parentId,t];return(await o.run(d,u)).changes}async sync(t){let r=P(),o=new Map;for(let w of t)if(w!=null&&typeof w==="object"&&"id"in w){let{id:c,...y}=w;o.set(c,y)}else o.set(w,{});let s=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),i=new Set(s.map((w)=>w[this.fkRelated])),a=[],d=[],u=[],f=[...i].filter((w)=>!o.has(w));if(f.length>0)await this.detach(f),d.push(...f);for(let[w,c]of o)if(!i.has(w))await this.attach(w,c),a.push(w);else if(Object.keys(c).length>0)await this.updateExistingPivot(w,c),u.push(w);return{attached:a,detached:d,updated:u}}async toggle(t){let r=P(),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((f)=>f[this.fkRelated])),d=o.filter((f)=>!a.has(f)),u=o.filter((f)=>a.has(f));if(d.length>0)await this.attach(d);if(u.length>0)await this.detach(u);return{attached:d,detached:u}}}class C{_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 z(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return z(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return z(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return z(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:Re(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Re(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 C(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 z(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){z(t,"whereNotBetween(column)");let o=q(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(Oe(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=q(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(q(o.column),i,o.operator==="not in",i.map(()=>"?").join(", ")),t.push(...i)}else s=`${q(o.column)} ${o.operator} ?`,t.push(o.value);r.push({conn:o.boolean==="or"?"OR":"AND",sql:s})}return x(r)}softDeleteClause(){if(this._trashed==="include"||!ne(this._definition))return"";return this._trashed==="only"?`${W} IS NOT NULL`:`${W} 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:q(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)=>`${q(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=P(),s=this._definition.primaryKey||"id",i=`${this._definition.name}:${t}`,a=se.get(i);if(a===void 0){if(a=je(this._definition,t),se.size>=Je)se.clear();se.set(i,a)}if(!a)throw Error(tt(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=pe(r,s);if(u.length===0)return;let f=u.map(()=>"?").join(", "),w=a.morphTypeColumn?` AND ${a.morphTypeColumn} = ?`:"",c=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.foreignKey} IN (${f})${w}`,a.morphTypeColumn?[...u,a.morphTypeValue]:u),y=F(a.relatedModelName),A=y?.getDefinition?.()||y?.definition||this._definition;if(!d){let k=new Map;for(let _ of c){let v=_[a.foreignKey];if(!k.has(v))k.set(v,[]);k.get(v).push(_)}for(let _ of r){let v=k.get(_.get(s))||[];_.setRelation(t,v.map((D)=>new j(A,D,!0)))}}else{let k=new Map;for(let _ of c){let v=_[a.foreignKey];if(!k.has(v))k.set(v,_)}for(let _ of r){let v=k.get(_.get(s));_.setRelation(t,v?new j(A,v,!0):null)}}}if(a.type==="belongsTo"){let u=new Set;for(let _ of r){let v=_._attributes[a.foreignKey];if(v!=null)u.add(v)}let f=[...u];if(f.length===0){for(let _ of r)_.setRelation(t,null);return}let w=f.map(()=>"?").join(", "),c=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.localKey} IN (${w})`,f),y=F(a.relatedModelName),A=y?.getDefinition?.()||y?.definition||this._definition,k=new Map;for(let _ of c)k.set(_[a.localKey],_);for(let _ of r){let v=_._attributes[a.foreignKey],D=k.get(v);_.setRelation(t,D?new j(A,D,!0):null)}}if(a.type==="belongsToMany"){let u=pe(r,s);if(u.length===0)return;if(!a.pivotTable||!a.pivotFkParent||!a.pivotFkRelated)return;let f=u.map(()=>"?").join(", "),w=await o.all(`SELECT * FROM ${a.pivotTable} WHERE ${a.pivotFkParent} IN (${f})`,u);if(w.length===0){for(let b of r)b.setRelation(t,[]);return}let c=new Set;for(let b of w){let h=b[a.pivotFkRelated];if(h!=null)c.add(h)}let y=[...c],A=F(a.relatedModelName),k=A?.getDefinition?.()||A?.definition||this._definition,_=k?.primaryKey||"id",v=[];if(y.length>0){let b=y.map(()=>"?").join(", ");v=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${_} IN (${b})`,y)}let D=new Map;for(let b of v)D.set(b[_],b);let g=new Map;for(let b of w){let h=b[a.pivotFkParent];if(!g.has(h))g.set(h,[]);g.get(h).push(b)}let M=new Set([a.pivotFkParent,a.pivotFkRelated]);for(let b of r){let h=b.get(s),I=(g.get(h)||[]).map((U)=>{let J=D.get(U[a.pivotFkRelated]);if(!J)return null;let G=new j(k,J,!0),L={};for(let[Q,ye]of Object.entries(U))if(!M.has(Q))L[Q]=ye;return G.pivot=L,G}).filter((U)=>U!==null);b.setRelation(t,I)}}if(a.type==="hasManyThrough"||a.type==="hasOneThrough"){let u=pe(r,s);if(u.length===0)return;let f=a.throughLocalKey||"id",w=u.map(()=>"?").join(", "),c=await o.all(`SELECT ${f}, ${a.throughForeignKey} FROM ${a.throughTable} WHERE ${a.throughForeignKey} IN (${w})`,u);if(c.length===0){for(let M of r)M.setRelation(t,a.type==="hasManyThrough"?[]:null);return}let y=new Map;for(let M of c)y.set(M[f],M[a.throughForeignKey]);let A=[...new Set(c.map((M)=>M[f]))],k=A.map(()=>"?").join(", "),_=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.targetForeignKey} IN (${k})`,A),v=F(a.relatedModelName),D=v?.getDefinition?.()||v?.definition||this._definition,g=new Map;for(let M of _){let b=y.get(M[a.targetForeignKey]);if(b==null)continue;if(!g.has(b))g.set(b,[]);g.get(b).push(new j(D,M,!0))}for(let M of r){let b=g.get(M.get(s))||[];M.setRelation(t,a.type==="hasManyThrough"?b:b[0]??null)}}}async get(){let t=P(),{sql:r,params:o}=this.buildQuery(),i=(await t.all(r,o)).map((a)=>new j(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=P(),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){z(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let o=P(),s=[r],i=q(t),a=`UPDATE ${this._definition.table} SET ${i} = ${i} + ?`;if(ee(this._definition))a+=", updated_at = ?",s.push(Z());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 C(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){z(t,"pluck(column)");let r=P(),o=[],s=q(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)=>`${q(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){z(r,`${t}(column)`);let o=P(),s=[],i=`SELECT ${t}(${q(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 f=Number(u);return u.trim()!==""&&!Number.isNaN(f)?f: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=ne(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=P(),o=this._definition.table,s=this._definition.hooks,i=[],a=this.composeWhere(i);if(t&&this._trashed==="include")a=a?`(${a}) AND ${W} IS NULL`:`${W} IS NULL`;let d=a?` WHERE ${a}`:"",u=t?Z():void 0;if(!s?.beforeDelete&&!s?.afterDelete)return t?(await r.run(`UPDATE ${o} SET ${W} = ?${d}`,[u,...i])).changes:(await r.run(`DELETE FROM ${o}${d}`,i)).changes;let f=this._definition.primaryKey||"id",c=(await r.all(`SELECT * FROM ${o}${d}`,i)).map((k)=>new j(this._definition,k,!0)),y=c.map((k)=>k._attributes[f]);if(y.some((k)=>k==null))throw Error(`Cannot delete a model without a primary key: '${f}' is missing from a matching row`);for(let k of c)await s.beforeDelete?.(k);let A=0;for(let k=0;k<y.length;k+=ve){let _=y.slice(k,k+ve),v=`${f} IN (${_.map(()=>"?").join(", ")})`;A+=t?(await r.run(`UPDATE ${o} SET ${W} = ? WHERE ${v}`,[u,..._])).changes:(await r.run(`DELETE FROM ${o} WHERE ${v}`,_)).changes}for(let k of c){if(t)k._attributes[W]=u;await s.afterDelete?.(k)}return A}async update(t){this.assertNoUnappliedClauses("update");let r=P(),o=Object.entries(t),s=o.map(([u])=>`${q(u)} = ?`).join(", "),i=o.map(([,u])=>u);if(ee(this._definition))i.push(Z());let a=`UPDATE ${this._definition.table} SET ${s}${ee(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(i);if(d)a+=` WHERE ${d}`;return(await r.run(a,i)).changes}}function nt(t){let r={query:()=>new C(t),where(o,s,i){return new C(t).where(o,s,i)},orWhere(o,s,i){return new C(t).orWhere(o,s,i)},whereIn(o,s){return new C(t).whereIn(o,s)},whereNotIn(o,s){return new C(t).whereNotIn(o,s)},whereNull(o){return new C(t).whereNull(o)},whereNotNull(o){return new C(t).whereNotNull(o)},whereLike(o,s){return new C(t).whereLike(o,s)},orderBy(o,s="asc"){return new C(t).orderBy(o,s)},orderByDesc(o){return new C(t).orderByDesc(o)},select(...o){return new C(t).select(...o)},with(...o){return new C(t).with(...o)},limit:(o)=>new C(t).limit(o),take:(o)=>new C(t).take(o),skip:(o)=>new C(t).skip(o),withTrashed:()=>new C(t).withTrashed(),onlyTrashed:()=>new C(t).onlyTrashed(),async find(o){let s=P(),i=t.primaryKey||"id",a=ne(t)?` AND ${W} IS NULL`:"",d=await s.get(`SELECT * FROM ${t.table} WHERE ${i} = ?${a}`,[o]);return d?new j(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=P(),i=t.primaryKey||"id",a=ne(t)?` AND ${W} IS NULL`:"";return(await s.all(`SELECT * FROM ${t.table} WHERE ${i} IN (${o.map(()=>"?").join(", ")})${a}`,o)).map((u)=>new j(t,u,!0))},all:()=>new C(t).get(),first:()=>new C(t).first(),firstOrFail:()=>new C(t).firstOrFail(),last:()=>new C(t).last(),count:()=>new C(t).count(),exists:()=>new C(t).exists(),doesntExist:()=>new C(t).doesntExist(),paginate:(o,s)=>new C(t).paginate(o,s),whereBetween(o,s){return new C(t).whereBetween(o,s)},whereNotBetween(o,s){return new C(t).whereNotBetween(o,s)},async create(o){let s=new j(t,o,!1);return await s.save(),s},async createMany(o){let s=o.map((f)=>new j(t,f,!1));if(!s.length)return[];let i=P(),a=t.primaryKey||"id",d=[];for(let f of s)d.push(await f._prepareInsert());let u=new Map;d.forEach((f,w)=>{let c=Object.keys(f).join("\x00"),y=u.get(c);if(y)y.push(w);else u.set(c,[w])});for(let[f,w]of u){let c=f?f.split("\x00"):[],y=!c.includes(a);if(!c.length||y&&i.dialect==="mysql"){for(let k of w){let _=d[k],v=Object.keys(_),D=await i.insert(v.length?`INSERT INTO ${t.table} (${v.join(", ")}) VALUES (${v.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(_),a);await s[k]._markInserted(_,y?D.lastInsertId:void 0)}continue}if(i.dialect==="postgres"&&ze(t,c,w.map((k)=>d[k]))){let k=t.table,_=c.join(", "),v=`INSERT INTO ${k} (${_}) SELECT ${_} FROM jsonb_populate_recordset(NULL::${k}, (?::text)::jsonb)`;for(let D=0;D<w.length;D+=Ae){let g=w.slice(D,D+Ae),M=JSON.stringify(g.map((N)=>Object.fromEntries(c.map((I)=>[I,d[N][I]??null]))),Ge);if(!y){await i.run(v,[M]);for(let N of g)await s[N]._markInserted(d[N]);continue}let b=(await i.all(`${v} RETURNING ${a}`,[M])).map((N)=>N[a]),h=b.every((N)=>typeof N==="number"||typeof N==="bigint")?[...b].sort((N,I)=>N<I?-1:N>I?1:0):b;for(let N=0;N<g.length;N++)await s[g[N]]._markInserted(d[g[N]],h[N])}continue}let A=Ee(Math.max(1,Math.floor(Qe/c.length)));for(let k=0;k<w.length;){let _=Math.min(A,Ee(w.length-k)),v=w.slice(k,k+_);k+=_;let D=`INSERT INTO ${t.table} (${c.join(", ")}) VALUES ${v.map(()=>`(${c.map(()=>"?").join(", ")})`).join(", ")}`,g=v.flatMap((h)=>c.map((N)=>d[h][N]));if(!y){await i.run(D,g);for(let h of v)await s[h]._markInserted(d[h]);continue}let M=(await i.all(`${D} RETURNING ${a}`,g)).map((h)=>h[a]),b=M.every((h)=>typeof h==="number"||typeof h==="bigint")?[...M].sort((h,N)=>h<N?-1:h>N?1:0):M;for(let h=0;h<v.length;h++)await s[v[h]]._markInserted(d[v[h]],b[h])}}return s},async updateOrCreate(o,s){let i=new C(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 C(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 P().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(o={}){return new j(t,o,!1)},latest:(o="created_at")=>new C(t).orderByDesc(o),oldest:(o="created_at")=>new C(t).orderBy(o,"asc"),max:(o)=>new C(t).max(o),min:(o)=>new C(t).min(o),avg:(o)=>new C(t).avg(o),sum:(o)=>new C(t).sum(o),pluck(o){return new C(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 C(t).where(a,d)}return Reflect.get(o,s)}})}function jt(t){let r=nt(t);if(t?.name)Ue(t.name,r);return r}async function Wn(t){let r=P(),o=S(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=S(a);if(i.has(u))continue;i.add(u);let f=Me(d.type),w=Ie(f);if(u.endsWith("_id")&&(f===void 0||O(f)))w="INTEGER";let c=`${u} ${w}`;if(d.unique)c+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let y=d.foreignKey;if(c+=` REFERENCES ${y.table}(${y.column??"id"})`,y.onDelete)c+=` ON DELETE ${y.onDelete.toUpperCase()}`;if(y.onUpdate)c+=` ON UPDATE ${y.onUpdate.toUpperCase()}`}s.push(c)}for(let a of B(t.belongsTo)){let d=a.foreignKey??`${S(a.model)}_id`;if(i.has(d))continue;i.add(d),s.push(`${d} INTEGER`)}if(ee(t))for(let a of["created_at","updated_at"]){if(i.has(a))continue;i.add(a),s.push(`${a} TEXT`)}if(ne(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 Un(t,r,o){let s=P(),i=t.traits?.useSeeder,a=r??(typeof i==="object"&&i?i.count:10);if(!o)try{let d=await import("./chunk-r2ta1rnj.js");o=_t(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[w,c]of Object.entries(t.attributes))if(c.factory)u[S(w)]=c.factory(o);if(ee(t)){let w=Z();u.created_at=w,u.updated_at=w}if(t.traits?.useUuid)u.uuid=crypto.randomUUID();let f=Object.keys(u);await s.run(`INSERT INTO ${t.table} (${f.join(", ")}) VALUES (${f.map(()=>"?").join(", ")})`,Object.values(u))}}var ie=new Map;function an(t){return ie.get(t)}function on(){return[...ie.values()]}function ln(){return Object.fromEntries(ie)}function cn(t){return ie.has(t)}function un(){ie.clear(),It()}function qt(t,r){return ie.set(t,r),r}function rt(){return typeof window<"u"&&typeof document<"u"}function dn(t){let r;if(rt())r=Ve(t);else{let o=jt(t);r=Object.assign(o,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return qt(t.name,r),r}function fn(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
2
+ import{Ve}from"./chunk-wvae8521.js";import{p,n,e,R,K,T,qe,m,x,l,lt,te}from"./chunk-bqywz1ww.js";function O(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function Me(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 Ie(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 re(t){if(typeof t==="number")return{length:t};return t}function ge(t){if(typeof t==="number")return{max:t};return t}function Fe(t){return typeof t==="function"}function We(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 X(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[We(s)];if(Fe(a))return a.bind(o);return}})}function _t(t){let r=(c)=>{let y=Array.isArray(c)?c:[],A=Math.floor(Math.random()*y.length);return y[A]},o=()=>t.string,s=()=>t.number,i=()=>t.random,a=X(t.string,{alpha:(c)=>o()?.alpha?.(re(c)),alphanumeric:(c)=>o()?.alphanumeric?.(re(c)),numeric:(c)=>o()?.numeric?.(re(c)),sample:(c)=>o()?.sample?.(re(c)),hexadecimal:(c)=>o()?.hexadecimal?.(re(c))}),d=X(t.number,{int:(c)=>s()?.int?.(ge(c)),float:(c)=>{let y=ge(c);return Ke(Number(s()?.float?.(y)??0),y)}}),u=X(t.helpers,{arrayElement:r,arrayElements:(c,y)=>{let A=[...Array.isArray(c)?c:[]],k=typeof y==="number"?y:Math.max(1,Math.floor(Math.random()*A.length));for(let _=A.length-1;_>0;_-=1){let v=Math.floor(Math.random()*(_+1));[A[_],A[v]]=[A[v],A[_]]}return A.slice(0,Math.min(k,A.length))},shuffle:(c)=>{let y=[...Array.isArray(c)?c:[]];for(let A=y.length-1;A>0;A-=1){let k=Math.floor(Math.random()*(A+1));[y[A],y[k]]=[y[k],y[A]]}return y},maybe:(c,y)=>{let A=typeof y?.probability==="number"?y.probability:0.5;return Math.random()<A?c():void 0},slugify:(c)=>String(c??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),w={string:a,number:d,helpers:u,datatype:{boolean:(c)=>{let y=typeof c==="number"?c:c?.probability;if(typeof y==="number")return Math.random()<y;return Boolean(i()?.boolean?.())},number:(c)=>Number(s()?.int?.(ge(c))??0),float:(c)=>Ke(Number(s()?.float?.(c)??0),c),uuid:()=>crypto.randomUUID(),string:(c)=>String(o()?.alphanumeric?.({length:c??10})??""),hexadecimal:(c)=>String(o()?.hexadecimal?.(re(c))??""),array:(c)=>Array.from({length:c??3},()=>o()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:o()?.alphanumeric?.({length:8})})},location:X(t.address),address:X(t.address),vehicle:X(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:X(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(c,y){if(y in w)return w[y];let A=c[y];if(A&&typeof A==="object")return X(A);return A}})}function E(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,...typeof r.relationName==="string"?{relationName:r.relationName}:{}}}return null}function B(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(E).filter((o)=>o!==null)}function Z(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var Pe=/^[A-Z_][A-Z0-9_]*$/i;function z(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(!Pe.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Oe(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||!Pe.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 Re(t,r){if(r.length!==1)return r;let o=r[0];if(Array.isArray(o))return[...o];if(o===void 0&&te(t)===0)return[];return r}var ue=null,ke=new Map;function Ue(t,r){ke.set(t,r),se.clear()}function It(){ke.clear(),se.clear()}function F(t){if(!ue)try{ue=import.meta.require("./chunk-ymnm4hd2.js").getModel}catch{ue=()=>{return}}return ue(t)??ke.get(t)}var de=new Map,He=500;function _e(t){let r=de.get(t);if(r!==void 0)return r;let o=lt(t,"postgres");if(de.size>=He)de.clear();return de.set(t,o),o}function Lt(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 Kt(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 we{sqliteDb;dialect="sqlite";constructor(t){this.sqliteDb=t}all(t,r){return Promise.resolve(this.sqliteDb.query(t).all(...p(r)))}get(t,r){return Promise.resolve(this.sqliteDb.query(t).get(...p(r))??void 0)}run(t,r){let o=this.sqliteDb.run(t,p(r));return Promise.resolve({changes:o.changes,lastInsertId:o.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class De{dialect;constructor(t){this.dialect=t}conn(){return T()}text(t){return this.dialect==="postgres"?_e(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:Lt(o),lastInsertId:Kt(o)}}async insert(t,r,o){if(this.dialect==="postgres"){let a=await this.conn().unsafe(`${_e(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=Kt(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:Lt(s)||1,lastInsertId:i}}}var V=null,me=!1,H=null,oe=null,ce=null,fe=null;function Fn(t){if(t.database instanceof Te)V=t.database,me=!1;else V=new Te(t.database||":memory:",{create:!0}),me=!0,R(V);H=null,oe=null}function jn(){let t=me,r=V;if(V=null,me=!1,H=null,oe=null,ce=null,fe=null,t&&r)try{r.close()}catch{}}var xe=!1;function P(){if(V){if(!H||oe!==V)H=new we(V),oe=V,ce="sqlite",fe=null;return H}let t=e.dialect,r=e.database?.database??null,o=`${r??""}|${K()?.url??""}`;if(H&&oe===null&&ce===t&&fe===o)return H;if(oe=null,ce=t,fe=o,t==="sqlite"&&K())H=new De(t);else if(t==="sqlite"){if(!r&&!xe)xe=!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});R(s),H=new we(s)}else H=new De(t);return H}function qn(){let t=P();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,Ae=1000;function ze(t,r,o){let s=t.attributes,i=new Map(Object.entries(s).map(([a,d])=>[S(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 f=typeof u;if(f!=="string"&&f!=="number"&&f!=="boolean"&&f!=="bigint")return!1}return!0}function Ge(t,r){return typeof r==="bigint"?r.toString():r}function Ee(t){return 2**Math.floor(Math.log2(t))}var W="deleted_at",ve=500,be="__btm_rel__";function ne(t){let r=t.traits;return Boolean(r?.useSoftDeletes||r?.softDeletable)}function ee(t){let r=t.traits;return Boolean(r?.useTimestamps||r?.timestampable)}var Ce=new WeakMap;function Xe(t){let r=Ce.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 Ce.set(t,o),o}function Be(t){let r={};for(let[o,s]of Object.entries(t))r[S(o)]=s;return r}function Ye(t){for(let r in t)if(S(r)!==r)return Be(t);return t}function Ze(t,r){if(t[r])return t[r];let o=S(r);if(t[o])return t[o];for(let s of Object.keys(t))if(S(s)===o)return t[s];return}class j{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_exists;_relations={};constructor(t,r,o){this._definition=t,this._exists=o,this._attributes=Ye({...r}),this._original=null;let s=Xe(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 f=je(t,d);if(!f||f.type!=="belongsToMany")throw Error(`[orm] relation '${d}' did not resolve to a belongsToMany on '${t.name}'`);let w=F(f.relatedModelName),c=w?.getDefinition?.()||w?.definition;if(!c)throw Error(`[orm] related model '${f.relatedModelName}' is not registered`);return new Ft(i,t,f,c)};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[S(t)]}getAttribute(t){return this._attributes[S(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[S(t)]=r}only(t){let r={};for(let o of t)r[o]=this._attributes[S(o)];return r}except(t){let r=new Set(t.map((s)=>S(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=S(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()[S(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=Ze(r,o),a=!i&&S(o).endsWith("_id");if(i?.fillable&&!i?.guarded||a){if(this._original===null)this._original={...this._attributes};this._attributes[S(o)]=s}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Be(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,f]of Object.entries(o)){if(f.guarded&&!this._forced.has(S(u)))continue;let w=S(u);if(this._attributes[w]!==void 0)s[w]=this._attributes[w]}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(ee(this._definition)){let u=Z(),f=this._attributes.created_at;s.created_at=f===void 0||f===null?u:f,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[S(r)]=o(this._attributes)}async save(){let t=P(),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(ee(this._definition)){let u=Z();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=P(),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 j(this._definition,s,!0)}async delete(){let t=P(),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),ne(this._definition)){let i=Z();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[i,o]),this._attributes[W]=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 P().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await o?.afterDelete?.(this),!0}async restore(){if(!ne(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 P().run(`UPDATE ${this._definition.table} SET ${W} = ? WHERE ${t} = ?`,[null,r]),this._attributes[W]=null,this._original=null,this}trashed(){return this._attributes[W]!=null}async refresh(){let t=P(),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 j(this._definition,r,!1)}toArray(){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.toArray());else if(s)r[o]=s.toArray();else r[o]=null;return r}toJSON(){return this.toArray()}}var Ne=new Map,$e=new Map,se=new Map,Je=1000;function q(t){return S(t)}function S(t){let r=Ne.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),Ne.set(t,r),r}function Y(t){let r=$e.get(t);if(r!==void 0)return r;return r=qe(t),$e.set(t,r),r}var he=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],et=[...he,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Se(t,r){let o=t[r];if(!o)return[];if(Array.isArray(o))return o.map((s)=>{let i=E(s);return i?.relationName??i?.model??""}).filter(Boolean);if(typeof o==="object")return Object.keys(o);if(typeof o==="string")return[o];return[]}function tt(t,r){let o=t.name??t.table??"model",i=et.filter((d)=>Se(t,d).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((d)=>!he.includes(d));if(i.length>0)return`[orm] '${o}' declares '${r}' as ${i.join("/")}, which eager loading does not support yet. Supported kinds: ${he.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let a=he.flatMap((d)=>Se(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 je(t,r){let{name:o,table:s}=t,i=t.primaryKey||"id";function a(D){if(!D)return null;if(Array.isArray(D)){for(let g of D){let M=E(g);if(M&&(M.relationName??M.model).toLowerCase()===r.toLowerCase())return M.model}return null}if(typeof D==="object"){for(let[g,M]of Object.entries(D))if(g===r||g.toLowerCase()===r.toLowerCase())return typeof M==="string"?M:M?.model||M?.target||g}return null}function d(){let D=t.belongsTo;if(!D)return null;let g=r.toLowerCase(),M=(b)=>{if(typeof b==="string")return{model:b};if(b&&typeof b==="object"&&typeof b.model==="string")return{model:b.model,foreignKey:b.foreignKey};return null};if(Array.isArray(D)){for(let b of D){let h=M(b);if(h&&(E(b)?.relationName??h.model).toLowerCase()===g)return h}return null}if(typeof D==="object"){for(let[b,h]of Object.entries(D))if(b===r||b.toLowerCase()===g)return M(h)}return null}function u(){let D=t.belongsToMany;if(!D)return null;if(Array.isArray(D)){for(let g of D)if(typeof g==="string"){if(g.toLowerCase()===r.toLowerCase())return{entry:g}}else if(g&&typeof g==="object"&&g.model){if(g.model.toLowerCase()===r.toLowerCase())return{entry:g}}return null}if(typeof D==="object"){for(let[g,M]of Object.entries(D))if(g===r||g.toLowerCase()===r.toLowerCase())return{entry:M}}return null}function f(D){let g=t[D];if(!g)return null;let M=r.toLowerCase();if(Array.isArray(g)){for(let b of g){let h=typeof b==="string"?b:String(b?.model??"");if(!h||h.toLowerCase()!==M)continue;let N=typeof b==="object"?b?.morphName:void 0;return{model:h,morphName:String(N??`${S(o)}able`)}}return null}if(typeof g==="object")for(let[b,h]of Object.entries(g)){let N=typeof h==="string"?h:String(h?.model??"");if(b.toLowerCase()!==M&&N.toLowerCase()!==M)continue;let I=typeof h==="object"?h?.morphName:void 0;return{model:N,morphName:String(I??b)}}return null}for(let D of["morphMany","morphOne"]){let g=f(D);if(!g)continue;let b=F(g.model)?.getTable?.()||Y(g.model);return{type:D,relatedModelName:g.model,relatedTable:b,foreignKey:`${g.morphName}_id`,localKey:i,morphTypeColumn:`${g.morphName}_type`,morphTypeValue:s}}let w=a(t.hasMany);if(w){let g=F(w)?.getTable?.()||Y(w),M=S(o)+"_id";return{type:"hasMany",relatedModelName:w,relatedTable:g,foreignKey:M,localKey:i}}let c=a(t.hasOne);if(c){let g=F(c)?.getTable?.()||Y(c),M=S(o)+"_id";return{type:"hasOne",relatedModelName:c,relatedTable:g,foreignKey:M,localKey:i}}let y=d();if(y){let D=y.model,g=F(D),M=g?.getTable?.()||Y(D),b=g?.getDefinition?.()?.primaryKey||"id",h=y.foreignKey||`${S(D)}_id`;return{type:"belongsTo",relatedModelName:D,relatedTable:M,foreignKey:h,localKey:b}}let A=u();if(A){let D=typeof A.entry==="object",g=D?A.entry.model:A.entry,b=F(g)?.getTable?.()||Y(g),h=D?A.entry:null,N,I;if(h?.table)N=h.table;else if(h?.through){I=h.through;let L=F(h.through);if(!L)throw Error(`[orm] belongsToMany relation '${r}' on '${o}' references unknown through model '${h.through}'. Make sure '${h.through}' is registered.`);N=L.getTable?.()||L.getDefinition?.()?.table||Y(h.through)}else{let L=le(s),Q=le(b);N=[L,Q].sort().join("_")}let U=h?.foreignKey||`${le(s)}_id`,J=h?.relatedKey||`${le(b)}_id`,G=[];if(h?.pivot?.columns)for(let L of Object.keys(h.pivot.columns))G.push(L);if(I){let L=F(I),Q=L?.getDefinition?.()||L?.definition,ye=Q?.attributes??{},Le=Q?.primaryKey??"id";for(let ae of Object.keys(ye)){if(ae===U||ae===J||ae===Le)continue;if(!G.includes(ae))G.push(ae)}}return{type:"belongsToMany",relatedModelName:g,relatedTable:b,foreignKey:U,localKey:i,pivotTable:N,pivotFkParent:U,pivotFkRelated:J,pivotColumns:G,pivotModelName:I,pivotTimestamps:Boolean(h?.pivot?.timestamps)}}let k=(D,g)=>{if(!D||typeof D!=="object"||Array.isArray(D))return null;let M=D[r]??D[Object.keys(D).find((Q)=>Q.toLowerCase()===r.toLowerCase())??""];if(!M||typeof M!=="object")return null;let{through:b,target:h}=M;if(!b||!h)return null;let N=F(b),I=N?.getDefinition?.()||N?.definition,U=N?.getTable?.()||I?.table||Y(b),J=I?.primaryKey||"id",L=F(h)?.getTable?.()||Y(h);return{type:g,relatedModelName:h,relatedTable:L,foreignKey:`${S(o)}_id`,localKey:i,throughTable:U,throughForeignKey:`${S(o)}_id`,throughLocalKey:J,targetForeignKey:`${le(U)}_id`}},_=k(t.hasManyThrough,"hasManyThrough");if(_)return _;let v=k(t.hasOneThrough,"hasOneThrough");if(v)return v;return null}function pe(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 le(t){return m(e.relations?.singularizeStrategy)(t)}class Ft{_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(Oe(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 ${be}${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,f]of Object.entries(s))if(u.startsWith(be))i[u.slice(be.length)]=f;else if(u!==r&&u!==o)a[u]=f;let d=new j(this._relatedDef,i,!0);return d.pivot=a,d})}async get(){let t=P(),{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=P(),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 Z()}async attach(t,r={}){let o=P(),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 f=Object.keys(u),w=f.map(()=>"?").join(", "),c=`INSERT INTO ${this.pivotTable} (${f.join(", ")}) VALUES (${w})`,y=f.map((A)=>u[A]);await o.run(c,y),a++}return a}async detach(t){let r=P(),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=P(),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((f)=>`${f} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${a} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,u=[...i.map((f)=>s[f]),this.parentId,t];return(await o.run(d,u)).changes}async sync(t){let r=P(),o=new Map;for(let w of t)if(w!=null&&typeof w==="object"&&"id"in w){let{id:c,...y}=w;o.set(c,y)}else o.set(w,{});let s=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),i=new Set(s.map((w)=>w[this.fkRelated])),a=[],d=[],u=[],f=[...i].filter((w)=>!o.has(w));if(f.length>0)await this.detach(f),d.push(...f);for(let[w,c]of o)if(!i.has(w))await this.attach(w,c),a.push(w);else if(Object.keys(c).length>0)await this.updateExistingPivot(w,c),u.push(w);return{attached:a,detached:d,updated:u}}async toggle(t){let r=P(),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((f)=>f[this.fkRelated])),d=o.filter((f)=>!a.has(f)),u=o.filter((f)=>a.has(f));if(d.length>0)await this.attach(d);if(u.length>0)await this.detach(u);return{attached:d,detached:u}}}class C{_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 z(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return z(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return z(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return z(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:Re(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Re(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 C(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 z(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){z(t,"whereNotBetween(column)");let o=q(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(Oe(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=q(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(q(o.column),i,o.operator==="not in",i.map(()=>"?").join(", ")),t.push(...i)}else s=`${q(o.column)} ${o.operator} ?`,t.push(o.value);r.push({conn:o.boolean==="or"?"OR":"AND",sql:s})}return x(r)}softDeleteClause(){if(this._trashed==="include"||!ne(this._definition))return"";return this._trashed==="only"?`${W} IS NOT NULL`:`${W} 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:q(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)=>`${q(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=P(),s=this._definition.primaryKey||"id",i=`${this._definition.name}:${t}`,a=se.get(i);if(a===void 0){if(a=je(this._definition,t),se.size>=Je)se.clear();se.set(i,a)}if(!a)throw Error(tt(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=pe(r,s);if(u.length===0)return;let f=u.map(()=>"?").join(", "),w=a.morphTypeColumn?` AND ${a.morphTypeColumn} = ?`:"",c=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.foreignKey} IN (${f})${w}`,a.morphTypeColumn?[...u,a.morphTypeValue]:u),y=F(a.relatedModelName),A=y?.getDefinition?.()||y?.definition||this._definition;if(!d){let k=new Map;for(let _ of c){let v=_[a.foreignKey];if(!k.has(v))k.set(v,[]);k.get(v).push(_)}for(let _ of r){let v=k.get(_.get(s))||[];_.setRelation(t,v.map((D)=>new j(A,D,!0)))}}else{let k=new Map;for(let _ of c){let v=_[a.foreignKey];if(!k.has(v))k.set(v,_)}for(let _ of r){let v=k.get(_.get(s));_.setRelation(t,v?new j(A,v,!0):null)}}}if(a.type==="belongsTo"){let u=new Set;for(let _ of r){let v=_._attributes[a.foreignKey];if(v!=null)u.add(v)}let f=[...u];if(f.length===0){for(let _ of r)_.setRelation(t,null);return}let w=f.map(()=>"?").join(", "),c=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.localKey} IN (${w})`,f),y=F(a.relatedModelName),A=y?.getDefinition?.()||y?.definition||this._definition,k=new Map;for(let _ of c)k.set(_[a.localKey],_);for(let _ of r){let v=_._attributes[a.foreignKey],D=k.get(v);_.setRelation(t,D?new j(A,D,!0):null)}}if(a.type==="belongsToMany"){let u=pe(r,s);if(u.length===0)return;if(!a.pivotTable||!a.pivotFkParent||!a.pivotFkRelated)return;let f=u.map(()=>"?").join(", "),w=await o.all(`SELECT * FROM ${a.pivotTable} WHERE ${a.pivotFkParent} IN (${f})`,u);if(w.length===0){for(let b of r)b.setRelation(t,[]);return}let c=new Set;for(let b of w){let h=b[a.pivotFkRelated];if(h!=null)c.add(h)}let y=[...c],A=F(a.relatedModelName),k=A?.getDefinition?.()||A?.definition||this._definition,_=k?.primaryKey||"id",v=[];if(y.length>0){let b=y.map(()=>"?").join(", ");v=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${_} IN (${b})`,y)}let D=new Map;for(let b of v)D.set(b[_],b);let g=new Map;for(let b of w){let h=b[a.pivotFkParent];if(!g.has(h))g.set(h,[]);g.get(h).push(b)}let M=new Set([a.pivotFkParent,a.pivotFkRelated]);for(let b of r){let h=b.get(s),I=(g.get(h)||[]).map((U)=>{let J=D.get(U[a.pivotFkRelated]);if(!J)return null;let G=new j(k,J,!0),L={};for(let[Q,ye]of Object.entries(U))if(!M.has(Q))L[Q]=ye;return G.pivot=L,G}).filter((U)=>U!==null);b.setRelation(t,I)}}if(a.type==="hasManyThrough"||a.type==="hasOneThrough"){let u=pe(r,s);if(u.length===0)return;let f=a.throughLocalKey||"id",w=u.map(()=>"?").join(", "),c=await o.all(`SELECT ${f}, ${a.throughForeignKey} FROM ${a.throughTable} WHERE ${a.throughForeignKey} IN (${w})`,u);if(c.length===0){for(let M of r)M.setRelation(t,a.type==="hasManyThrough"?[]:null);return}let y=new Map;for(let M of c)y.set(M[f],M[a.throughForeignKey]);let A=[...new Set(c.map((M)=>M[f]))],k=A.map(()=>"?").join(", "),_=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.targetForeignKey} IN (${k})`,A),v=F(a.relatedModelName),D=v?.getDefinition?.()||v?.definition||this._definition,g=new Map;for(let M of _){let b=y.get(M[a.targetForeignKey]);if(b==null)continue;if(!g.has(b))g.set(b,[]);g.get(b).push(new j(D,M,!0))}for(let M of r){let b=g.get(M.get(s))||[];M.setRelation(t,a.type==="hasManyThrough"?b:b[0]??null)}}}async get(){let t=P(),{sql:r,params:o}=this.buildQuery(),i=(await t.all(r,o)).map((a)=>new j(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=P(),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){z(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let o=P(),s=[r],i=q(t),a=`UPDATE ${this._definition.table} SET ${i} = ${i} + ?`;if(ee(this._definition))a+=", updated_at = ?",s.push(Z());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 C(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){z(t,"pluck(column)");let r=P(),o=[],s=q(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)=>`${q(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){z(r,`${t}(column)`);let o=P(),s=[],i=`SELECT ${t}(${q(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 f=Number(u);return u.trim()!==""&&!Number.isNaN(f)?f: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=ne(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=P(),o=this._definition.table,s=this._definition.hooks,i=[],a=this.composeWhere(i);if(t&&this._trashed==="include")a=a?`(${a}) AND ${W} IS NULL`:`${W} IS NULL`;let d=a?` WHERE ${a}`:"",u=t?Z():void 0;if(!s?.beforeDelete&&!s?.afterDelete)return t?(await r.run(`UPDATE ${o} SET ${W} = ?${d}`,[u,...i])).changes:(await r.run(`DELETE FROM ${o}${d}`,i)).changes;let f=this._definition.primaryKey||"id",c=(await r.all(`SELECT * FROM ${o}${d}`,i)).map((k)=>new j(this._definition,k,!0)),y=c.map((k)=>k._attributes[f]);if(y.some((k)=>k==null))throw Error(`Cannot delete a model without a primary key: '${f}' is missing from a matching row`);for(let k of c)await s.beforeDelete?.(k);let A=0;for(let k=0;k<y.length;k+=ve){let _=y.slice(k,k+ve),v=`${f} IN (${_.map(()=>"?").join(", ")})`;A+=t?(await r.run(`UPDATE ${o} SET ${W} = ? WHERE ${v}`,[u,..._])).changes:(await r.run(`DELETE FROM ${o} WHERE ${v}`,_)).changes}for(let k of c){if(t)k._attributes[W]=u;await s.afterDelete?.(k)}return A}async update(t){this.assertNoUnappliedClauses("update");let r=P(),o=Object.entries(t),s=o.map(([u])=>`${q(u)} = ?`).join(", "),i=o.map(([,u])=>u);if(ee(this._definition))i.push(Z());let a=`UPDATE ${this._definition.table} SET ${s}${ee(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(i);if(d)a+=` WHERE ${d}`;return(await r.run(a,i)).changes}}function nt(t){let r={query:()=>new C(t),where(o,s,i){return new C(t).where(o,s,i)},orWhere(o,s,i){return new C(t).orWhere(o,s,i)},whereIn(o,s){return new C(t).whereIn(o,s)},whereNotIn(o,s){return new C(t).whereNotIn(o,s)},whereNull(o){return new C(t).whereNull(o)},whereNotNull(o){return new C(t).whereNotNull(o)},whereLike(o,s){return new C(t).whereLike(o,s)},orderBy(o,s="asc"){return new C(t).orderBy(o,s)},orderByDesc(o){return new C(t).orderByDesc(o)},select(...o){return new C(t).select(...o)},with(...o){return new C(t).with(...o)},limit:(o)=>new C(t).limit(o),take:(o)=>new C(t).take(o),skip:(o)=>new C(t).skip(o),withTrashed:()=>new C(t).withTrashed(),onlyTrashed:()=>new C(t).onlyTrashed(),async find(o){let s=P(),i=t.primaryKey||"id",a=ne(t)?` AND ${W} IS NULL`:"",d=await s.get(`SELECT * FROM ${t.table} WHERE ${i} = ?${a}`,[o]);return d?new j(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=P(),i=t.primaryKey||"id",a=ne(t)?` AND ${W} IS NULL`:"";return(await s.all(`SELECT * FROM ${t.table} WHERE ${i} IN (${o.map(()=>"?").join(", ")})${a}`,o)).map((u)=>new j(t,u,!0))},all:()=>new C(t).get(),first:()=>new C(t).first(),firstOrFail:()=>new C(t).firstOrFail(),last:()=>new C(t).last(),count:()=>new C(t).count(),exists:()=>new C(t).exists(),doesntExist:()=>new C(t).doesntExist(),paginate:(o,s)=>new C(t).paginate(o,s),whereBetween(o,s){return new C(t).whereBetween(o,s)},whereNotBetween(o,s){return new C(t).whereNotBetween(o,s)},async create(o){let s=new j(t,o,!1);return await s.save(),s},async createMany(o){let s=o.map((f)=>new j(t,f,!1));if(!s.length)return[];let i=P(),a=t.primaryKey||"id",d=[];for(let f of s)d.push(await f._prepareInsert());let u=new Map;d.forEach((f,w)=>{let c=Object.keys(f).join("\x00"),y=u.get(c);if(y)y.push(w);else u.set(c,[w])});for(let[f,w]of u){let c=f?f.split("\x00"):[],y=!c.includes(a);if(!c.length||y&&i.dialect==="mysql"){for(let k of w){let _=d[k],v=Object.keys(_),D=await i.insert(v.length?`INSERT INTO ${t.table} (${v.join(", ")}) VALUES (${v.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(_),a);await s[k]._markInserted(_,y?D.lastInsertId:void 0)}continue}if(i.dialect==="postgres"&&ze(t,c,w.map((k)=>d[k]))){let k=t.table,_=c.join(", "),v=`INSERT INTO ${k} (${_}) SELECT ${_} FROM jsonb_populate_recordset(NULL::${k}, (?::text)::jsonb)`;for(let D=0;D<w.length;D+=Ae){let g=w.slice(D,D+Ae),M=JSON.stringify(g.map((N)=>Object.fromEntries(c.map((I)=>[I,d[N][I]??null]))),Ge);if(!y){await i.run(v,[M]);for(let N of g)await s[N]._markInserted(d[N]);continue}let b=(await i.all(`${v} RETURNING ${a}`,[M])).map((N)=>N[a]),h=b.every((N)=>typeof N==="number"||typeof N==="bigint")?[...b].sort((N,I)=>N<I?-1:N>I?1:0):b;for(let N=0;N<g.length;N++)await s[g[N]]._markInserted(d[g[N]],h[N])}continue}let A=Ee(Math.max(1,Math.floor(Qe/c.length)));for(let k=0;k<w.length;){let _=Math.min(A,Ee(w.length-k)),v=w.slice(k,k+_);k+=_;let D=`INSERT INTO ${t.table} (${c.join(", ")}) VALUES ${v.map(()=>`(${c.map(()=>"?").join(", ")})`).join(", ")}`,g=v.flatMap((h)=>c.map((N)=>d[h][N]));if(!y){await i.run(D,g);for(let h of v)await s[h]._markInserted(d[h]);continue}let M=(await i.all(`${D} RETURNING ${a}`,g)).map((h)=>h[a]),b=M.every((h)=>typeof h==="number"||typeof h==="bigint")?[...M].sort((h,N)=>h<N?-1:h>N?1:0):M;for(let h=0;h<v.length;h++)await s[v[h]]._markInserted(d[v[h]],b[h])}}return s},async updateOrCreate(o,s){let i=new C(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 C(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 P().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(o={}){return new j(t,o,!1)},latest:(o="created_at")=>new C(t).orderByDesc(o),oldest:(o="created_at")=>new C(t).orderBy(o,"asc"),max:(o)=>new C(t).max(o),min:(o)=>new C(t).min(o),avg:(o)=>new C(t).avg(o),sum:(o)=>new C(t).sum(o),pluck(o){return new C(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 C(t).where(a,d)}return Reflect.get(o,s)}})}function jt(t){let r=nt(t);if(t?.name)Ue(t.name,r);return r}async function Wn(t){let r=P(),o=S(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=S(a);if(i.has(u))continue;i.add(u);let f=Me(d.type),w=Ie(f);if(u.endsWith("_id")&&(f===void 0||O(f)))w="INTEGER";let c=`${u} ${w}`;if(d.unique)c+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let y=d.foreignKey;if(c+=` REFERENCES ${y.table}(${y.column??"id"})`,y.onDelete)c+=` ON DELETE ${y.onDelete.toUpperCase()}`;if(y.onUpdate)c+=` ON UPDATE ${y.onUpdate.toUpperCase()}`}s.push(c)}for(let a of B(t.belongsTo)){let d=a.foreignKey??`${S(a.model)}_id`;if(i.has(d))continue;i.add(d),s.push(`${d} INTEGER`)}if(ee(t))for(let a of["created_at","updated_at"]){if(i.has(a))continue;i.add(a),s.push(`${a} TEXT`)}if(ne(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 Un(t,r,o){let s=P(),i=t.traits?.useSeeder,a=r??(typeof i==="object"&&i?i.count:10);if(!o)try{let d=await import("./chunk-r2ta1rnj.js");o=_t(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[w,c]of Object.entries(t.attributes))if(c.factory)u[S(w)]=c.factory(o);if(ee(t)){let w=Z();u.created_at=w,u.updated_at=w}if(t.traits?.useUuid)u.uuid=crypto.randomUUID();let f=Object.keys(u);await s.run(`INSERT INTO ${t.table} (${f.join(", ")}) VALUES (${f.map(()=>"?").join(", ")})`,Object.values(u))}}var ie=new Map;function an(t){return ie.get(t)}function on(){return[...ie.values()]}function ln(){return Object.fromEntries(ie)}function cn(t){return ie.has(t)}function un(){ie.clear(),It()}function qt(t,r){return ie.set(t,r),r}function rt(){return typeof window<"u"&&typeof document<"u"}function dn(t){let r;if(rt())r=Ve(t);else{let o=jt(t);r=Object.assign(o,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return qt(t.name,r),r}function fn(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
3
3
  export{O,Ie,_t,E,B,It,Lt,Kt,Fn,jn,qn,Ft,jt,Wn,Un,an,on,ln,cn,un,qt,dn,fn};