bun-query-builder 0.2.63 → 0.2.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +2 -2
- package/dist/{chunk-wyr48f41.js → chunk-0f4s7pd5.js} +1 -1
- package/dist/{chunk-0h7e47md.js → chunk-a11rdptj.js} +2 -2
- package/dist/chunk-t384ajfz.js +2 -0
- package/dist/{chunk-2jmgdx61.js → chunk-xbpyj4mw.js} +2 -2
- package/dist/src/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-eczymkcb.js +0 -2
package/dist/bin/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import"../chunk-
|
|
3
|
+
import"../chunk-xbpyj4mw.js";import"../chunk-7xvyccgk.js";import{J,z,Y,X,N,Z,ee,te,ne,B,re,P,O,ie,se,_,ae,oe,v,le,b,k,C,me,he,I,ge,L,pe,K,F,R,j,ye,be,Te,we,q,Se,De}from"../chunk-a11rdptj.js";import"../chunk-55jccfgb.js";import{existsSync as Le}from"fs";import Q from"fs/promises";import Ie from"os";import ce from"path";import E from"process";import{EventEmitter as Ne}from"events";import x from"process";import Ee from"process";import fe from"process";import G from"process";import V from"process";import Me from"tty";import kt,{stdin as Xt,stdout as Zt}from"process";class Be{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Ie.homedir(),t=ce.join(e,".config","clapp");this.configPath=ce.join(t,"telemetry.json")}async isEnabled(){if(E.env.DO_NOT_TRACK==="1"||E.env.DO_NOT_TRACK==="true")return!1;if(E.env.NO_TELEMETRY==="1"||E.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:Ie.platform(),nodeVersion:E.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:E.env.DO_NOT_TRACK==="1"||E.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Le(this.configPath)){let e=await Q.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=ce.dirname(this.configPath);await Q.mkdir(t,{recursive:!0}),await Q.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 Nt=new Be;function de(e){return e.replace(/[<[].+/,"").trim()}function Pe(e){let t=/<([^>]+)>/g,i=/\[([^\]]+)\]/g,s=[],r=(l)=>{let n=!1,a=l[1];if(a.startsWith("..."))a=a.slice(3),n=!0;return{required:l[0].startsWith("<"),value:a,variadic:n}},o;while(o=t.exec(e))s.push(r(o));let d;while(d=i.exec(e))s.push(r(d));return s}function We(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,d)=>d!==i&&o.names.some((l)=>s.names.includes(l))&&typeof o.required==="boolean"))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t}function ke(e){return e.reduce((t,i)=>t.length>=i.length?t:i,"")}function ue(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function U(e){return e.replace(/([a-z])-([a-z])/g,(t,i,s)=>i+s.toUpperCase())}function Fe(e,t,i){let s=0,r=t.length,o=e,d;for(;s<r;++s)d=o[t[s]],o=o[t[s]]=s===r-1?i:d!=null?d:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]}function ze(e,t){for(let i of Object.keys(t)){let s=t[i];if(s.shouldTransform){if(e[i]=Array.prototype.concat.call([],e[i]),typeof s.transformFunction==="function")e[i]=e[i].map(s.transformFunction)}}}function Ue(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function A(e){return e.split(".").map((t,i)=>i===0?U(t):t).join(".")}class D 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 Ge(e){if(e instanceof D)return!0;return!!e&&typeof e==="object"&&e.name==="ClappError"&&typeof e.message==="string"}function He(){let{env:e}=Ee,{TERM:t,TERM_PROGRAM:i}=e;if(Ee.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 H="\x1B",g=`${H}[`;var _e={to(e,t){if(!t)return`${g}${e+1}G`;return`${g}${t+1};${e+1}H`},move(e,t){let i="";if(e<0)i+=`${g}${-e}D`;else if(e>0)i+=`${g}${e}C`;if(t<0)i+=`${g}${-t}A`;else if(t>0)i+=`${g}${t}B`;return i},up:(e=1)=>`${g}${e}A`,down:(e=1)=>`${g}${e}B`,forward:(e=1)=>`${g}${e}C`,backward:(e=1)=>`${g}${e}D`,nextLine:(e=1)=>`${g}E`.repeat(e),prevLine:(e=1)=>`${g}F`.repeat(e),left:`${g}G`,hide:`${g}?25l`,show:`${g}?25h`,save:`${H}7`,restore:`${H}8`};var Ft={screen:`${g}2J`,up:(e=1)=>`${g}1J`.repeat(e),down:(e=1)=>`${g}J`.repeat(e),line:`${g}2K`,lineEnd:`${g}K`,lineStart:`${g}1K`,lines(e){let t="";for(let i=0;i<e;i++)t+=this.line+(i<e-1?_e.up():"");if(e)t+=_e.left;return t}},zt={screen:`${H}c`};function Ke(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 r=1;r<=e.length;r++)if(t.charAt(s-1)===e.charAt(r-1))i[s][r]=i[s-1][r-1];else i[s][r]=Math.min(i[s-1][r-1]+1,i[s][r-1]+1,i[s-1][r]+1);return i[t.length][e.length]}function je(e,t,i=2,s=3){return t.map((r)=>({cmd:r,distance:Ke(e,r)})).filter(({distance:r})=>r<=i).sort((r,o)=>r.distance-o.distance).slice(0,s).map(({cmd:r})=>r)}function Ye(e,t={}){let i={_:[]},s=t.alias||{},r=new Set(t.boolean||[]),o={};for(let l of Object.keys(s))for(let n of s[l])o[n]=l;for(let l of r)if(s[l])for(let n of s[l])r.add(n);function d(l,n){let a=o[l]||l;if(i[a]=n,s[a])for(let c of s[a])i[c]=n;if(o[l]&&s[o[l]])for(let c of s[o[l]])i[c]=n;i[l]=n}for(let l=0;l<e.length;l++){let n=e[l];if(n==="--"){i._.push(...e.slice(l+1));break}if(n.startsWith("--")){let a=n.indexOf("=");if(a!==-1){let c=U(n.slice(2,a)),m=n.slice(a+1);d(c,m)}else{let c=n.slice(2);if(c.startsWith("no-")){let w=U(c.slice(3));d(w,!1);continue}let m=U(c),h=o[m]||m;if(r.has(h)||r.has(m))d(m,!0);else{let w=e[l+1];if(w!==void 0&&!w.startsWith("-"))d(m,w),l++;else d(m,!0)}}}else if(n.startsWith("-")&&n.length>1){let a=n.slice(1);for(let c=0;c<a.length;c++){let m=a[c],h=o[m]||m;if(c===a.length-1&&!r.has(h)&&!r.has(m)){let w=e[l+1];if(w!==void 0&&!w.startsWith("-"))d(m,w),l++;else d(m,!0)}else d(m,!0)}}else i._.push(n)}return i}class Re{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,i){if(this.rawName=e,this.description=t,this.config=Object.assign({},i),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=de(e).split(",").map((s)=>{let r=s.trim().replace(/^-{1,2}/,"");if(r.startsWith("no-"))this.negated=!0,r=r.replace(/^no-/,"");return A(r)}).sort((s,r)=>s.length>r.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 Gt=fe.argv,Qe=`${fe.platform}-${fe.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,qe=G.argv,Je=`${G.platform}-${G.arch} node-${G.version}`;class $e{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=de(e);let r=de(e),o=r.indexOf(":");if(o>0)this.namespace=r.substring(0,o),this.name=r.substring(o+1);if(this.args=Pe(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 Re(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 ve}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){let t=A(e.split(".")[0]);return!!this.options.find((i)=>i.names.some((s)=>A(s)===t))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:i,options:s,helpCallback:r}=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 a=ke(t.map((y)=>y.rawName)),c=new Map,m=[];for(let y of t)if(y.namespace){if(!c.has(y.namespace))c.set(y.namespace,[]);c.get(y.namespace).push(y)}else m.push(y);let h="";if(m.sort((y,W)=>y.rawName<W.rawName?-1:y.rawName>W.rawName?1:0),m.length>0)h+=m.map((y)=>` ${ue(y.rawName,a.length)} ${y.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=je(e,t);if(i.length>0)console.log(T.yellow("Did you mean one of these?")),i.forEach((s)=>console.log(` ${T.dim("\u2022")} ${this.name} ${s}`)),console.log("")}console.log(T.dim("Run"),`${this.name} --help`,T.dim("to see all available commands")),x.exit(1)}async parse(e=qe,t={}){let{run:i=!0,exitOnError:s=!1}=t;if(s)try{return await this.parse(e,{run:i})}catch(n){throw this.handleUsageError(n),n}if(this.rawArgs=e,!this.name)this.name=e[1]?Ue(e[1]):"cli";let r=!0,o=e.slice(2),d=o[0];if(d&&!d.startsWith("-")){for(let n of this.commands)if(n.isMatched(d)){let a=this.mri(o,n);r=!1;let c={...a,args:a.args.slice(1)};this.setParsedInfo(c,n,d),this.emit(`command:${d}`,n);break}if(r){let n=o[1];if(n&&!n.startsWith("-")){let a=`${d}:${n}`;for(let c of this.commands)if(c.isMatched(a)){let m=this.mri(o,c);r=!1;let h={...m,args:m.args.slice(2)};this.setParsedInfo(h,c,a),this.emit(`command:${a}`,c);break}}}}if(r){for(let n of this.commands)if(n.name===""){r=!1;let a=this.mri(o,n);this.setParsedInfo(a,n),this.emit("command:!",n);break}}if(r){let n=this.mri(e.slice(2));this.setParsedInfo(n)}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 l={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 l}mri(e,t){let i=[...this.globalCommand.options,...t?t.options:[]],s=We(i),r=[],o=e.indexOf("--");if(o>-1)r=e.slice(o+1),e=e.slice(0,o);let d=Ye(e,s),l={_:d._};for(let h of Object.keys(d))if(h!=="_")l[A(h)]=d[h];let n=l._,a={"--":r},c=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,m=Object.create(null);for(let h of i){if(!c&&h.config.default!==void 0)for(let w of h.names)a[w]=h.config.default;if(Array.isArray(h.config.type)){if(m[h.name]===void 0)m[h.name]={shouldTransform:!0,transformFunction:h.config.type[0]}}}for(let h of Object.keys(l))if(h!=="_"){let w=h.split(".");Fe(a,w,l[h]),ze(a,m)}return{args:n,options:a}}async run(e=qe){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!Ge(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.`;x.stderr.write(`${i}${t}${s}
|
|
32
|
-
`),x.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((l,n)=>{if(l.variadic)s.push(e.slice(n));else s.push(e[n])}),s.push(t);let r={command:i,args:s,options:t};for(let l of i.beforeHooks)await l(r);let o,d=async()=>{let l=i.commandAction.apply(this,s);if(l instanceof Promise)o=await l;else o=l;return o};if(i.middleware.length>0){let l=0,n=async()=>{if(l<i.middleware.length){let a=i.middleware[l++];await a({...r,next:n})}else await d()};await n()}else await d();for(let l of i.afterHooks)await l(r);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return x.removeAllListeners("SIGINT"),x.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 Ve{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 Kt=new Ve;function tt(){if("FORCE_COLOR"in V.env)return V.env.FORCE_COLOR!=="0";if("NO_COLOR"in V.env||V.env.TERM==="dumb")return!1;if(V.platform==="win32")return!0;return Me.isatty(1)&&Me.isatty(2)}var Ae=tt();function f(e,t){if(!Ae)return(i)=>i;return(i)=>e+i+t}var it=f("\x1B[0m","\x1B[0m"),st=f("\x1B[31m","\x1B[39m"),rt=f("\x1B[32m","\x1B[39m"),nt=f("\x1B[33m","\x1B[39m"),at=f("\x1B[34m","\x1B[39m"),ot=f("\x1B[35m","\x1B[39m"),lt=f("\x1B[36m","\x1B[39m"),ct=f("\x1B[37m","\x1B[39m"),ut=f("\x1B[90m","\x1B[39m"),dt=f("\x1B[1m","\x1B[22m"),mt=f("\x1B[3m","\x1B[23m"),ht=f("\x1B[4m","\x1B[24m"),pt=f("\x1B[2m","\x1B[22m"),ft=f("\x1B[7m","\x1B[27m"),gt=f("\x1B[8m","\x1B[28m"),bt=f("\x1B[9m","\x1B[29m"),yt=f("\x1B[41m","\x1B[49m"),$t=f("\x1B[42m","\x1B[49m"),wt=f("\x1B[43m","\x1B[49m"),vt=f("\x1B[44m","\x1B[49m"),xt=f("\x1B[45m","\x1B[49m"),Ct=f("\x1B[46m","\x1B[49m"),St=f("\x1B[47m","\x1B[49m"),Ot=Ae,It={reset:it,red:st,green:rt,yellow:nt,blue:at,magenta:ot,cyan:lt,white:ct,gray:ut,bold:dt,italic:mt,underline:ht,dim:pt,inverse:ft,hidden:gt,strikethrough:bt,bgRed:yt,bgGreen:$t,bgYellow:wt,bgBlue:vt,bgMagenta:xt,bgCyan:Ct,bgWhite:St,isColorSupported:Ot},Et=It,_t=["up","down","left","right","space","enter","cancel"],ei={actions:new Set(_t),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var ti=kt.platform.startsWith("win"),ii=Symbol("clapp:cancel");var qt=He();var p=(e,t)=>qt?e:t,si=p("\u25C6","*"),ri=p("\u25A0","x"),ni=p("\u25B2","x"),ai=p("\u25C7","o"),oi=p("\u250C","T"),Mt=p("\u2502","|"),li=p("\u2514","\u2014"),ci=p("\u25CF",">"),ui=p("\u25CB"," "),di=p("\u25FB","[\u2022]"),mi=p("\u25FC","[+]"),hi=p("\u25FB","[ ]"),pi=p("\u25AA","\u2022"),fi=p("\u2500","-"),gi=p("\u256E","+"),bi=p("\u251C","+"),yi=p("\u256F","+"),$i=p("\u25CF","\u2022"),wi=p("\u25C6","*"),vi=p("\u25B2","!"),xi=p("\u25A0","x");var Ci={light:p("\u2500","-"),heavy:p("\u2501","="),block:p("\u2588","#")};function Bt(){return`${Et.gray(Mt)} `}var Si=Bt();var Ce="0.2.
|
|
32
|
+
`),x.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((l,n)=>{if(l.variadic)s.push(e.slice(n));else s.push(e[n])}),s.push(t);let r={command:i,args:s,options:t};for(let l of i.beforeHooks)await l(r);let o,d=async()=>{let l=i.commandAction.apply(this,s);if(l instanceof Promise)o=await l;else o=l;return o};if(i.middleware.length>0){let l=0,n=async()=>{if(l<i.middleware.length){let a=i.middleware[l++];await a({...r,next:n})}else await d()};await n()}else await d();for(let l of i.afterHooks)await l(r);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return x.removeAllListeners("SIGINT"),x.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 Ve{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 Kt=new Ve;function tt(){if("FORCE_COLOR"in V.env)return V.env.FORCE_COLOR!=="0";if("NO_COLOR"in V.env||V.env.TERM==="dumb")return!1;if(V.platform==="win32")return!0;return Me.isatty(1)&&Me.isatty(2)}var Ae=tt();function f(e,t){if(!Ae)return(i)=>i;return(i)=>e+i+t}var it=f("\x1B[0m","\x1B[0m"),st=f("\x1B[31m","\x1B[39m"),rt=f("\x1B[32m","\x1B[39m"),nt=f("\x1B[33m","\x1B[39m"),at=f("\x1B[34m","\x1B[39m"),ot=f("\x1B[35m","\x1B[39m"),lt=f("\x1B[36m","\x1B[39m"),ct=f("\x1B[37m","\x1B[39m"),ut=f("\x1B[90m","\x1B[39m"),dt=f("\x1B[1m","\x1B[22m"),mt=f("\x1B[3m","\x1B[23m"),ht=f("\x1B[4m","\x1B[24m"),pt=f("\x1B[2m","\x1B[22m"),ft=f("\x1B[7m","\x1B[27m"),gt=f("\x1B[8m","\x1B[28m"),bt=f("\x1B[9m","\x1B[29m"),yt=f("\x1B[41m","\x1B[49m"),$t=f("\x1B[42m","\x1B[49m"),wt=f("\x1B[43m","\x1B[49m"),vt=f("\x1B[44m","\x1B[49m"),xt=f("\x1B[45m","\x1B[49m"),Ct=f("\x1B[46m","\x1B[49m"),St=f("\x1B[47m","\x1B[49m"),Ot=Ae,It={reset:it,red:st,green:rt,yellow:nt,blue:at,magenta:ot,cyan:lt,white:ct,gray:ut,bold:dt,italic:mt,underline:ht,dim:pt,inverse:ft,hidden:gt,strikethrough:bt,bgRed:yt,bgGreen:$t,bgYellow:wt,bgBlue:vt,bgMagenta:xt,bgCyan:Ct,bgWhite:St,isColorSupported:Ot},Et=It,_t=["up","down","left","right","space","enter","cancel"],ei={actions:new Set(_t),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var ti=kt.platform.startsWith("win"),ii=Symbol("clapp:cancel");var qt=He();var p=(e,t)=>qt?e:t,si=p("\u25C6","*"),ri=p("\u25A0","x"),ni=p("\u25B2","x"),ai=p("\u25C7","o"),oi=p("\u250C","T"),Mt=p("\u2502","|"),li=p("\u2514","\u2014"),ci=p("\u25CF",">"),ui=p("\u25CB"," "),di=p("\u25FB","[\u2022]"),mi=p("\u25FC","[+]"),hi=p("\u25FB","[ ]"),pi=p("\u25AA","\u2022"),fi=p("\u2500","-"),gi=p("\u256E","+"),bi=p("\u251C","+"),yi=p("\u256F","+"),$i=p("\u25CF","\u2022"),wi=p("\u25C6","*"),vi=p("\u25B2","!"),xi=p("\u25A0","x");var Ci={light:p("\u2500","-"),heavy:p("\u2501","="),block:p("\u2588","#")};function Bt(){return`${Et.gray(Mt)} `}var Si=Bt();var Ce="0.2.64";var u=new xe("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 oe(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 v({tables:i});console.log(`import { defineModel } from 'bun-query-builder'
|
|
33
33
|
|
|
34
34
|
${s.map((r)=>r.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 Te(e,t,i)});u.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await pe()});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 De(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 we(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 se(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").example("query-builder migrate ./app/Models --dialect postgres").action(async(e,t)=>{try{await b(e,{dialect:t.dialect,state:t.state,apply:t.apply,full:t.full}),await k()}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 ie(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 K(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 F({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 C(e,{dialect:t.dialect,state:t.state}),console.log("-- Generating fresh migrations..."),await b(e,{dialect:t.dialect,state:t.state,full:t.full}),console.log("-- Executing migrations..."),await k()}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 C(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 R({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 R({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 ye(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 be({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 le(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 L(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 I()}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 ge()}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 he({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 me(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 B()}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 re()}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 O({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 P({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 N()}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 Z()}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 _(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 ae(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 z()}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 Y()}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 X({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 J({operations:e.operations,iterations:e.iterations?Number(e.iterations):void 0})}catch(t){console.error("-- Benchmark failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("validate:schema [dir]","Validate models against database schema").example("query-builder validate:schema").example("query-builder validate:schema ./app/Models").action(async(e)=>{try{await q(e)}catch(t){console.error("-- Validation failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("check [dir]","Validate schema (alias for validate:schema)").example("query-builder check").action(async(e)=>{try{await Se(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 ee(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 te(e,t,{format:i.format,truncate:i.truncate})}catch(s){console.error("-- Import failed:",s);let r=await import("process");r.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 ne({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(Ce)});u.version(Ce);u.help();u.parse();
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{jt,qt,Wt,Ut,Vt,vt,Ht,Qt}from"./chunk-
|
|
2
|
+
import{jt,qt,Wt,Ut,Vt,vt,Ht,Qt}from"./chunk-xbpyj4mw.js";import"./chunk-7xvyccgk.js";export{Vt as clearModelRegistry,Ht as defineModel,qt as getAllModels,jt as getModel,Wt as getModelRegistry,Ut as hasModel,Qt as registerBrowserModels,vt as registerModel};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r,e,H,t,s,Q,qe,Ce,w,We,n,p,y,Tt,x,o,Re,A,Ae,Me,M}from"./chunk-
|
|
2
|
+
import{r,e,H,t,s,Q,qe,Ce,w,We,n,p,y,Tt,x,o,Re,A,Ae,Me,M}from"./chunk-xbpyj4mw.js";import{c}from"./chunk-55jccfgb.js";var ni=import.meta.require;import{existsSync as Xn,mkdirSync as qs,mkdtempSync as Ra,readdirSync as Ks,readFileSync as Rr,rmSync as Fs,unlinkSync as Xr,writeFileSync as Us}from"fs";import{tmpdir as xa}from"os";import{isAbsolute as Na,join as Kn}from"path";import Zr from"process";function ri(d){let h=2166136261;for(let D=0;D<d.length;D++)h^=d.charCodeAt(D),h=Math.imul(h,16777619)>>>0;return h.toString(36).padStart(7,"0").slice(-7)}function si(d,h=63){if(d.length<=h)return d;let D=`_${ri(d)}`;return d.slice(0,h-D.length)+D}function Jn(d,h){let D=`${d}_`,E=h.startsWith(D)?h:`${D}${h}`;return si(E)}class a{quoteIdentifier(d){return`\`${d.replace(/`/g,"``")}\``}getColumnType(d){switch(d.type){case"string":return`varchar(${d.maxLength??255})`;case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"datetime";case"timestamptz":return"datetime";case"json":return"json";case"enum":if(d.enumValues&&d.enumValues.length>0)return`ENUM(${d.enumValues.map((D)=>`'${D.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(d){return this.getColumnType(d)}getAutoIncrementClause(d){if(d.isPrimaryKey&&(d.type==="integer"||d.type==="bigint"))return"auto_increment";return""}getDefaultValue(d){if(!d.hasDefault||d.defaultValue===void 0)return"";let h=d.defaultValue;if(typeof h==="string"){let D=h.toUpperCase();if(D==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(D))return`default ${D}`;let V=`'${h.replace(/'/g,"''")}'`;if(d.type==="text"||d.type==="json"||d.type==="enum"&&!d.enumValues?.length)return`default (${V})`;return`default ${V}`}else if(typeof h==="number"||typeof h==="bigint")return`default ${h}`;else if(typeof h==="boolean")return`default ${h?1:0}`;else if(h instanceof Date)return`default '${h.toISOString()}'`;return""}createEnumType(d,h){return""}foreignKeyClauses(d){return d.columns.filter((h)=>h.references).map((h)=>{let D=h.references,E=`${d.table}_${h.name}_fk`,V=`CONSTRAINT ${this.quoteIdentifier(E)} FOREIGN KEY (${this.quoteIdentifier(h.name)}) REFERENCES ${this.quoteIdentifier(D.table)}(${this.quoteIdentifier(D.column)})`;if(D.onDelete)V+=` ON DELETE ${D.onDelete.toUpperCase()}`;if(D.onUpdate)V+=` ON UPDATE ${D.onUpdate.toUpperCase()}`;return V})}createTable(d){let h=[...d.columns.map((D)=>this.renderColumn(D)),...this.foreignKeyClauses(d)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(d.table)} (
|
|
3
3
|
${h.join(`,
|
|
4
4
|
`)}
|
|
5
5
|
) DEFAULT CHARSET=utf8mb4;`}static KEY_PREFIX_CHARACTERS=255;static MAX_KEY_BYTES=3072;static BYTES_PER_CHARACTER=4;keyPartWidth(d){let h=this.getColumnType(d).toLowerCase();if(h.includes("text")||h.includes("blob")||h==="json")return{bytes:Number.POSITIVE_INFINITY,indexableWhole:!1};let D=h.match(/^(?:var)?char\((\d+)\)$/)?.[1];if(D!==void 0)return{bytes:Number(D)*a.BYTES_PER_CHARACTER,indexableWhole:!0};return{bytes:8,indexableWhole:!0}}keyParts(d,h,D){let E=h.columns.map((Ne)=>{let xe=D?.find((Ve)=>Ve.name===Ne),Fe=xe?this.keyPartWidth(xe):{bytes:0,indexableWhole:!0},Ie=!Fe.indexableWhole;return{name:Ne,prefixed:Ie,bytes:Ie?a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER:Fe.bytes,narrowable:!Fe.indexableWhole||Fe.bytes>a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER}}),V=()=>E.reduce((Ne,xe)=>Ne+xe.bytes,0);while(V()>a.MAX_KEY_BYTES){let Ne=E.filter((xe)=>xe.narrowable&&!xe.prefixed).sort((xe,Fe)=>Fe.bytes-xe.bytes)[0];if(!Ne)throw Error(`[migrations] Index '${h.name}' on table '${d}' needs ${V()} bytes of key, over MySQL's ${a.MAX_KEY_BYTES}. Every column in it is already at its ${a.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);Ne.prefixed=!0,Ne.bytes=a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER}return E.map((Ne)=>Ne.prefixed?`${this.quoteIdentifier(Ne.name)}(${a.KEY_PREFIX_CHARACTERS})`:this.quoteIdentifier(Ne.name))}createIndex(d,h,D){if(h.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${h.name}' on table '${d}' uses WHERE clause: ${h.where}`);let E=h.type==="unique"?"UNIQUE ":"",V=Jn(d,h.name),Ne=this.keyParts(d,h,D).join(", ");return`CREATE ${E}INDEX ${this.quoteIdentifier(V)} ON ${this.quoteIdentifier(d)} (${Ne});`}addForeignKey(d,h,D,E,V,Ne,xe=[]){let Fe=`${d}_${h}_fk`,Ie=`ALTER TABLE ${this.quoteIdentifier(d)} ADD CONSTRAINT ${this.quoteIdentifier(Fe)} FOREIGN KEY (${this.quoteIdentifier(h)}) REFERENCES ${this.quoteIdentifier(D)}(${this.quoteIdentifier(E)})`;if(V)Ie+=` ON DELETE ${V.toUpperCase()}`;if(Ne)Ie+=` ON UPDATE ${Ne.toUpperCase()}`;let Ve=[...new Set(xe)].map((gt)=>`ALTER TABLE ${this.quoteIdentifier(d)} DROP FOREIGN KEY ${this.quoteIdentifier(gt)};`).join(`
|
|
@@ -340,7 +340,7 @@ export default class ${V} extends Seeder {
|
|
|
340
340
|
return 100
|
|
341
341
|
}
|
|
342
342
|
}
|
|
343
|
-
`;na(xe,Fe),console.log(`-- \u2713 Created seeder: ${xe}`)}async function be(d={}){let h=Pr(Dr.cwd()),D=d.modelsDir||rr(h,"app/Models"),E=d.seedersDir||rr(h,"database/seeders"),V=d.verbose??!0;try{let{resetDatabase:Ne,generateMigration:xe,executeMigration:Fe}=await import("./chunk-
|
|
343
|
+
`;na(xe,Fe),console.log(`-- \u2713 Created seeder: ${xe}`)}async function be(d={}){let h=Pr(Dr.cwd()),D=d.modelsDir||rr(h,"app/Models"),E=d.seedersDir||rr(h,"database/seeders"),V=d.verbose??!0;try{let{resetDatabase:Ne,generateMigration:xe,executeMigration:Fe}=await import("./chunk-t384ajfz.js");if(V)console.log("-- Refreshing database...");if(await Ne(D),V)console.log("-- Running migrations...");if(await xe(D,{full:!0}),await Fe(),V)console.log("-- Running seeders...");if(await R({seedersDir:E,verbose:V}),V)console.log("-- \u2713 Database refreshed successfully")}catch(Ne){throw console.error("-- \u2717 Database refresh failed:",Ne),Ne}}function Te(d,h,D={}){let E=u({modelsDir:d}),V=$e(E);if(e.debug)e.debug.captureText=!0;let Ne=i({schema:V}),xe=Ne.selectFrom(h).limit(Number(D.limit||10)).toText?.()??"";return console.log(xe||"[query]"),{sql:xe,qb:Ne,schema:V}}async function we(d,h={}){let D=i(),E=h.params?JSON.parse(h.params):void 0,V=await D.unsafe(d,E);return console.log(JSON.stringify(V)),V}import{existsSync as ra}from"fs";import{dirname as ws,join as Ds}from"path";import Es from"process";function sa(d){let h=d;while(h!==ws(h)){if(ra(Ds(h,"package.json")))return h;h=ws(h)}return Es.cwd()}async function q(d){if(!d)d=Ds(sa(Es.cwd()),"app/Models");let h=e.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${d}`),console.log(`-- Dialect: ${h}`),console.log();let D=[];try{let E=await u({modelsDir:d}),V=W(E,{dialect:h}),Ne=i(),xe=[];if(h==="sqlite")xe=(await Ne.unsafe(`
|
|
344
344
|
SELECT name FROM sqlite_master
|
|
345
345
|
WHERE type = 'table'
|
|
346
346
|
AND name NOT LIKE 'sqlite_%'
|
|
@@ -59,8 +59,8 @@ export type ConfigOf = Config
|
|
|
59
59
|
`,c+=`|----------|------|-------------|----------|
|
|
60
60
|
`;for(let l of i)c+=`| \`${l.key}\` | ${l.type} | ${l.description} | \`${l.example}\` |
|
|
61
61
|
`;return c}}function La(i,a,c={}){return ti(i,a,c,new WeakMap)}function ti(i,a,c,l){let{arrayMergeMode:u="replace",skipNullish:f=!1,customMerger:d}=c;if(a===null||a===void 0)return f?i:a;if(d){let h=d(i,a);if(h!==void 0)return h}if(Array.isArray(a)||Array.isArray(i))return ri(i,a,u,l);if(!ue(a)||!ue(i))return a;return Wa(i,a,c,l)}function ri(i,a,c,l){if(Array.isArray(a)&&!Array.isArray(i))return a;if(Array.isArray(i)&&!Array.isArray(a))return a;if(Array.isArray(a)&&Array.isArray(i))switch(c){case"replace":return a;case"concat":return Ba(i,a);case"smart":return Ia(i,a,l);default:return a}return a}function Ba(i,a){let c=[...a];for(let l of i)if(!c.some((u)=>cn(u,l)))c.push(l);return c}function Ia(i,a,c){if(a.length===0)return i;if(i.length===0)return a;if(ue(a[0])&&ue(i[0]))return ja(i,a,c);if(a.every((l)=>typeof l==="string")&&i.every((l)=>typeof l==="string")){let l=[...a];for(let u of i)if(!l.includes(u))l.push(u);return l}return a}function ja(i,a,c){let l=[...a];for(let u of i){if(!ue(u)){l.push(u);continue}let f=["id","name","key","path","type"],d=!1;for(let h of f)if(h in u){if(l.find((m)=>ue(m)&&(h in m)&&m[h]===u[h])){d=!0;break}}if(!d)l.push(u)}return l}function Wa(i,a,c,l){let u=a;if(ue(u)&&l.has(u))return l.get(u);let f={...i};if(ue(u))l.set(u,f);for(let d in u){if(!Object.prototype.hasOwnProperty.call(u,d))continue;let h=u[d],g=f[d];if(c.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){f[d]=h;continue}if(ue(h)&&ue(g))f[d]=ti(g,h,c,l);else if(Array.isArray(h)||Array.isArray(g))f[d]=ri(g,h,c.arrayMergeMode||"smart",l);else f[d]=h}return f}function ni(i,a,c="replace"){return La(i,a,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function cn(i,a){if(i===a)return!0;if(Array.isArray(i)&&Array.isArray(a)){if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(!cn(i[c],a[c]))return!1;return!0}if(ue(i)&&ue(a)){let c=Object.keys(i),l=Object.keys(a);if(c.length!==l.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(a,u))return!1;if(!cn(i[u],a[u]))return!1}return!0}return!1}function ue(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class si{extensions=xs;async loadFromPath(i,a,c={}){let{arrayStrategy:l="replace",useCache:u=!0,cacheTtl:f,trackPerformance:d=!0,verbose:h=!1}=c;if(u){let m=ir.getWithFileCheck("file",i);if(m){if(h)console.log(`Configuration loaded from cache: ${i}`);return m}}let g=async()=>{if(!Xt(i))return null;try{let m=`?t=${Date.now()}`,b=await import(i+m),T=b.default||b,v="default"in b,D=Object.keys(b).length>0;if(!v&&!D)throw new pr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof T!=="object"||T===null||Array.isArray(T))throw new pr(i,Error("Configuration must export a valid object"),"unknown");let E={config:ni(a,T,l),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)ir.setWithFileCheck("file",E,i,f);return E}catch(m){throw m instanceof Error?Fe.configLoad(i,m):Fe.configLoad(i,Error(String(m)))}};if(d)return ln.track("loadFromPath",g,{path:i});return g()}async tryLoadFromPaths(i,a,c={}){for(let l of i)try{let u=await this.loadFromPath(l,a,c);if(u)return u}catch(u){if(u instanceof Error&&u.name==="ConfigLoadError")throw u;if(c.verbose)console.warn(`Failed to load config from ${l}:`,u)}return null}generateConfigPaths(i,a,c){return Pi({name:i,directory:a,alias:c})}generateNamePatterns(i,a){return Es({name:i,alias:a})}checkFileAccess(i){return Fa(async()=>Xt(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,a,c){let l=[];if(!Xt(i))return l;if(a||c){let u=this.generateNamePatterns(a||"",c);for(let f of u)for(let d of this.extensions){let h=Ds(i,`${f}${d}`);if(await this.checkFileAccess(h))l.push(h)}}else try{let{readdirSync:u}=await import("fs"),f=u(i);for(let d of f)if(this.looksLikeConfigFile(d)){let h=Ds(i,d);if(await this.checkFileAccess(h))l.push(h)}}catch{return[]}return l}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((c)=>c.test(i))}async validateConfigFile(i){let a=[];try{if(!Xt(i))return a.push("Configuration file does not exist"),a;let c=await import(i),l=c.default||c;if(l===void 0)a.push("Configuration file must export a default value or named exports");else if(typeof l!=="object"||l===null)a.push("Configuration must be an object");else if(Array.isArray(l))a.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),f=u(i,"utf8");JSON.parse(f)}catch(u){a.push(`Invalid JSON syntax: ${u}`)}}catch(c){a.push(`Failed to load configuration file: ${c}`)}return a}async getFileModificationTime(i){try{let{statSync:a}=await import("fs");return a(i).mtime}catch{return null}}async preloadConfigurations(i,a={}){let c=new Map;return await Promise.allSettled(i.map(async(l)=>{try{let u=await this.loadFromPath(l,{},a);if(u)c.set(l,u.config)}catch(u){if(a.verbose)console.warn(`Failed to preload ${l}:`,u)}})),c}}var Ua=/^https?:\/\//;class ii{async validateConfiguration(i,a,c={}){let{stopOnFirstError:l=!1,validateRequired:u=!0,validateTypes:f=!0,customRules:d=[],trackPerformance:h=!0,verbose:g=!1}=c,m=async()=>{let b=[],T=[],v={stopOnFirstError:l,validateRequired:u,validateTypes:f,customRules:d,trackPerformance:h,verbose:g};try{if(typeof a==="string")return await this.validateWithSchemaFile(i,a,v);else if(Array.isArray(a))return this.validateWithRules(i,[...a,...d],v);else return this.validateWithJSONSchema(i,a,v)}catch(D){return b.push({path:"",message:`Validation failed: ${D}`,rule:"system"}),{isValid:!1,errors:b,warnings:T}}};if(h)return await ln.track("validateConfiguration",m);return m()}async validateWithSchemaFile(i,a,c){try{if(!Va(a))throw new wr(a,[{path:"",message:"Schema file does not exist"}]);let l=await import(a),u=l.default||l;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(l){throw new wr(a,[{path:"",message:`Failed to load schema: ${l}`}])}}validateWithJSONSchema(i,a,c){let l=[],u=[];return this.validateObjectAgainstSchema(i,a,"",l,u,c),{isValid:l.length===0,errors:l,warnings:u}}validateObjectAgainstSchema(i,a,c,l,u,f){if(f.validateTypes&&a.type){let d=Array.isArray(i)?"array":typeof i,h=Array.isArray(a.type)?a.type:[a.type];if(!h.includes(d)){if(l.push({path:c,message:`Expected type ${h.join(" or ")}, got ${d}`,expected:h.join(" or "),actual:d,rule:"type"}),f.stopOnFirstError)return}}if(a.enum&&!a.enum.includes(i)){if(l.push({path:c,message:`Value must be one of: ${a.enum.join(", ")}`,expected:a.enum.join(", "),actual:i,rule:"enum"}),f.stopOnFirstError)return}if(typeof i==="string"){if(a.minLength!==void 0&&i.length<a.minLength)l.push({path:c,message:`String length must be at least ${a.minLength}`,expected:`>= ${a.minLength}`,actual:i.length,rule:"minLength"});if(a.maxLength!==void 0&&i.length>a.maxLength)l.push({path:c,message:`String length must not exceed ${a.maxLength}`,expected:`<= ${a.maxLength}`,actual:i.length,rule:"maxLength"});if(a.pattern){if(!new RegExp(a.pattern).test(i))l.push({path:c,message:`String does not match pattern ${a.pattern}`,expected:a.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(a.minimum!==void 0&&i<a.minimum)l.push({path:c,message:`Value must be at least ${a.minimum}`,expected:`>= ${a.minimum}`,actual:i,rule:"minimum"});if(a.maximum!==void 0&&i>a.maximum)l.push({path:c,message:`Value must not exceed ${a.maximum}`,expected:`<= ${a.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&a.items)for(let d=0;d<i.length;d++){let h=c?`${c}[${d}]`:`[${d}]`;if(this.validateObjectAgainstSchema(i[d],a.items,h,l,u,f),f.stopOnFirstError&&l.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let d=i;if(f.validateRequired&&a.required){for(let h of a.required)if(!(h in d)){if(l.push({path:c?`${c}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(a.properties){for(let[h,g]of Object.entries(a.properties))if(h in d){let m=c?`${c}.${h}`:h;if(this.validateObjectAgainstSchema(d[h],g,m,l,u,f),f.stopOnFirstError&&l.length>0)return}}if(a.additionalProperties===!1){let h=new Set(Object.keys(a.properties||{}));for(let g of Object.keys(d))if(!h.has(g))u.push({path:c?`${c}.${g}`:g,message:`Additional property '${g}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,a,c){let l=[],u=[];for(let f of a)try{let d=this.getValueByPath(i,f.path),h=this.validateWithRule(d,f,f.path);if(l.push(...h),c.stopOnFirstError&&l.length>0)break}catch(d){l.push({path:f.path,message:`Rule validation failed: ${d}`,rule:"system"})}return{isValid:l.length===0,errors:l,warnings:u}}validateWithRule(i,a,c){let l=[];if(a.required&&(i===void 0||i===null))return l.push({path:c,message:a.message||`Property '${c}' is required`,expected:"required",rule:"required"}),l;if(i===void 0||i===null)return l;if(a.type){let u=Array.isArray(i)?"array":typeof i;if(u!==a.type)l.push({path:c,message:a.message||`Expected type ${a.type}, got ${u}`,expected:a.type,actual:u,rule:"type"})}if(a.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<a.min)l.push({path:c,message:a.message||`Value must be at least ${a.min}`,expected:`>= ${a.min}`,actual:u,rule:"min"})}if(a.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>a.max)l.push({path:c,message:a.message||`Value must not exceed ${a.max}`,expected:`<= ${a.max}`,actual:u,rule:"max"})}if(a.pattern&&typeof i==="string"){if(!a.pattern.test(i))l.push({path:c,message:a.message||`Value does not match pattern ${a.pattern}`,expected:a.pattern.toString(),actual:i,rule:"pattern"})}if(a.enum&&!a.enum.includes(i))l.push({path:c,message:a.message||`Value must be one of: ${a.enum.join(", ")}`,expected:a.enum.join(", "),actual:i,rule:"enum"});if(a.validator){let u=a.validator(i);if(u)l.push({path:c,message:a.message||u,rule:"custom"})}return l}getValueByPath(i,a){if(!a)return i;let c=a.split("."),l=i;for(let u of c)if(l&&typeof l==="object"&&u in l)l=l[u];else return;return l}generateRulesFromInterface(i){let a=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let l of c){let[,u,f,d]=l;a.push({path:u,required:!f,type:this.mapTypeScriptType(d)})}return a}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Ua},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var fe=new Dr("bunfig",{showTags:!0});function qa(i){if(!i)return"";let a=Array.isArray(i)?i.filter(Boolean):[i];if(a.length===0)return"";if(a.length===1)return` or alias "${a[0]}"`;return` or aliases ${a.map((c)=>`"${c}"`).join(", ")}`}class oi{fileLoader=new si;envProcessor=new kn;validator=new ii;async loadConfig(i){let a=Date.now(),{cache:c,performance:l,schema:u,validate:f,...d}=i;try{if(c?.enabled){let g=this.checkCache(d.name||"",d);if(g)return g}let h;try{h=await this.loadConfigurationStrategies(d,!0,c)}catch(g){if(d.configFile)throw g;let m=d.__strictErrorHandling;if(g instanceof Error&&g.name==="ConfigNotFoundError"){if(m)throw g;h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`No configuration file found for "${d.name||"config"}", using defaults with environment variables`]}}else if(g instanceof Error&&g.name==="ConfigLoadError"){let b=g.message.includes("EACCES")||g.message.includes("EPERM")||g.message.includes("permission denied"),T=!b&&(g.message.includes("syntax")||g.message.includes("Expected")||g.message.includes("Unexpected")||g.message.includes("BuildMessage")||g.message.includes("errors building")),v=g.message.includes("Configuration must export a valid object")||g.message.includes("Configuration file is empty and exports nothing");if(m&&(v||b))throw g;if(T&&(!m||!v))h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!m)h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`Configuration loading error, using defaults: ${g.message}`]};else throw g}else h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${g instanceof Error?g.message:String(g)}`]}}if(u||f)await this.validateConfiguration(h.config,u,f,d.name);if(c?.enabled&&h)this.cacheResult(d.name||"",h,c,d);if(l?.enabled){let g={operation:"loadConfig",duration:Date.now()-a,configName:d.name,timestamp:new Date};if(l.onMetrics)l.onMetrics(g);if(l.slowThreshold&&g.duration>l.slowThreshold)fe.warn(`Slow configuration loading detected: ${g.duration}ms for ${d.name}`);h.metrics=g}return h}catch(h){if(h instanceof Error&&h.name==="ConfigNotFoundError")throw h;let g=Date.now()-a;throw fe.error(`Configuration loading failed after ${g}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(i,a=!1,c){let{name:l="",alias:u,configFile:f,cwd:d,configDir:h,defaultConfig:g,checkEnv:m=!0,arrayStrategy:b="replace",verbose:T=!1}=i,v=d||br.cwd(),D=[];if(f){let C=me(v,f);D.push(C);let N=m?ut(l,g,T):g,V=await this.fileLoader.tryLoadFromPaths([C],N,{arrayStrategy:b,verbose:T,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(!V)throw Fe.configNotFound(l||f,D,u);if(T)fe.success(`Configuration loaded from explicit path: ${C}`);return this.finalizeResult(V,D,m,l,T)}let R=await this.loadLocalConfiguration(l,u,v,h,g,b,T,m,c);if(R)return D.push(...this.getLocalSearchPaths(l,u,v,h)),this.finalizeResult(R,D,m,l,T);let k=await this.loadHomeConfiguration(l,u,g,b,T,m);if(k)return D.push(...this.getHomeSearchPaths(l,u)),this.finalizeResult(k,D,m,l,T);let E=await this.loadPackageJsonConfiguration(l,u,v,g,b,T,m);if(E)return D.push(me(v,"package.json")),this.finalizeResult(E,D,m,l,T);if(D.push(...this.getAllSearchPaths(l,u,v,h)),a)throw Fe.configNotFound(l,D,u);return{...await this.applyEnvironmentVariables(l,g,m,T),warnings:[`No configuration file found for "${l}"${qa(u)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,a,c,l,u,f,d,h,g){let m=h?ut(i,u,d):u,b=this.getLocalDirectories(c,l);for(let T of b){if(d)fe.info(`Searching for configuration in: ${T}`);let v=this.fileLoader.generateConfigPaths(i,T,a),D=await this.fileLoader.tryLoadFromPaths(v,m,{arrayStrategy:f,verbose:d,cacheTtl:g?.ttl,useCache:!g?.ttl||g.ttl>100});if(D){if(d)fe.success(`Configuration loaded from: ${D.source.path}`);return D}}return null}async loadHomeConfiguration(i,a,c,l,u,f){if(!i)return null;let d=f?ut(i,c,u):c,h=[me(Ve(),".config",i),me(Ve(),".config"),Ve()];for(let g of h){if(u)fe.info(`Checking home directory: ${g}`);let m=this.fileLoader.generateConfigPaths(i,g,a),b=await this.fileLoader.tryLoadFromPaths(m,d,{arrayStrategy:l,verbose:u});if(b){if(u)fe.success(`Configuration loaded from home directory: ${b.source.path}`);return b}}return null}async loadPackageJsonConfiguration(i,a,c,l,u,f,d){let h=d?ut(i,l,f):l;try{let g=me(c,"package.json");if(!Fi(g))return null;let m={};try{m=JSON.parse(Li(g,"utf8"))}catch(v){if(f)fe.warn("Failed to parse package.json:",[v instanceof Error?v:Error(String(v))]);return null}let b=m[i],T=i;if(!b&&a){let v=Array.isArray(a)?a:[a];for(let D of v){if(!D)continue;if(m[D]){b=m[D],T=D;break}}}if(b&&typeof b==="object"&&!Array.isArray(b)){if(f)fe.success(`Configuration loaded from package.json: ${T}`);return{config:ni(h,b,u),source:{type:"package.json",path:g,priority:30,timestamp:new Date}}}}catch(g){if(f)fe.warn("Failed to load package.json:",[g instanceof Error?g:Error(String(g))])}return null}async applyEnvironmentVariables(i,a,c,l){if(!c||!i||typeof a!=="object"||a===null||Array.isArray(a))return{config:a,source:{type:"default",priority:10,timestamp:new Date}};return{config:ut(i,a,l),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,a,c,l,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,a,c,l){let u=[];if(c){let f=c(i);if(f)u.push(...f)}if(a){let f=await this.validator.validateConfiguration(i,a);if(!f.isValid)u.push(...f.errors.map((d)=>d.path?`${d.path}: ${d.message}`:d.message))}if(u.length>0)throw Fe.configValidation(l||"unknown",u,l)}checkCache(i,a){let c=this.generateCacheKey(i,a);return ir.get(c)||null}cacheResult(i,a,c,l){let u=this.generateCacheKey(i,l);ir.set(u,a,void 0,c.ttl)}generateCacheKey(i,a){let c=[i];if(a.alias){let l=Array.isArray(a.alias)?a.alias.join(","):a.alias;c.push(`alias:${l}`)}if(a.cwd)c.push(`cwd:${a.cwd}`);if(a.configFile)c.push(`configFile:${a.configFile}`);if(a.configDir)c.push(`configDir:${a.configDir}`);if("checkEnv"in a)c.push(`checkEnv:${a.checkEnv}`);return c.join("|")}getLocalDirectories(i,a){return Ki({cwd:i,configDir:a})}getAllSearchPaths(i,a,c,l){let u=[];return u.push(...this.getLocalSearchPaths(i,a,c,l)),u.push(...this.getHomeSearchPaths(i,a)),u.push(me(c,"package.json")),u}getLocalSearchPaths(i,a,c,l){let u=this.getLocalDirectories(c,l),f=[];for(let d of u)f.push(...this.fileLoader.generateConfigPaths(i,d,a));return f}getHomeSearchPaths(i,a){if(!i)return[];let c=[me(Ve(),".config",i),me(Ve(),".config"),Ve()],l=[];for(let u of c)l.push(...this.fileLoader.generateConfigPaths(i,u,a));return l}async loadConfigWithResult(i){return this.loadConfig(i)}}var Gr=new oi;async function ai(i){let a="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let l;if(c)l=await Gr.loadConfig(i);else l=await Gr.loadConfig({...i,defaultConfig:a,cache:{enabled:!0},performance:{enabled:!1}});return l?.config??a}catch(l){if(i.configFile)throw l;let u=l instanceof Error?l.name:"UnknownError",f=l instanceof Error?l.message:String(l);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||f.includes("config"))&&i.verbose)fe.warn("Unexpected error loading config, using defaults:",[l instanceof Error?l:Error(String(l))]);let h=c?{...i,defaultConfig:a}:{...i,defaultConfig:a,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await Gr.applyEnvironmentVariables(h.name||"",a,!0,h.verbose||!1))?.config??a;return a}}function ut(i,a,c=!1){let l=new kn,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(d,h=[]){let g={...d};for(let[m,b]of Object.entries(d)){let T=[...h,m],v=[`${u}_${T.join("_").toUpperCase()}`,`${u}_${T.map((k)=>k.toUpperCase()).join("")}`,`${u}_${T.map((k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],D,R;for(let k of v)if(D=br.env[k],D!==void 0){R=k;break}if(D!==void 0&&R)if(typeof b==="boolean")g[m]=["true","1","yes"].includes(D.toLowerCase());else if(typeof b==="number"){let k=Number(D);if(!Number.isNaN(k))g[m]=k}else if(Array.isArray(b))try{g[m]=JSON.parse(D)}catch{g[m]=D.split(",").map((k)=>k.trim())}else g[m]=D;else if(b&&typeof b==="object"&&!Array.isArray(b))g[m]=f(b,T)}return g}return f(a)}var ru=me(br.cwd(),"config"),nu=me(br.cwd(),"src/generated");function r(i=e.dialect){return i==="mysql"||i==="singlestore"||i==="vitess"}var bt={verbose:!0,snapshotDir:".qb",migrationDir:"database/migrations",dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},vitess:{sharded:!0},timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},pagination:{defaultPerPage:25,cursorColumn:"id"},aliasing:{relationColumnAliasFormat:"table_column"},relations:{foreignKeyFormat:"singularParent_id",maxDepth:10,maxEagerLoad:50,detectCycles:!0},transactionDefaults:{retries:2,isolation:"read committed",sqlStates:["40001","40P01"],backoff:{baseMs:50,factor:2,maxMs:2000,jitter:!0}},sql:{randomFunction:"RANDOM()",sharedLockSyntax:"FOR SHARE",jsonContainsMode:"operator"},features:{distinctOn:!0},debug:{captureText:!0},hooks:{},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0}},fi=new Set(["__proto__","constructor","prototype"]);function li(i){if(i===null||typeof i!=="object"||Array.isArray(i))return!1;let a=Object.getPrototypeOf(i);return a===Object.prototype||a===null}function xn(i,a,c=new Set){let l={...i};c.add(a);for(let u of Object.keys(a)){if(fi.has(u))continue;let f=a[u];if(li(f)&&!c.has(f)){let d=l[u];l[u]=xn(li(d)?d:{},f,c)}else l[u]=f}return c.delete(a),l}var za=Symbol.for("bun-query-builder.config"),e=globalThis[za]??=xn({},bt),Ha=Symbol.for("bun-query-builder.config-state"),$r=globalThis[Ha]??={explicit:new Set,fileLoaded:!1};function H(i){if(i)return i;let a=ci.env.DB_DIALECT||ci.env.DB_CONNECTION;if(a)return a;return e.dialect||"postgres"}function t(i){if(e.dialect==="postgres")return`$${i}`;return"?"}function s(i,a=1){if(i<=0)return"";if(e.dialect==="postgres"){let c=`$${a}`;for(let l=1;l<i;l++)c+=`, $${a+l}`;return c}return i===1?"?":`?${", ?".repeat(i-1)}`}async function Q(){if(!$r.fileLoaded){$r.fileLoaded=!0;let i=await ai({name:"query-builder",alias:"qb",defaultConfig:bt}),a={};for(let[c,l]of Object.entries(i??{}))if(!$r.explicit.has(c))a[c]=l;di(a)}return e}var pt=null,ui=new Set;function di(i){let a=xn(e,i),c=e;for(let l of Object.keys(a)){if(fi.has(l))continue;c[l]=a[l]}}function qe(i){if(i.dialect&&pt&&i.dialect!==pt){let a=`${pt}->${i.dialect}`;if(!ui.has(a))ui.add(a),console.warn(`[query-builder] Configuring dialect '${i.dialect}' overrides the previously configured dialect '${pt}'. Config is process-wide (setConfig, db.configure and query-builder.config.ts all write it); in-flight queries from the previous configuration may break. `+"Run conflicting connections in separate processes \u2014 see stacksjs/stacks#1862 #18.")}if(i.dialect)pt=i.dialect;for(let a of Object.keys(i))$r.explicit.add(a);di(i)}function yn(i){return i}var{SQL:hi}=globalThis.Bun;import{Database as Ga}from"bun:sqlite";import{mkdirSync as Ya}from"fs";import{dirname as Ja}from"path";import Ct from"process";var It=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"];function Lt(){let i=e.sqlite?.pragmas;return Array.isArray(i)?i:It}function G(i){for(let a of Lt())try{i.run(a)}catch{}}function kt(i){return i}function Qa(i){return i!==null&&typeof i==="object"?i:null}function gi(i,a){if(a.length===0||!/\$\d/.test(i))return{sql:i,params:a};let c=[],l="",u=0;for(let f=0;f<i.length;f++){let d=i[f];if(d==="'"||d==='"'||d==="`"){let h=Za(i,f,d);l+=i.slice(f,h),f=h-1;continue}if(d==="-"&&i[f+1]==="-"){let h=i.indexOf(`
|
|
62
|
-
`,f),g=h===-1?i.length:h;l+=i.slice(f,g),f=g-1;continue}if(d==="/"&&i[f+1]==="*"){let h=i.indexOf("*/",f+2),g=h===-1?i.length:h+2;l+=i.slice(f,g),f=g-1;continue}if(d==="$"){let h=/^\d+/.exec(i.slice(f+1))?.[0];if(h){let g=Number(h);if(u=Math.max(u,g),g>=1&&g<=a.length){c.push(a[g-1]),l+="?",f+=h.length;continue}}}l+=d}if(u>a.length)throw Error(`SQL references $${u} but only ${a.length} value${a.length===1?" was":"s were"} provided`);if(c.length===0)return{sql:i,params:a};return{sql:l,params:c}}function Za(i,a,c){for(let l=a+1;l<i.length;l++){if(i[l]!==c)continue;if(i[l+1]===c){l++;continue}return l+1}return i.length}class wi{db;constructor(i){if(i!==":memory:"&&!i.startsWith(":")){let a=Ja(i);if(a&&a!==".")Ya(a,{recursive:!0})}this.db=new Ga(i),G(this.db)}query(i,a=[]){let c=gi(i,a);return
|
|
62
|
+
`,f),g=h===-1?i.length:h;l+=i.slice(f,g),f=g-1;continue}if(d==="/"&&i[f+1]==="*"){let h=i.indexOf("*/",f+2),g=h===-1?i.length:h+2;l+=i.slice(f,g),f=g-1;continue}if(d==="$"){let h=/^\d+/.exec(i.slice(f+1))?.[0];if(h){let g=Number(h);if(u=Math.max(u,g),g>=1&&g<=a.length){c.push(a[g-1]),l+="?",f+=h.length;continue}}}l+=d}if(u>a.length)throw Error(`SQL references $${u} but only ${a.length} value${a.length===1?" was":"s were"} provided`);if(c.length===0)return{sql:i,params:a};return{sql:l,params:c}}function Za(i,a,c){for(let l=a+1;l<i.length;l++){if(i[l]!==c)continue;if(i[l+1]===c){l++;continue}return l+1}return i.length}class wi{db;constructor(i){if(i!==":memory:"&&!i.startsWith(":")){let a=Ja(i);if(a&&a!==".")Ya(a,{recursive:!0})}this.db=new Ga(i),G(this.db)}query(i,a=[]){let c=gi(i,a);return(c.params.length>0?this.db.query(c.sql):this.db.prepare(c.sql)).all(...c.params)}run(i,a=[]){let c=gi(i,a);return(c.params.length>0?this.db.query(c.sql):this.db.prepare(c.sql)).run(...c.params)}close(){this.db.close()}get database(){return this.db}}function mi(i){return{__raw:!0,value:i,toString:()=>i}}function yi(i){let a=i.trimStart();for(;;)if(a.startsWith("--")){let c=a.indexOf(`
|
|
63
63
|
`);a=c===-1?"":a.slice(c+1).trimStart()}else if(a.startsWith("/*")){let c=a.indexOf("*/");a=c===-1?"":a.slice(c+2).trimStart()}else return a}function Xa(i){let a=[],c="",l=!1,u=!1,f=!1,d=!1;for(let g=0;g<i.length;g++){let m=i[g],b=i[g+1];if(!l&&!u&&!d&&m==="-"&&b==="-"){f=!0,c+=m;continue}if(f&&(m===`
|
|
64
64
|
`||m==="\r")){f=!1,c+=m;continue}if(!l&&!u&&!f&&m==="/"&&b==="*"){d=!0,c+=m;continue}if(d&&m==="*"&&b==="/"){d=!1,c+=m+b,g++;continue}if(f||d){c+=m;continue}if(m==="'"&&!u){if(l&&b==="'"){c+=m+b,g++;continue}l=!l,c+=m;continue}if(m==='"'&&!l){u=!u,c+=m;continue}if(m===";"&&!l&&!u){let T=yi(c.trim());if(T)a.push(T);c="";continue}c+=m}let h=yi(c.trim());if(h)a.push(h);return a}function pi(i){let a=new wi(i);function c(f,...d){let h=f[0],g=[];for(let m=0;m<d.length;m++){let b=d[m],T=Qa(b);if(T&&typeof T.sql==="string"&&Array.isArray(T.values))h+=T.sql+(f[m+1]||""),g.push(...T.values);else if(T&&(T.__raw||T.raw)){let v=T.raw,D=T.__raw?T.value:typeof v==="string"?v:v();h+=D+(f[m+1]||"")}else if(Array.isArray(b)){let v=b.map(()=>"?").join(", ");h+=v+(f[m+1]||""),g.push(...b)}else h+=`?${f[m+1]||""}`,g.push(b)}return{sql:h,values:g,execute:()=>{try{let m=h.trim().toUpperCase();if(m.startsWith("SELECT")||m.startsWith("PRAGMA")||/\bRETURNING\b/.test(m)){let b=a.query(h,kt(g));return Promise.resolve(b)}else{let b=a.run(h,kt(g));return Promise.resolve(b)}}catch(m){return Promise.reject(m)}},raw:()=>h,toString:()=>h,cancel:()=>{}}}function l(f,...d){if(Array.isArray(f)&&"raw"in f)return c(f,...d);if(typeof f==="string")return mi(f);return c([""])}l.raw=(f)=>mi(f),l.unsafe=(f,d=[])=>{let h=()=>{try{let g=f.trim().toUpperCase();if(g.startsWith("SELECT")||g.startsWith("PRAGMA")||/\bRETURNING\b/.test(g)){let m=a.query(f,kt(d));return Promise.resolve(m)}else{let m=a.run(f,kt(d));return Promise.resolve(m)}}catch(g){return Promise.reject(g)}};return{sql:f,values:d,execute:h,then:(g,m)=>h().then(g,m),raw:()=>f,toString:()=>f,cancel:()=>{}}},l.close=()=>(a.close(),Promise.resolve()),l.query=(f,d)=>{try{let h=a.query(f,kt(d||[]));return Promise.resolve(h)}catch(h){return Promise.reject(h)}},l.file=async(f,d)=>{try{let{readFileSync:h}=await import("fs"),g=h(f,"utf-8"),m=Xa(g);for(let b of m){let T=b.trim();if(!T||T.startsWith("--"))continue;let v=T.toUpperCase();if(v.startsWith("SELECT")||v.startsWith("PRAGMA"))a.query(b);else a.run(b)}return Promise.resolve([])}catch(h){return Promise.reject(h)}};let u=0;return l.begin=async(f,d)=>{let h=typeof f==="function"?f:d;if(typeof h!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let g=u>0,m=`qb_sp_${u}`;if(g)a.run(`SAVEPOINT ${m}`);else a.run("BEGIN");u++;try{let b=await h(l);if(u--,g)a.run(`RELEASE SAVEPOINT ${m}`);else a.run("COMMIT");return b}catch(b){u--;try{if(g)a.run(`ROLLBACK TO SAVEPOINT ${m}`),a.run(`RELEASE SAVEPOINT ${m}`);else a.run("ROLLBACK")}catch{}throw b}},l.savepoint=l.begin,l.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},l._wrapper=a,l}function ec(i){let a=i.replace(/^(?:sqlite|sqlite3|file):/i,"");if(a===i)return i;return(a.startsWith("///")?a.slice(2):a.startsWith("//")?a.slice(2):a)||":memory:"}function Ce(i=e.database){let a=Ct.env.DB_DATABASE||i?.database||"";return String(a).replace(/^['"]|['"]$/g,"")}function tc(i,a){if((i==="postgres"||i==="mysql"||i==="singlestore"||i==="vitess")&&Ct.env.DB_CONNECTION===i){let m=Ct.env,b=(m.DB_DATABASE||a.database||"").replace(/^['"]|['"]$/g,""),T=m.DB_USERNAME||a.username,v=m.DB_PASSWORD??a.password??"",D=m.DB_HOST||a.host||"localhost",R=m.DB_PORT||a.port,k=i==="postgres"?"postgres":"mysql",E=m.DB_SSL==="true"||m.DB_SSL==="1"||a.ssl?"?ssl=true":"";return`${k}://${T}:${v}@${D}${R?`:${R}`:""}/${b}${E}`}if(a.url)return i==="sqlite"?ec(a.url):a.url;let{database:c,username:l,password:u,host:f="localhost",port:d,ssl:h}=a,g=h||Ct.env.DB_SSL==="true"||Ct.env.DB_SSL==="1"?"?ssl=true":"";switch(i){case"postgres":return`postgres://${l}:${u}@${f}${d?`:${d}`:""}/${c}${g}`;case"mysql":case"singlestore":case"vitess":return`mysql://${l}:${u}@${f}${d?`:${d}`:""}/${c}${g}`;case"sqlite":if(c===":memory:")return":memory:";return c||":memory:";default:throw Error(`Unsupported dialect: ${i}`)}}function bi(i){if(!i)return{};let a={},c=(l)=>Math.max(0,Math.round(l/1000));if(typeof i.max==="number"&&Number.isFinite(i.max))a.max=i.max;if(typeof i.idleTimeoutMs==="number"&&Number.isFinite(i.idleTimeoutMs))a.idleTimeout=c(i.idleTimeoutMs);if(typeof i.acquireTimeoutMs==="number"&&Number.isFinite(i.acquireTimeoutMs))a.connectionTimeout=c(i.acquireTimeoutMs);if(typeof i.maxLifetimeMs==="number"&&Number.isFinite(i.maxLifetimeMs))a.maxLifetime=c(i.maxLifetimeMs);return a}function rc(){let i=e.dialect,a=tc(i,e.database);try{if(i==="sqlite")return pi(a);let c=bi(e.database.pool);return Object.keys(c).length>0?new hi(a,c):new hi(a)}catch(c){if(console.error(`[query-builder] Failed to create database connection for dialect '${i}': ${c.message}`),i==="sqlite")return pi(":memory:");throw c}}var nt=null,Cn=null;function nc(){let i=e.database;return JSON.stringify({dialect:e.dialect,database:i.database,username:i.username,password:i.password,host:i.host,port:i.port,url:i.url,pool:bi(i.pool)})}function w(i=!1){let a=nc();if(i||nt!==null&&Cn!==a||!nt)Ti(),nt=rc(),Cn=a;return nt}function Ti(){let i=nt;return nt=null,Cn=null,i}async function sc(i){if(!i||typeof i.close!=="function")return;await i.close()}function bn(){sc(Ti()).catch((a)=>{console.error(`[query-builder] Failed to close database connection: ${a.message}`)})}async function We(i){try{return await i(w())}catch(a){if(a?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||a?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let c=w(!0);return await i(c)}throw a}}function ic(){return new Proxy(function(){},{get(i,a){let c=w(),l=c[a];if(typeof l==="function")return l.bind(c);return l},apply(i,a,c){return w()(...c)}})}var n=ic();function st(i){if(typeof i==="number")return{length:i};return i}function Mn(i){if(typeof i==="number")return{max:i};return i}function oc(i){return typeof i==="function"}function ac(i){return i.replace(/[A-Z]/g,(a)=>a.toLowerCase())}function vi(i,a){if(!a||typeof a.fractionDigits!=="number")return i;return Number(i.toFixed(a.fractionDigits))}function Oe(i,a={}){if(!i)return a;return new Proxy(i,{get(c,l){if(l in a)return a[l];let u=c[l];if(u!==void 0)return u;let f=c[ac(l)];if(oc(f))return f.bind(c);return}})}function wt(i){let a=(b)=>{let T=Array.isArray(b)?b:[],v=Math.floor(Math.random()*T.length);return T[v]},c=()=>i.string,l=()=>i.number,u=()=>i.random,f=Oe(i.string,{alpha:(b)=>c()?.alpha?.(st(b)),alphanumeric:(b)=>c()?.alphanumeric?.(st(b)),numeric:(b)=>c()?.numeric?.(st(b)),sample:(b)=>c()?.sample?.(st(b)),hexadecimal:(b)=>c()?.hexadecimal?.(st(b))}),d=Oe(i.number,{int:(b)=>l()?.int?.(Mn(b)),float:(b)=>{let T=Mn(b);return vi(Number(l()?.float?.(T)??0),T)}}),h=Oe(i.helpers,{arrayElement:a,arrayElements:(b,T)=>{let v=[...Array.isArray(b)?b:[]],D=typeof T==="number"?T:Math.max(1,Math.floor(Math.random()*v.length));for(let R=v.length-1;R>0;R-=1){let k=Math.floor(Math.random()*(R+1));[v[R],v[k]]=[v[k],v[R]]}return v.slice(0,Math.min(D,v.length))},shuffle:(b)=>{let T=[...Array.isArray(b)?b:[]];for(let v=T.length-1;v>0;v-=1){let D=Math.floor(Math.random()*(v+1));[T[v],T[D]]=[T[D],T[v]]}return T},maybe:(b,T)=>{let v=typeof T?.probability==="number"?T.probability:0.5;return Math.random()<v?b():void 0},slugify:(b)=>String(b??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),m={string:f,number:d,helpers:h,datatype:{boolean:(b)=>{let T=typeof b==="number"?b:b?.probability;if(typeof T==="number")return Math.random()<T;return Boolean(u()?.boolean?.())},number:(b)=>Number(l()?.int?.(Mn(b))??0),float:(b)=>vi(Number(l()?.float?.(b)??0),b),uuid:()=>crypto.randomUUID(),string:(b)=>String(c()?.alphanumeric?.({length:b??10})??""),hexadecimal:(b)=>String(c()?.hexadecimal?.(st(b))??""),array:(b)=>Array.from({length:b??3},()=>c()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:c()?.alphanumeric?.({length:8})})},location:Oe(i.address),address:Oe(i.address),vehicle:Oe(i.vehicle,{vrm:()=>i.vehicle?.registration?.()}),company:Oe(i.company,{catchPhrase:()=>i.company?.catchphrase?.(),buzzPhrase:()=>i.company?.bs?.()??i.company?.buzzword?.()})};return new Proxy(i,{get(b,T){if(T in m)return m[T];let v=b[T];if(v&&typeof v==="object")return Oe(v);return v}})}function Me(i){if(typeof i==="string")return{model:i};if(i&&typeof i==="object"&&typeof i.model==="string"){let a=i;return{model:a.model,foreignKey:a.foreignKey,onDelete:a.onDelete}}return null}function M(i){if(!i)return[];return(Array.isArray(i)?i:typeof i==="object"?Object.values(i):[]).map(Me).filter((c)=>c!==null)}function Ue(i){let a=String(i).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(a.endsWith("y")&&!/[aeou]y$/.test(a))return`${a.slice(0,-1)}ies`;if(a.endsWith("s")||a.endsWith("x")||a.endsWith("ch")||a.endsWith("sh"))return`${a}es`;return`${a}s`}function p(i){return typeof i?.table==="string"&&i.table.length>0?i.table:Ue(String(i?.name??""))}function Kt(i){return i.endsWith("s")?i.slice(0,-1):i}function Ft(i){if(i.endsWith("ies")&&i.length>3){let a=i.slice(0,-3),c=a[a.length-1];if(c&&!"aeiou".includes(c))return`${a}y`}if(i.endsWith("es")&&i.length>2){let a=i.slice(0,-2);if(a.endsWith("s")||a.endsWith("x")||a.endsWith("ch")||a.endsWith("sh"))return a}if(i.endsWith("s")&&!i.endsWith("ss")&&!i.endsWith("us")&&!i.endsWith("is"))return i.slice(0,-1);return i}function y(i){if(i==="none")return(a)=>a;if(i==="inflect")return Ft;return Kt}var Tt="1 = 0";function x(i){if(i.length===0)return"";let a=[];for(let c of i)if(c.conn==="OR"&&a.length>0)a[a.length-1].push(c);else a.push([c]);return a.map((c,l)=>{let u=c.map((d)=>d.sql).join(" OR "),f=c.length>1&&a.length>1?`(${u})`:u;return l===0?f:`${c[0].conn} ${f}`}).join(" ")}function o(i,a,c,l){if(a.length===0)return c?"1 = 1":"1 = 0";return`${i} ${c?"NOT IN":"IN"} (${l})`}function Tn(i,a){if(a!=="postgres")return i;let c="",l=0,u=0;while(u<i.length){let f=i[u];if(f==="'"){let d=Di(i,u,"'");c+=i.slice(u,d),u=d;continue}if(f==='"'){let d=Di(i,u,'"');c+=i.slice(u,d),u=d;continue}if(f==="$"){let d=i.slice(u).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(d){let h=i.indexOf(d,u+d.length),g=h===-1?i.length:h+d.length;c+=i.slice(u,g),u=g;continue}}if(f==="?"){l++,c+=`$${l}`,u++;continue}c+=f,u++}return c}function Di(i,a,c){let l=a+1;while(l<i.length){if(i[l]===c){if(i[l+1]===c){l+=2;continue}return l+1}l++}return i.length}function Re(i,a,c=Number.POSITIVE_INFINITY){let l=[],u=0,f=(d)=>d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||d===95;for(let d=0;d<i.length;d++){let h=i.charCodeAt(d);if(h===45&&i.charCodeAt(d+1)===45){let m=i.indexOf(`
|
|
65
|
-
`,d+2);if(m===-1)return l;d=m;continue}if(h===47&&i.charCodeAt(d+1)===42){let m=1,b=d+2;while(b<i.length&&m>0)if(i[b]==="/"&&i[b+1]==="*")m++,b+=2;else if(i[b]==="*"&&i[b+1]==="/")m--,b+=2;else b++;d=b-1;continue}if(h===39||h===34||h===96){let m=d+1;while(m<i.length){if(i.charCodeAt(m)===h){if(i.charCodeAt(m+1)===h){m+=2;continue}break}m++}d=m;continue}if(h===36){let m=/^\$(?:[A-Z_][A-Z0-9_]*)?\$/i.exec(i.slice(d));if(m){let b=i.indexOf(m[0],d+m[0].length);d=b===-1?i.length:b+m[0].length-1;continue}}if(h===40){u++;continue}if(h===41){u=Math.max(0,u-1);continue}if(u!==0)continue;if(d===0)continue;let g=h&-33;if(g<65||g>90)continue;if(f(i.charCodeAt(d-1)))continue;for(let{key:m,pattern:b}of a){b.lastIndex=d;let T=b.exec(i);if(!T)continue;if(l.push({key:m,start:d,length:T[0].length}),l.length>=c)return l;d+=T[0].length-1;break}}return l}function Ie(){let i=new Date().toISOString();return r(e.dialect)?i.slice(0,19).replace("T"," "):i}var Si=/^[A-Z_][A-Z0-9_]*$/i;function ke(i,a){if(typeof i!=="string"||i.length===0)throw TypeError(`[bun-query-builder] ${a}: identifier must be a non-empty string, got ${typeof i}`);if(i.length>64)throw TypeError(`[bun-query-builder] ${a}: identifier '${i}' exceeds 64 chars`);if(!Si.test(i))throw TypeError(`[bun-query-builder] ${a}: identifier '${i}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Mi(i,a){if(typeof i!=="string"||i.length===0)throw TypeError(`[bun-query-builder] ${a}: identifier must be a non-empty string, got ${typeof i}`);let c=i.split(".");if(c.length>2||c.some((l)=>l.length===0||l.length>64||!Si.test(l)))throw TypeError(`[bun-query-builder] ${a}: invalid ORDER BY column '${i}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}var kr=null,On=new Map;function cc(i,a){On.set(i,a),ot.clear()}function St(){On.clear(),ot.clear()}function ce(i){if(!kr)try{kr=import.meta.require("./chunk-wyr48f41.js").getModel}catch{kr=()=>{return}}return kr(i)??On.get(i)}var xr=new Map,lc=500;function $i(i){let a=xr.get(i);if(a!==void 0)return a;let c=0,l=i.replace(/\?/g,()=>`$${++c}`);if(xr.size>=lc)xr.clear();return xr.set(i,l),l}function Dt(i){if(i==null)return 0;if(typeof i.affectedRows==="number")return i.affectedRows;if(typeof i.count==="number")return i.count;if(Array.isArray(i))return i.length;return 0}function $t(i){if(i==null||typeof i!=="object")return null;if("insertId"in i&&i.insertId!=null)return i.insertId;if("lastInsertRowid"in i&&i.lastInsertRowid!=null)return i.lastInsertRowid;return null}class _n{sqliteDb;dialect="sqlite";constructor(i){this.sqliteDb=i}all(i,a){return Promise.resolve(this.sqliteDb.query(i).all(...a))}get(i,a){return Promise.resolve(this.sqliteDb.query(i).get(...a)??void 0)}run(i,a){let c=this.sqliteDb.run(i,a);return Promise.resolve({changes:c.changes,lastInsertId:c.lastInsertRowid})}insert(i,a){return this.run(i,a)}}class Ai{dialect;constructor(i){this.dialect=i}conn(){return w()}text(i){return this.dialect==="postgres"?$i(i):i}async all(i,a){let c=await this.conn().unsafe(this.text(i),a);return Array.isArray(c)?c:[]}async get(i,a){let c=await this.conn().unsafe(this.text(i),a);if(Array.isArray(c))return c[0]??void 0;return c??void 0}async run(i,a){let c=await this.conn().unsafe(this.text(i),a);return{changes:Dt(c),lastInsertId:$t(c)}}async insert(i,a,c){if(this.dialect==="postgres"){let f=await this.conn().unsafe(`${$i(i)} RETURNING ${c}`,a),d=Array.isArray(f)?f[0]:f;return{changes:1,lastInsertId:d?d[c]??null:null}}let l=await this.conn().unsafe(i,a),u=$t(l);if(u==null){let f=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);u=(Array.isArray(f)?f[0]:f)?.id??null}return{changes:Dt(l)||1,lastInsertId:u}}}var xe=null,Mr=!1,ye=null,it=null,Er=null,Cr=null;function wn(i){if(i.database instanceof Nn)xe=i.database,Mr=!1;else xe=new Nn(i.database||":memory:",{create:!0}),Mr=!0,G(xe);ye=null,it=null}function Sn(){let i=Mr,a=xe;if(xe=null,Mr=!1,ye=null,it=null,Er=null,Cr=null,i&&a)try{a.close()}catch{}}function B(){if(xe){if(!ye||it!==xe)ye=new _n(xe),it=xe,Er="sqlite",Cr=null;return ye}let i=e.dialect,a=e.database?.database??null;if(ye&&it===null&&Er===i&&Cr===a)return ye;if(it=null,Er=i,Cr=a,i==="sqlite"){let c=new Nn(a||":memory:",{create:!0});G(c),ye=new _n(c)}else ye=new Ai(i);return ye}function Dn(){let i=B();if(i.sqliteDb)return i.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${i.dialect}'. Use the async model API instead.`)}var Pe="deleted_at",An="__btm_rel__";function at(i){let a=i.traits;return Boolean(a?.useSoftDeletes||a?.softDeletable)}function je(i){let a=i.traits;return Boolean(a?.useTimestamps||a?.timestampable)}var ki=new WeakMap;function uc(i){let a=ki.get(i);if(a)return a;let c=new Set,l=i.belongsToMany;if(l){if(Array.isArray(l)){for(let u of l)if(typeof u==="string")c.add(u.toLowerCase());else if(u&&typeof u==="object"&&u.model)c.add(u.model.toLowerCase())}else if(typeof l==="object")for(let u of Object.keys(l))c.add(u)}return ki.set(i,c),c}function Ri(i){let a={};for(let[c,l]of Object.entries(i))a[I(c)]=l;return a}function fc(i){for(let a in i)if(I(a)!==a)return Ri(i);return i}function dc(i,a){if(i[a])return i[a];let c=I(a);if(i[c])return i[c];for(let l of Object.keys(i))if(I(l)===c)return i[l];return}class oe{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_relations={};constructor(i,a={}){this._definition=i,this._attributes=fc({...a}),this._original=null;let c=uc(i);if(c.size===0)return;let l=this;return new Proxy(this,{get(u,f,d){if(typeof f==="string"&&c.has(f)&&!(f in u))return()=>{let h=Ni(i,f);if(!h||h.type!=="belongsToMany")throw Error(`[orm] relation '${f}' did not resolve to a belongsToMany on '${i.name}'`);let g=ce(h.relatedModelName),m=g?.getDefinition?.()||g?.definition;if(!m)throw Error(`[orm] related model '${h.relatedModelName}' is not registered`);return new Et(l,i,h,m)};return Reflect.get(u,f,d)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(i){let a=this._definition.get?.[i];if(a)try{let c=a(this._attributes);if(c!==void 0)return c}catch{}return this._attributes[I(i)]}getAttribute(i){return this._attributes[I(i)]}getAttributes(){return{...this._attributes}}set(i,a){if(this._original===null)this._original={...this._attributes};this._attributes[I(i)]=a}only(i){let a={};for(let c of i)a[c]=this._attributes[I(c)];return a}except(i){let a=new Set(i.map((l)=>I(l))),c={};for(let l of Object.keys(this._attributes))if(!a.has(l))c[l]=this._attributes[l];return c}getRelation(i){return this._relations[i]}setRelation(i,a){this._relations[i]=a}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let i=this._definition.primaryKey||"id";return this._attributes[i]}isDirty(i){if(this._original===null)return!1;if(i){let a=I(i);return this._attributes[a]!==this._original[a]}return Object.keys(this._attributes).some((a)=>this._attributes[a]!==this._original[a])}isClean(i){return!this.isDirty(i)}getOriginal(i){return this.getOriginalAttributes()[I(i)]}getChanges(){if(this._original===null)return{};let i={};for(let a of Object.keys(this._attributes))if(this._attributes[a]!==this._original[a])i[a]=this._attributes[a];return i}fill(i){let a=this._definition.attributes;for(let[c,l]of Object.entries(i)){let u=dc(a,c),f=!u&&I(c).endsWith("_id");if(u?.fillable&&!u?.guarded||f){if(this._original===null)this._original={...this._attributes};this._attributes[I(c)]=l}}return this}forceFill(i){if(this._original===null)this._original={...this._attributes};let a=Ri(i);Object.assign(this._attributes,a);for(let c of Object.keys(a))this._forced.add(c);return this}async save(){let i=B(),a=this._definition.primaryKey||"id",c=this._definition.hooks,l=this._definition.set||{};for(let[u,f]of Object.entries(l))if(this.isDirty(u))this._attributes[I(u)]=f(this._attributes);if(this._attributes[a]){await c?.beforeUpdate?.(this,this.getChanges());let u=this.getChanges(),f=Object.keys(u);if(f.length>0){let d=f.map((g)=>`${g} = ?`).join(", "),h=[...Object.values(u),this._attributes[a]];if(je(this._definition)){let g=Ie();await i.run(`UPDATE ${this._definition.table} SET ${d}, updated_at = ? WHERE ${a} = ?`,[...Object.values(u),g,this._attributes[a]])}else await i.run(`UPDATE ${this._definition.table} SET ${d} WHERE ${a} = ?`,h)}await c?.afterUpdate?.(this)}else{let u=this._definition.attributes,f={};for(let[m,b]of Object.entries(u)){if(b.guarded&&!this._forced.has(I(m)))continue;let T=I(m);if(this._attributes[T]!==void 0)f[T]=this._attributes[T]}for(let m of Object.keys(this._attributes))if(m.endsWith("_id")&&m!==a&&!(m in f))f[m]=this._attributes[m];if(je(this._definition)){let m=Ie(),b=this._attributes.created_at;f.created_at=b===void 0||b===null?m:b,f.updated_at=m}if(this._definition.traits?.useUuid&&!f.uuid)f.uuid=crypto.randomUUID();await c?.beforeCreate?.(f);let d=Object.keys(f),h=d.map(()=>"?").join(", "),g=await i.insert(`INSERT INTO ${this._definition.table} (${d.join(", ")}) VALUES (${h})`,Object.values(f),a);for(let[m,b]of Object.entries(f))this._attributes[m]=b;if(g.lastInsertId!=null)this._attributes[a]=g.lastInsertId;await c?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update(i){return this.fill(i),this.save()}async fresh(){let i=B(),a=this._definition.primaryKey||"id",c=this._attributes[a];if(c==null)return null;let l=await i.get(`SELECT * FROM ${this._definition.table} WHERE ${a} = ?`,[c]);if(!l)return null;return new oe(this._definition,l)}async delete(){let i=B(),a=this._definition.primaryKey||"id",c=this._attributes[a],l=this._definition.hooks;if(!c)throw Error("Cannot delete a model without a primary key");if(await l?.beforeDelete?.(this),at(this._definition)){let u=Ie();await i.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${a} = ?`,[u,c]),this._attributes[Pe]=u}else await i.run(`DELETE FROM ${this._definition.table} WHERE ${a} = ?`,[c]);return await l?.afterDelete?.(this),!0}async restore(){if(!at(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let i=this._definition.primaryKey||"id",a=this._attributes[i];if(!a)throw Error("Cannot restore a model without a primary key");return await B().run(`UPDATE ${this._definition.table} SET ${Pe} = ? WHERE ${i} = ?`,[null,a]),this._attributes[Pe]=null,this._original=null,this}trashed(){return this._attributes[Pe]!=null}async refresh(){let i=B(),a=this._definition.primaryKey||"id",c=this._attributes[a];if(!c)throw Error("Cannot refresh a model without a primary key");let l=await i.get(`SELECT * FROM ${this._definition.table} WHERE ${a} = ?`,[c]);if(!l)return null;return this._attributes=l,this._original=null,this}replicate(){let i=this._definition.primaryKey||"id",a={...this._attributes};return delete a[i],delete a.uuid,delete a.created_at,delete a.updated_at,new oe(this._definition,a)}toArray(){let i={...this._attributes};for(let[a,c]of Object.entries(this._relations))if(Array.isArray(c))i[a]=c.map((l)=>l.toArray());else if(c)i[a]=c.toArray();else i[a]=null;return i}toJSON(){let i=new Set;for(let[c,l]of Object.entries(this._definition.attributes))if(l.hidden)i.add(c);let a={};for(let[c,l]of Object.entries(this._attributes))if(!i.has(c))a[c]=l;for(let[c,l]of Object.entries(this._relations))if(Array.isArray(l))a[c]=l.map((u)=>u.toJSON());else if(l)a[c]=l.toJSON();else a[c]=null;return a}}var xi=new Map,Ei=new Map,ot=new Map,hc=1000;function ge(i){return I(i)}function I(i){let a=xi.get(i);if(a!==void 0)return a;return a=i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),xi.set(i,a),a}function Be(i){let a=Ei.get(i);if(a!==void 0)return a;return a=Ue(i),Ei.set(i,a),a}var Sr=["hasMany","hasOne","belongsTo","belongsToMany"],gc=[...Sr,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Ci(i,a){let c=i[a];if(!c)return[];if(Array.isArray(c))return c.map((l)=>typeof l==="string"?l:String(l?.model??"")).filter(Boolean);if(typeof c==="object")return Object.keys(c);if(typeof c==="string")return[c];return[]}function mc(i,a){let c=i.name??i.table??"model",u=gc.filter((d)=>Ci(i,d).some((h)=>h.toLowerCase()===a.toLowerCase())).filter((d)=>!Sr.includes(d));if(u.length>0)return`[orm] '${c}' declares '${a}' as ${u.join("/")}, which eager loading does not support yet. Supported kinds: ${Sr.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let f=Sr.flatMap((d)=>Ci(i,d));return f.length>0?`[orm] '${c}' has no relation '${a}'. Available: ${f.join(", ")}.`:`[orm] '${c}' has no relation '${a}' \u2014 it declares no relations at all.`}function Ni(i,a){let{name:c,table:l}=i,u=i.primaryKey||"id";function f(k){if(!k)return null;if(Array.isArray(k)){for(let E of k){let S=typeof E==="string"?E:E?.model||"";if(S&&S.toLowerCase()===a.toLowerCase())return S}return null}if(typeof k==="object"){for(let[E,S]of Object.entries(k))if(E===a||E.toLowerCase()===a.toLowerCase())return typeof S==="string"?S:S?.model||S?.target||E}return null}function d(){let k=i.belongsTo;if(!k)return null;let E=a.toLowerCase(),S=(C)=>{if(typeof C==="string")return{model:C};if(C&&typeof C==="object"&&typeof C.model==="string")return{model:C.model,foreignKey:C.foreignKey};return null};if(Array.isArray(k)){for(let C of k){let N=S(C);if(N&&N.model.toLowerCase()===E)return N}return null}if(typeof k==="object"){for(let[C,N]of Object.entries(k))if(C===a||C.toLowerCase()===E)return S(N)}return null}function h(){let k=i.belongsToMany;if(!k)return null;if(Array.isArray(k)){for(let E of k)if(typeof E==="string"){if(E.toLowerCase()===a.toLowerCase())return{entry:E}}else if(E&&typeof E==="object"&&E.model){if(E.model.toLowerCase()===a.toLowerCase())return{entry:E}}return null}if(typeof k==="object"){for(let[E,S]of Object.entries(k))if(E===a||E.toLowerCase()===a.toLowerCase())return{entry:S}}return null}let g=f(i.hasMany);if(g){let E=ce(g)?.getTable?.()||Be(g),S=I(c)+"_id";return{type:"hasMany",relatedModelName:g,relatedTable:E,foreignKey:S,localKey:u}}let m=f(i.hasOne);if(m){let E=ce(m)?.getTable?.()||Be(m),S=I(c)+"_id";return{type:"hasOne",relatedModelName:m,relatedTable:E,foreignKey:S,localKey:u}}let b=d();if(b){let k=b.model,E=ce(k),S=E?.getTable?.()||Be(k),C=E?.getDefinition?.()?.primaryKey||"id",N=b.foreignKey||`${I(k)}_id`;return{type:"belongsTo",relatedModelName:k,relatedTable:S,foreignKey:N,localKey:C}}let T=h();if(T){let k=typeof T.entry==="object",E=k?T.entry.model:T.entry,C=ce(E)?.getTable?.()||Be(E),N=k?T.entry:null,V,q;if(N?.table)V=N.table;else if(N?.through){q=N.through;let re=ce(N.through);if(!re)throw Error(`[orm] belongsToMany relation '${a}' on '${c}' references unknown through model '${N.through}'. Make sure '${N.through}' is registered.`);V=re.getTable?.()||re.getDefinition?.()?.table||Be(N.through)}else{let re=Mt(l),pe=Mt(C);V=[re,pe].sort().join("_")}let ie=N?.foreignKey||`${Mt(l)}_id`,Ke=N?.relatedKey||`${Mt(C)}_id`,Ee=[];if(N?.pivot?.columns)for(let re of Object.keys(N.pivot.columns))Ee.push(re);if(q){let re=ce(q),pe=re?.getDefinition?.()||re?.definition,Ar=pe?.attributes??{},_i=pe?.primaryKey??"id";for(let lt of Object.keys(Ar)){if(lt===ie||lt===Ke||lt===_i)continue;if(!Ee.includes(lt))Ee.push(lt)}}return{type:"belongsToMany",relatedModelName:E,relatedTable:C,foreignKey:ie,localKey:u,pivotTable:V,pivotFkParent:ie,pivotFkRelated:Ke,pivotColumns:Ee,pivotModelName:q,pivotTimestamps:Boolean(N?.pivot?.timestamps)}}let v=(k,E)=>{if(!k||typeof k!=="object"||Array.isArray(k))return null;let S=k[a]??k[Object.keys(k).find((pe)=>pe.toLowerCase()===a.toLowerCase())??""];if(!S||typeof S!=="object")return null;let{through:C,target:N}=S;if(!C||!N)return null;let V=ce(C),q=V?.getDefinition?.()||V?.definition,ie=V?.getTable?.()||q?.table||Be(C),Ke=q?.primaryKey||"id",re=ce(N)?.getTable?.()||Be(N);return{type:E,relatedModelName:N,relatedTable:re,foreignKey:`${I(c)}_id`,localKey:u,throughTable:ie,throughForeignKey:`${I(c)}_id`,throughLocalKey:Ke,targetForeignKey:`${Mt(ie)}_id`}},D=v(i.hasManyThrough,"hasManyThrough");if(D)return D;let R=v(i.hasOneThrough,"hasOneThrough");if(R)return R;return null}function Rn(i,a){let c=new Set;for(let l of i){let u=l.get(a);if(u!=null)c.add(u)}return[...c]}function Mt(i){return y(e.relations?.singularizeStrategy)(i)}class Et{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(i,a,c,l){this._parent=i,this._parentDef=a,this._resolved=c,this._relatedDef=l}get parentId(){let i=this._parentDef.primaryKey||"id";return this._parent.get(i)}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(i,a,c){if(c===void 0)this._wheres.push({sql:`${this.relatedTable}.${i} = ?`,params:[a]});else this._wheres.push({sql:`${this.relatedTable}.${i} ${String(a)} ?`,params:[c]});return this}wherePivot(i,a,c){if(c===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${i} = ?`,params:[a]});else this._pivotWheres.push({sql:`${this.pivotTable}.${i} ${String(a)} ?`,params:[c]});return this}wherePivotIn(i,a){if(!a.length)return this;let c=a.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${i} IN (${c})`,params:[...a]}),this}wherePivotNotIn(i,a){if(!a.length)return this;let c=a.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${i} NOT IN (${c})`,params:[...a]}),this}wherePivotNull(i){return this._pivotWheres.push({sql:`${this.pivotTable}.${i} IS NULL`,params:[]}),this}wherePivotNotNull(i){return this._pivotWheres.push({sql:`${this.pivotTable}.${i} IS NOT NULL`,params:[]}),this}orderBy(i,a="asc"){if(Mi(i,"orderBy(column)"),a!=="asc"&&a!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${a}'`);return this._orderBy.push(`${i} ${a.toUpperCase()}`),this}limit(i){if(!Number.isFinite(i)||i<0||!Number.isInteger(i))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${i}`);return this._limit=i,this}offset(i){if(!Number.isFinite(i)||i<0||!Number.isInteger(i))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${i}`);return this._offset=i,this}relatedSelectColumns(){let i=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),a=this._relatedDef.traits;if(a?.useTimestamps||a?.timestampable)i.add("created_at"),i.add("updated_at");if(a?.useSoftDeletes||a?.softDeletable)i.add("deleted_at");if(a?.useUuid)i.add("uuid");return[...i]}buildSelect(){let i=[],c=`SELECT ${this.relatedSelectColumns().map((l)=>`${this.relatedTable}.${l} AS ${An}${l}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;c+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,c+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,i.push(this.parentId);for(let l of this._pivotWheres)c+=` AND ${l.sql}`,i.push(...l.params);for(let l of this._wheres)c+=` AND ${l.sql}`,i.push(...l.params);if(this._orderBy.length>0)c+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)c+=` LIMIT ${this._limit}`;if(this._offset!==void 0)c+=` OFFSET ${this._offset}`;return{sql:c,params:i}}hydrateRows(i){let a=this.fkParent,c=this.fkRelated;return i.map((l)=>{let u={},f={};for(let[h,g]of Object.entries(l))if(h.startsWith(An))u[h.slice(An.length)]=g;else if(h!==a&&h!==c)f[h]=g;let d=new oe(this._relatedDef,u);return d.pivot=f,d})}async get(){let i=B(),{sql:a,params:c}=this.buildSelect(),l=await i.all(a,c);return this.hydrateRows(l)}async first(){return this._limit=1,(await this.get())[0]}async count(){let i=B(),a=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,c=[this.parentId];for(let u of this._pivotWheres)a+=` AND ${u.sql}`,c.push(...u.params);let l=await i.get(a,c);return Number(l?.count??0)}async exists(){return await this.count()>0}now(){return Ie()}async attach(i,a={}){let c=B(),l=Array.isArray(i)?i:[i];if(l.length===0)return 0;let u=this._resolved.pivotTimestamps?this.now():null,f=0;for(let d of l){let h={[this.fkParent]:this.parentId,[this.fkRelated]:d,...a};if(u){if(h.created_at===void 0)h.created_at=u;if(h.updated_at===void 0)h.updated_at=u}let g=Object.keys(h),m=g.map(()=>"?").join(", "),b=`INSERT INTO ${this.pivotTable} (${g.join(", ")}) VALUES (${m})`,T=g.map((v)=>h[v]);await c.run(b,T),f++}return f}async detach(i){let a=B(),c=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,l=[this.parentId];if(i!==void 0&&i!==null){let u=Array.isArray(i)?i:[i];if(u.length===0)return 0;let f=u.map(()=>"?").join(", ");c+=` AND ${this.fkRelated} IN (${f})`,l.push(...u)}return(await a.run(c,l)).changes}async updateExistingPivot(i,a){let c=B(),l={...a};if(this._resolved.pivotTimestamps&&l.updated_at===void 0)l.updated_at=this.now();let u=Object.keys(l);if(u.length===0)return 0;let f=u.map((g)=>`${g} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${f} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,h=[...u.map((g)=>l[g]),this.parentId,i];return(await c.run(d,h)).changes}async sync(i){let a=B(),c=new Map;for(let m of i)if(m!=null&&typeof m==="object"&&"id"in m){let{id:b,...T}=m;c.set(b,T)}else c.set(m,{});let l=await a.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),u=new Set(l.map((m)=>m[this.fkRelated])),f=[],d=[],h=[],g=[...u].filter((m)=>!c.has(m));if(g.length>0)await this.detach(g),d.push(...g);for(let[m,b]of c)if(!u.has(m))await this.attach(m,b),f.push(m);else if(Object.keys(b).length>0)await this.updateExistingPivot(m,b),h.push(m);return{attached:f,detached:d,updated:h}}async toggle(i){let a=B(),c=Array.isArray(i)?i:[i];if(c.length===0)return{attached:[],detached:[]};let l=c.map(()=>"?").join(", "),u=await a.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${l})`,[this.parentId,...c]),f=new Set(u.map((g)=>g[this.fkRelated])),d=c.filter((g)=>!f.has(g)),h=c.filter((g)=>f.has(g));if(d.length>0)await this.attach(d);if(h.length>0)await this.detach(h);return{attached:d,detached:h}}}class _{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(i){this._definition=i}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(i,a,c){if(c===void 0)this._wheres.push({column:i,operator:"=",value:a,boolean:"and"});else this._wheres.push({column:i,operator:a,value:c,boolean:"and"});return this}orWhere(i,a,c){if(c===void 0)this._wheres.push({column:i,operator:"=",value:a,boolean:"or"});else this._wheres.push({column:i,operator:a,value:c,boolean:"or"});return this}whereIn(i,a){return this._wheres.push({column:i,operator:"in",value:a,boolean:"and"}),this}orWhereIn(i,a){return this._wheres.push({column:i,operator:"in",value:a,boolean:"or"}),this}whereNotIn(i,a){return this._wheres.push({column:i,operator:"not in",value:a,boolean:"and"}),this}orWhereNotIn(i,a){return this._wheres.push({column:i,operator:"not in",value:a,boolean:"or"}),this}whereNull(i){return ke(i,"whereNull(column)"),this._wheres.push({column:i,operator:"=",value:null,boolean:"and"}),this}orWhereNull(i){return ke(i,"orWhereNull(column)"),this._wheres.push({column:i,operator:"=",value:null,boolean:"or"}),this}whereNotNull(i){return ke(i,"whereNotNull(column)"),this._wheres.push({column:i,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(i){return ke(i,"orWhereNotNull(column)"),this._wheres.push({column:i,operator:"!=",value:null,boolean:"or"}),this}whereLike(i,a){return this._wheres.push({column:i,operator:"like",value:a,boolean:"and"}),this}orWhereLike(i,a){return this._wheres.push({column:i,operator:"like",value:a,boolean:"or"}),this}whereNotLike(i,a){return this._wheres.push({column:i,operator:"not like",value:a,boolean:"and"}),this}orWhereNotLike(i,a){return this._wheres.push({column:i,operator:"not like",value:a,boolean:"or"}),this}whereRaw(i,...a){return this._wheres.push({raw:i,rawParams:a,boolean:"and"}),this}orWhereRaw(i,...a){return this._wheres.push({raw:i,rawParams:a,boolean:"or"}),this}whereGroup(i){return this._addGroup("and",i)}orWhereGroup(i){return this._addGroup("or",i)}_addGroup(i,a){let c=new _(this._definition);if(a(c),c._wheres.length===0)return this;let l=[],u=c.buildWhereClauses(l);if(!u)return this;return this._wheres.push({raw:`(${u})`,rawParams:l,boolean:i}),this}whereBetween(i,a){return ke(i,"whereBetween(column)"),this._wheres.push({column:i,operator:">=",value:a[0],boolean:"and"}),this._wheres.push({column:i,operator:"<=",value:a[1],boolean:"and"}),this}whereNotBetween(i,a){ke(i,"whereNotBetween(column)");let c=ge(i);return this._wheres.push({raw:`(${c} < ? OR ${c} > ?)`,rawParams:[a[0],a[1]],boolean:"and"}),this}when(i,a){if(i)return a(this);return this}orderBy(i,a="asc"){if(Mi(i,"orderBy(column)"),a!=="asc"&&a!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${a}'`);return this._orderBy.push({column:i,direction:a}),this}orderByDesc(i){return this.orderBy(i,"desc")}orderByAsc(i){return this.orderBy(i,"asc")}limit(i){return this._limit=i,this}take(i){return this.limit(i)}offset(i){return this._offset=i,this}skip(i){return this.offset(i)}select(...i){return this._select=i,this}with(...i){for(let a of i)if(!this._withRelations.includes(a))this._withRelations.push(a);return this}getWithRelations(){return this._withRelations}buildWhereClauses(i){let a=[];for(let c of this._wheres){let l;if(c.raw){if(l=c.raw,c.rawParams&&c.rawParams.length>0)i.push(...c.rawParams)}else if(c.value===null){let u=ge(c.column);l=c.operator==="="?`${u} IS NULL`:`${u} IS NOT NULL`}else if(c.operator==="in"||c.operator==="not in"){let u=c.value;l=o(ge(c.column),u,c.operator==="not in",u.map(()=>"?").join(", ")),i.push(...u)}else l=`${ge(c.column)} ${c.operator} ?`,i.push(c.value);a.push({conn:c.boolean==="or"?"OR":"AND",sql:l})}return x(a)}softDeleteClause(){if(this._trashed==="include"||!at(this._definition))return"";return this._trashed==="only"?`${Pe} IS NOT NULL`:`${Pe} IS NULL`}assertNoUnappliedClauses(i){let a=[];if(this._limit!==void 0)a.push("limit()");if(this._offset!==void 0)a.push("offset()");if(this._orderBy.length>0)a.push("orderBy()");if(a.length>0)throw TypeError(`[orm] ${i}() cannot apply ${a.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(i){let a=this._wheres.length>0?this.buildWhereClauses(i):"",c=this.softDeleteClause();if(a&&c)return`(${a}) AND ${c}`;return a||c}buildQuery(){let i=[],c=`SELECT ${this._select.map((u)=>u==="*"?u:ge(u)).join(", ")} FROM ${this._definition.table}`,l=this.composeWhere(i);if(l)c+=` WHERE ${l}`;if(this._orderBy.length>0)c+=` ORDER BY ${this._orderBy.map((u)=>`${ge(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)c+=` LIMIT ${this._limit}`;if(this._offset!==void 0)c+=` OFFSET ${this._offset}`;return{sql:c,params:i}}toSql(){return this.buildQuery()}async eagerLoadRelations(i){if(i.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((a)=>this.eagerLoadRelation(a,i)))}async eagerLoadRelation(i,a){let c=B(),l=this._definition.primaryKey||"id",u=`${this._definition.name}:${i}`,f=ot.get(u);if(f===void 0){if(f=Ni(this._definition,i),ot.size>=hc)ot.clear();ot.set(u,f)}if(!f)throw Error(mc(this._definition,i));if(f.type==="hasMany"||f.type==="hasOne"){let d=Rn(a,l);if(d.length===0)return;let h=d.map(()=>"?").join(", "),g=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${f.foreignKey} IN (${h})`,d),m=ce(f.relatedModelName),b=m?.getDefinition?.()||m?.definition||this._definition;if(f.type==="hasMany"){let T=new Map;for(let v of g){let D=v[f.foreignKey];if(!T.has(D))T.set(D,[]);T.get(D).push(v)}for(let v of a){let D=T.get(v.get(l))||[];v.setRelation(i,D.map((R)=>new oe(b,R)))}}else{let T=new Map;for(let v of g){let D=v[f.foreignKey];if(!T.has(D))T.set(D,v)}for(let v of a){let D=T.get(v.get(l));v.setRelation(i,D?new oe(b,D):null)}}}if(f.type==="belongsTo"){let d=new Set;for(let D of a){let R=D._attributes[f.foreignKey];if(R!=null)d.add(R)}let h=[...d];if(h.length===0)return;let g=h.map(()=>"?").join(", "),m=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${f.localKey} IN (${g})`,h),b=ce(f.relatedModelName),T=b?.getDefinition?.()||b?.definition||this._definition,v=new Map;for(let D of m)v.set(D[f.localKey],D);for(let D of a){let R=D._attributes[f.foreignKey],k=v.get(R);D.setRelation(i,k?new oe(T,k):null)}}if(f.type==="belongsToMany"){let d=Rn(a,l);if(d.length===0)return;if(!f.pivotTable||!f.pivotFkParent||!f.pivotFkRelated)return;let h=d.map(()=>"?").join(", "),g=await c.all(`SELECT * FROM ${f.pivotTable} WHERE ${f.pivotFkParent} IN (${h})`,d);if(g.length===0){for(let C of a)C.setRelation(i,[]);return}let m=new Set;for(let C of g){let N=C[f.pivotFkRelated];if(N!=null)m.add(N)}let b=[...m],T=ce(f.relatedModelName),v=T?.getDefinition?.()||T?.definition||this._definition,D=v?.primaryKey||"id",R=[];if(b.length>0){let C=b.map(()=>"?").join(", ");R=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${D} IN (${C})`,b)}let k=new Map;for(let C of R)k.set(C[D],C);let E=new Map;for(let C of g){let N=C[f.pivotFkParent];if(!E.has(N))E.set(N,[]);E.get(N).push(C)}let S=new Set([f.pivotFkParent,f.pivotFkRelated]);for(let C of a){let N=C.get(l),q=(E.get(N)||[]).map((ie)=>{let Ke=k.get(ie[f.pivotFkRelated]);if(!Ke)return null;let Ee=new oe(v,Ke),re={};for(let[pe,Ar]of Object.entries(ie))if(!S.has(pe))re[pe]=Ar;return Ee.pivot=re,Ee}).filter((ie)=>ie!==null);C.setRelation(i,q)}}if(f.type==="hasManyThrough"||f.type==="hasOneThrough"){let d=Rn(a,l);if(d.length===0)return;let h=f.throughLocalKey||"id",g=d.map(()=>"?").join(", "),m=await c.all(`SELECT ${h}, ${f.throughForeignKey} FROM ${f.throughTable} WHERE ${f.throughForeignKey} IN (${g})`,d);if(m.length===0){for(let S of a)S.setRelation(i,f.type==="hasManyThrough"?[]:null);return}let b=new Map;for(let S of m)b.set(S[h],S[f.throughForeignKey]);let T=[...new Set(m.map((S)=>S[h]))],v=T.map(()=>"?").join(", "),D=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${f.targetForeignKey} IN (${v})`,T),R=ce(f.relatedModelName),k=R?.getDefinition?.()||R?.definition||this._definition,E=new Map;for(let S of D){let C=b.get(S[f.targetForeignKey]);if(C==null)continue;if(!E.has(C))E.set(C,[]);E.get(C).push(new oe(k,S))}for(let S of a){let C=E.get(S.get(l))||[];S.setRelation(i,f.type==="hasManyThrough"?C:C[0]??null)}}}async get(){let i=B(),{sql:a,params:c}=this.buildQuery(),u=(await i.all(a,c)).map((f)=>new oe(this._definition,f));if(this._withRelations.length>0)await this.eagerLoadRelations(u);return u}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let i=await this.first();if(!i)throw Error(`No ${this._definition.name} found`);return i}async last(){let i=this._definition.primaryKey||"id";return this._orderBy=[{column:i,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let i=B(),a=[],c=`SELECT COUNT(*) as count FROM ${this._definition.table}`,l=this.composeWhere(a);if(l)c+=` WHERE ${l}`;let u=await i.get(c,a);return Number(u?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let i=await this.get();if(i.length===0)throw Error(`No ${this._definition.name} found`);if(i.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return i[0]}async increment(i,a=1){ke(i,"increment(column)"),this.assertNoUnappliedClauses("increment");let c=B(),l=[a],u=ge(i),f=`UPDATE ${this._definition.table} SET ${u} = ${u} + ?`;if(je(this._definition))f+=", updated_at = ?",l.push(Ie());let d=this.composeWhere(l);if(d)f+=` WHERE ${d}`;return(await c.run(f,l)).changes}decrement(i,a=1){return this.increment(i,-a)}async chunk(i,a){let c=0;while(!0){let l=new _(this._definition);l._wheres=[...this._wheres],l._orderBy=[...this._orderBy],l._select=[...this._select],l._withRelations=[...this._withRelations],l._trashed=this._trashed,l._limit=i,l._offset=c*i;let u=await l.get();if(u.length===0)break;if(await a(u)===!1)break;if(u.length<i)break;c++}}async paginate(i=1,a=15){if(typeof i==="object"&&i!==null){let f=i;a=f.perPage??15,i=f.page??1}let c=await this.count(),l=Math.ceil(c/a);this._limit=a,this._offset=(i-1)*a;let u=await this.get();return{data:u,total:c,page:i,perPage:a,lastPage:l,hasMorePages:i<l,isEmpty:u.length===0,from:u.length>0?(i-1)*a+1:null,to:u.length>0?(i-1)*a+u.length:null,meta:{perPage:a,page:i,total:c,lastPage:l}}}async pluck(i){ke(i,"pluck(column)");let a=B(),c=[],l=ge(i),u=`SELECT ${l} FROM ${this._definition.table}`,f=this.composeWhere(c);if(f)u+=` WHERE ${f}`;if(this._orderBy.length>0)u+=` ORDER BY ${this._orderBy.map((h)=>`${ge(h.column)} ${h.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)u+=` LIMIT ${this._limit}`;if(this._offset!==void 0)u+=` OFFSET ${this._offset}`;return(await a.all(u,c)).map((h)=>h[l])}async aggregate(i,a){ke(a,`${i}(column)`);let c=B(),l=[],u=`SELECT ${i}(${ge(a)}) as v FROM ${this._definition.table}`,f=this.composeWhere(l);if(f)u+=` WHERE ${f}`;let h=(await c.get(u,l))?.v;if(h==null)return null;if(typeof h==="string"){let g=Number(h);return h.trim()!==""&&!Number.isNaN(g)?g:h}return h}max(i){return this.aggregate("MAX",i)}min(i){return this.aggregate("MIN",i)}async avg(i){return Number(await this.aggregate("AVG",i)??0)||0}async sum(i){return Number(await this.aggregate("SUM",i)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let i=B(),a=[],c=`DELETE FROM ${this._definition.table}`,l=this.composeWhere(a);if(l)c+=` WHERE ${l}`;return(await i.run(c,a)).changes}async update(i){this.assertNoUnappliedClauses("update");let a=B(),c=Object.entries(i),l=c.map(([h])=>`${ge(h)} = ?`).join(", "),u=c.map(([,h])=>h);if(je(this._definition))u.push(Ie());let f=`UPDATE ${this._definition.table} SET ${l}${je(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(u);if(d)f+=` WHERE ${d}`;return(await a.run(f,u)).changes}}function yc(i){let a={query:()=>new _(i),where(c,l,u){return new _(i).where(c,l,u)},orWhere(c,l,u){return new _(i).orWhere(c,l,u)},whereIn(c,l){return new _(i).whereIn(c,l)},whereNotIn(c,l){return new _(i).whereNotIn(c,l)},whereNull(c){return new _(i).whereNull(c)},whereNotNull(c){return new _(i).whereNotNull(c)},whereLike(c,l){return new _(i).whereLike(c,l)},orderBy(c,l="asc"){return new _(i).orderBy(c,l)},orderByDesc(c){return new _(i).orderByDesc(c)},select(...c){return new _(i).select(...c)},with(...c){return new _(i).with(...c)},limit:(c)=>new _(i).limit(c),take:(c)=>new _(i).take(c),skip:(c)=>new _(i).skip(c),withTrashed:()=>new _(i).withTrashed(),onlyTrashed:()=>new _(i).onlyTrashed(),async find(c){let l=B(),u=i.primaryKey||"id",f=at(i)?` AND ${Pe} IS NULL`:"",d=await l.get(`SELECT * FROM ${i.table} WHERE ${u} = ?${f}`,[c]);return d?new oe(i,d):void 0},async findOrFail(c){let l=await a.find(c);if(!l)throw Error(`${i.name} with id ${c} not found`);return l},async findMany(c){let l=B(),u=i.primaryKey||"id",f=at(i)?` AND ${Pe} IS NULL`:"";return(await l.all(`SELECT * FROM ${i.table} WHERE ${u} IN (${c.map(()=>"?").join(", ")})${f}`,c)).map((h)=>new oe(i,h))},all:()=>new _(i).get(),first:()=>new _(i).first(),firstOrFail:()=>new _(i).firstOrFail(),last:()=>new _(i).last(),count:()=>new _(i).count(),exists:()=>new _(i).exists(),doesntExist:()=>new _(i).doesntExist(),paginate:(c,l)=>new _(i).paginate(c,l),whereBetween(c,l){return new _(i).whereBetween(c,l)},whereNotBetween(c,l){return new _(i).whereNotBetween(c,l)},async create(c){let l=new oe(i,c);return await l.save(),l},async createMany(c){let l=[];for(let u of c)l.push(await this.create(u));return l},async updateOrCreate(c,l){let u=new _(i);for(let[d,h]of Object.entries(c))u=u.where(d,h);let f=await u.first();if(f)return await f.update(l),f;return this.create({...c,...l})},async firstOrCreate(c,l){let u=new _(i);for(let[d,h]of Object.entries(c))u=u.where(d,h);return await u.first()||this.create({...c,...l})},async destroy(c){let l=B(),u=i.primaryKey||"id";return(await l.run(`DELETE FROM ${i.table} WHERE ${u} = ?`,[c])).changes>0},remove(c){return this.destroy(c)},async truncate(){await B().run(`DELETE FROM ${i.table}`,[])},getDefinition:()=>i,getTable:()=>i.table,make(c={}){return new oe(i,c)},latest:(c="created_at")=>new _(i).orderByDesc(c),oldest:(c="created_at")=>new _(i).orderBy(c,"asc"),max:(c)=>new _(i).max(c),min:(c)=>new _(i).min(c),avg:(c)=>new _(i).avg(c),sum:(c)=>new _(i).sum(c),pluck(c){return new _(i).pluck(c)}};return new Proxy(a,{get(c,l){if(typeof l==="string"&&l.startsWith("where")&&l.length>5){let u=l.slice(5),f=u.charAt(0).toLowerCase()+u.slice(1);if(f in i.attributes||f==="id"||f===i.primaryKey)return(d)=>new _(i).where(f,d)}return Reflect.get(c,l)}})}function xt(i){let a=yc(i);if(i?.name)cc(i.name,a);return a}async function $n(i){let a=B(),c=I(i.primaryKey||"id"),l=[],u=new Set([c]);if(l.push(i.autoIncrement!==!1?`${c} INTEGER PRIMARY KEY AUTOINCREMENT`:`${c} INTEGER PRIMARY KEY`),i.traits?.useUuid)l.push("uuid TEXT UNIQUE"),u.add("uuid");for(let[f,d]of Object.entries(i.attributes)){let h=I(f);if(u.has(h))continue;u.add(h);let g=Pn(d.type),m=Ae(g);if(h.endsWith("_id")&&(g===void 0||A(g)))m="INTEGER";let b=`${h} ${m}`;if(d.unique)b+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let T=d.foreignKey;if(b+=` REFERENCES ${T.table}(${T.column??"id"})`,T.onDelete)b+=` ON DELETE ${T.onDelete.toUpperCase()}`;if(T.onUpdate)b+=` ON UPDATE ${T.onUpdate.toUpperCase()}`}l.push(b)}for(let f of M(i.belongsTo)){let d=f.foreignKey??`${I(f.model)}_id`;if(u.has(d))continue;u.add(d),l.push(`${d} INTEGER`)}if(je(i))for(let f of["created_at","updated_at"]){if(u.has(f))continue;u.add(f),l.push(`${f} TEXT`)}if(at(i)&&!u.has("deleted_at"))u.add("deleted_at"),l.push("deleted_at TEXT");await a.run(`CREATE TABLE IF NOT EXISTS ${i.table} (${l.join(", ")})`,[])}async function En(i,a,c){let l=B(),u=i.traits?.useSeeder,f=a??(typeof u==="object"&&u?u.count:10);if(!c)try{let d=await import("./chunk-0h2h0qf3.js");c=wt(d.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let d=0;d<f;d++){let h={};for(let[m,b]of Object.entries(i.attributes))if(b.factory)h[I(m)]=b.factory(c);if(je(i)){let m=Ie();h.created_at=m,h.updated_at=m}if(i.traits?.useUuid)h.uuid=crypto.randomUUID();let g=Object.keys(h);await l.run(`INSERT INTO ${i.table} (${g.join(", ")}) VALUES (${g.map(()=>"?").join(", ")})`,Object.values(h))}}var ct=new Map;function jt(i){return ct.get(i)}function qt(){return[...ct.values()]}function Wt(){return Object.fromEntries(ct)}function Ut(i){return ct.has(i)}function Vt(){ct.clear(),St()}function vt(i,a){return ct.set(i,a),a}function pc(){return typeof window<"u"&&typeof document<"u"}function Ht(i){let a;if(pc())a=Ne(i);else{let c=xt(i);a=Object.assign(c,{definition:i,getDefinition:()=>i,getTable:()=>i.table,getName:()=>i.name})}return vt(i.name,a),a}function Qt(i){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...i}}
|
|
65
|
+
`,d+2);if(m===-1)return l;d=m;continue}if(h===47&&i.charCodeAt(d+1)===42){let m=1,b=d+2;while(b<i.length&&m>0)if(i[b]==="/"&&i[b+1]==="*")m++,b+=2;else if(i[b]==="*"&&i[b+1]==="/")m--,b+=2;else b++;d=b-1;continue}if(h===39||h===34||h===96){let m=d+1;while(m<i.length){if(i.charCodeAt(m)===h){if(i.charCodeAt(m+1)===h){m+=2;continue}break}m++}d=m;continue}if(h===36){let m=/^\$(?:[A-Z_][A-Z0-9_]*)?\$/i.exec(i.slice(d));if(m){let b=i.indexOf(m[0],d+m[0].length);d=b===-1?i.length:b+m[0].length-1;continue}}if(h===40){u++;continue}if(h===41){u=Math.max(0,u-1);continue}if(u!==0)continue;if(d===0)continue;let g=h&-33;if(g<65||g>90)continue;if(f(i.charCodeAt(d-1)))continue;for(let{key:m,pattern:b}of a){b.lastIndex=d;let T=b.exec(i);if(!T)continue;if(l.push({key:m,start:d,length:T[0].length}),l.length>=c)return l;d+=T[0].length-1;break}}return l}function Ie(){let i=new Date().toISOString();return r(e.dialect)?i.slice(0,19).replace("T"," "):i}var Si=/^[A-Z_][A-Z0-9_]*$/i;function ke(i,a){if(typeof i!=="string"||i.length===0)throw TypeError(`[bun-query-builder] ${a}: identifier must be a non-empty string, got ${typeof i}`);if(i.length>64)throw TypeError(`[bun-query-builder] ${a}: identifier '${i}' exceeds 64 chars`);if(!Si.test(i))throw TypeError(`[bun-query-builder] ${a}: identifier '${i}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Mi(i,a){if(typeof i!=="string"||i.length===0)throw TypeError(`[bun-query-builder] ${a}: identifier must be a non-empty string, got ${typeof i}`);let c=i.split(".");if(c.length>2||c.some((l)=>l.length===0||l.length>64||!Si.test(l)))throw TypeError(`[bun-query-builder] ${a}: invalid ORDER BY column '${i}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}var kr=null,On=new Map;function cc(i,a){On.set(i,a),ot.clear()}function St(){On.clear(),ot.clear()}function ce(i){if(!kr)try{kr=import.meta.require("./chunk-0f4s7pd5.js").getModel}catch{kr=()=>{return}}return kr(i)??On.get(i)}var xr=new Map,lc=500;function $i(i){let a=xr.get(i);if(a!==void 0)return a;let c=0,l=i.replace(/\?/g,()=>`$${++c}`);if(xr.size>=lc)xr.clear();return xr.set(i,l),l}function Dt(i){if(i==null)return 0;if(typeof i.affectedRows==="number")return i.affectedRows;if(typeof i.count==="number")return i.count;if(Array.isArray(i))return i.length;return 0}function $t(i){if(i==null||typeof i!=="object")return null;if("insertId"in i&&i.insertId!=null)return i.insertId;if("lastInsertRowid"in i&&i.lastInsertRowid!=null)return i.lastInsertRowid;return null}class _n{sqliteDb;dialect="sqlite";constructor(i){this.sqliteDb=i}all(i,a){return Promise.resolve(this.sqliteDb.query(i).all(...a))}get(i,a){return Promise.resolve(this.sqliteDb.query(i).get(...a)??void 0)}run(i,a){let c=this.sqliteDb.run(i,a);return Promise.resolve({changes:c.changes,lastInsertId:c.lastInsertRowid})}insert(i,a){return this.run(i,a)}}class Ai{dialect;constructor(i){this.dialect=i}conn(){return w()}text(i){return this.dialect==="postgres"?$i(i):i}async all(i,a){let c=await this.conn().unsafe(this.text(i),a);return Array.isArray(c)?c:[]}async get(i,a){let c=await this.conn().unsafe(this.text(i),a);if(Array.isArray(c))return c[0]??void 0;return c??void 0}async run(i,a){let c=await this.conn().unsafe(this.text(i),a);return{changes:Dt(c),lastInsertId:$t(c)}}async insert(i,a,c){if(this.dialect==="postgres"){let f=await this.conn().unsafe(`${$i(i)} RETURNING ${c}`,a),d=Array.isArray(f)?f[0]:f;return{changes:1,lastInsertId:d?d[c]??null:null}}let l=await this.conn().unsafe(i,a),u=$t(l);if(u==null){let f=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);u=(Array.isArray(f)?f[0]:f)?.id??null}return{changes:Dt(l)||1,lastInsertId:u}}}var xe=null,Mr=!1,ye=null,it=null,Er=null,Cr=null;function wn(i){if(i.database instanceof Nn)xe=i.database,Mr=!1;else xe=new Nn(i.database||":memory:",{create:!0}),Mr=!0,G(xe);ye=null,it=null}function Sn(){let i=Mr,a=xe;if(xe=null,Mr=!1,ye=null,it=null,Er=null,Cr=null,i&&a)try{a.close()}catch{}}function B(){if(xe){if(!ye||it!==xe)ye=new _n(xe),it=xe,Er="sqlite",Cr=null;return ye}let i=e.dialect,a=e.database?.database??null;if(ye&&it===null&&Er===i&&Cr===a)return ye;if(it=null,Er=i,Cr=a,i==="sqlite"){let c=new Nn(a||":memory:",{create:!0});G(c),ye=new _n(c)}else ye=new Ai(i);return ye}function Dn(){let i=B();if(i.sqliteDb)return i.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${i.dialect}'. Use the async model API instead.`)}var Pe="deleted_at",An="__btm_rel__";function at(i){let a=i.traits;return Boolean(a?.useSoftDeletes||a?.softDeletable)}function je(i){let a=i.traits;return Boolean(a?.useTimestamps||a?.timestampable)}var ki=new WeakMap;function uc(i){let a=ki.get(i);if(a)return a;let c=new Set,l=i.belongsToMany;if(l){if(Array.isArray(l)){for(let u of l)if(typeof u==="string")c.add(u.toLowerCase());else if(u&&typeof u==="object"&&u.model)c.add(u.model.toLowerCase())}else if(typeof l==="object")for(let u of Object.keys(l))c.add(u)}return ki.set(i,c),c}function Ri(i){let a={};for(let[c,l]of Object.entries(i))a[I(c)]=l;return a}function fc(i){for(let a in i)if(I(a)!==a)return Ri(i);return i}function dc(i,a){if(i[a])return i[a];let c=I(a);if(i[c])return i[c];for(let l of Object.keys(i))if(I(l)===c)return i[l];return}class oe{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_relations={};constructor(i,a={}){this._definition=i,this._attributes=fc({...a}),this._original=null;let c=uc(i);if(c.size===0)return;let l=this;return new Proxy(this,{get(u,f,d){if(typeof f==="string"&&c.has(f)&&!(f in u))return()=>{let h=Ni(i,f);if(!h||h.type!=="belongsToMany")throw Error(`[orm] relation '${f}' did not resolve to a belongsToMany on '${i.name}'`);let g=ce(h.relatedModelName),m=g?.getDefinition?.()||g?.definition;if(!m)throw Error(`[orm] related model '${h.relatedModelName}' is not registered`);return new Et(l,i,h,m)};return Reflect.get(u,f,d)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(i){let a=this._definition.get?.[i];if(a)try{let c=a(this._attributes);if(c!==void 0)return c}catch{}return this._attributes[I(i)]}getAttribute(i){return this._attributes[I(i)]}getAttributes(){return{...this._attributes}}set(i,a){if(this._original===null)this._original={...this._attributes};this._attributes[I(i)]=a}only(i){let a={};for(let c of i)a[c]=this._attributes[I(c)];return a}except(i){let a=new Set(i.map((l)=>I(l))),c={};for(let l of Object.keys(this._attributes))if(!a.has(l))c[l]=this._attributes[l];return c}getRelation(i){return this._relations[i]}setRelation(i,a){this._relations[i]=a}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let i=this._definition.primaryKey||"id";return this._attributes[i]}isDirty(i){if(this._original===null)return!1;if(i){let a=I(i);return this._attributes[a]!==this._original[a]}return Object.keys(this._attributes).some((a)=>this._attributes[a]!==this._original[a])}isClean(i){return!this.isDirty(i)}getOriginal(i){return this.getOriginalAttributes()[I(i)]}getChanges(){if(this._original===null)return{};let i={};for(let a of Object.keys(this._attributes))if(this._attributes[a]!==this._original[a])i[a]=this._attributes[a];return i}fill(i){let a=this._definition.attributes;for(let[c,l]of Object.entries(i)){let u=dc(a,c),f=!u&&I(c).endsWith("_id");if(u?.fillable&&!u?.guarded||f){if(this._original===null)this._original={...this._attributes};this._attributes[I(c)]=l}}return this}forceFill(i){if(this._original===null)this._original={...this._attributes};let a=Ri(i);Object.assign(this._attributes,a);for(let c of Object.keys(a))this._forced.add(c);return this}async save(){let i=B(),a=this._definition.primaryKey||"id",c=this._definition.hooks,l=this._definition.set||{};for(let[u,f]of Object.entries(l))if(this.isDirty(u))this._attributes[I(u)]=f(this._attributes);if(this._attributes[a]){await c?.beforeUpdate?.(this,this.getChanges());let u=this.getChanges(),f=Object.keys(u);if(f.length>0){let d=f.map((g)=>`${g} = ?`).join(", "),h=[...Object.values(u),this._attributes[a]];if(je(this._definition)){let g=Ie();await i.run(`UPDATE ${this._definition.table} SET ${d}, updated_at = ? WHERE ${a} = ?`,[...Object.values(u),g,this._attributes[a]])}else await i.run(`UPDATE ${this._definition.table} SET ${d} WHERE ${a} = ?`,h)}await c?.afterUpdate?.(this)}else{let u=this._definition.attributes,f={};for(let[m,b]of Object.entries(u)){if(b.guarded&&!this._forced.has(I(m)))continue;let T=I(m);if(this._attributes[T]!==void 0)f[T]=this._attributes[T]}for(let m of Object.keys(this._attributes))if(m.endsWith("_id")&&m!==a&&!(m in f))f[m]=this._attributes[m];if(je(this._definition)){let m=Ie(),b=this._attributes.created_at;f.created_at=b===void 0||b===null?m:b,f.updated_at=m}if(this._definition.traits?.useUuid&&!f.uuid)f.uuid=crypto.randomUUID();await c?.beforeCreate?.(f);let d=Object.keys(f),h=d.map(()=>"?").join(", "),g=await i.insert(`INSERT INTO ${this._definition.table} (${d.join(", ")}) VALUES (${h})`,Object.values(f),a);for(let[m,b]of Object.entries(f))this._attributes[m]=b;if(g.lastInsertId!=null)this._attributes[a]=g.lastInsertId;await c?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update(i){return this.fill(i),this.save()}async fresh(){let i=B(),a=this._definition.primaryKey||"id",c=this._attributes[a];if(c==null)return null;let l=await i.get(`SELECT * FROM ${this._definition.table} WHERE ${a} = ?`,[c]);if(!l)return null;return new oe(this._definition,l)}async delete(){let i=B(),a=this._definition.primaryKey||"id",c=this._attributes[a],l=this._definition.hooks;if(!c)throw Error("Cannot delete a model without a primary key");if(await l?.beforeDelete?.(this),at(this._definition)){let u=Ie();await i.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${a} = ?`,[u,c]),this._attributes[Pe]=u}else await i.run(`DELETE FROM ${this._definition.table} WHERE ${a} = ?`,[c]);return await l?.afterDelete?.(this),!0}async restore(){if(!at(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let i=this._definition.primaryKey||"id",a=this._attributes[i];if(!a)throw Error("Cannot restore a model without a primary key");return await B().run(`UPDATE ${this._definition.table} SET ${Pe} = ? WHERE ${i} = ?`,[null,a]),this._attributes[Pe]=null,this._original=null,this}trashed(){return this._attributes[Pe]!=null}async refresh(){let i=B(),a=this._definition.primaryKey||"id",c=this._attributes[a];if(!c)throw Error("Cannot refresh a model without a primary key");let l=await i.get(`SELECT * FROM ${this._definition.table} WHERE ${a} = ?`,[c]);if(!l)return null;return this._attributes=l,this._original=null,this}replicate(){let i=this._definition.primaryKey||"id",a={...this._attributes};return delete a[i],delete a.uuid,delete a.created_at,delete a.updated_at,new oe(this._definition,a)}toArray(){let i={...this._attributes};for(let[a,c]of Object.entries(this._relations))if(Array.isArray(c))i[a]=c.map((l)=>l.toArray());else if(c)i[a]=c.toArray();else i[a]=null;return i}toJSON(){let i=new Set;for(let[c,l]of Object.entries(this._definition.attributes))if(l.hidden)i.add(c);let a={};for(let[c,l]of Object.entries(this._attributes))if(!i.has(c))a[c]=l;for(let[c,l]of Object.entries(this._relations))if(Array.isArray(l))a[c]=l.map((u)=>u.toJSON());else if(l)a[c]=l.toJSON();else a[c]=null;return a}}var xi=new Map,Ei=new Map,ot=new Map,hc=1000;function ge(i){return I(i)}function I(i){let a=xi.get(i);if(a!==void 0)return a;return a=i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),xi.set(i,a),a}function Be(i){let a=Ei.get(i);if(a!==void 0)return a;return a=Ue(i),Ei.set(i,a),a}var Sr=["hasMany","hasOne","belongsTo","belongsToMany"],gc=[...Sr,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Ci(i,a){let c=i[a];if(!c)return[];if(Array.isArray(c))return c.map((l)=>typeof l==="string"?l:String(l?.model??"")).filter(Boolean);if(typeof c==="object")return Object.keys(c);if(typeof c==="string")return[c];return[]}function mc(i,a){let c=i.name??i.table??"model",u=gc.filter((d)=>Ci(i,d).some((h)=>h.toLowerCase()===a.toLowerCase())).filter((d)=>!Sr.includes(d));if(u.length>0)return`[orm] '${c}' declares '${a}' as ${u.join("/")}, which eager loading does not support yet. Supported kinds: ${Sr.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let f=Sr.flatMap((d)=>Ci(i,d));return f.length>0?`[orm] '${c}' has no relation '${a}'. Available: ${f.join(", ")}.`:`[orm] '${c}' has no relation '${a}' \u2014 it declares no relations at all.`}function Ni(i,a){let{name:c,table:l}=i,u=i.primaryKey||"id";function f(k){if(!k)return null;if(Array.isArray(k)){for(let E of k){let S=typeof E==="string"?E:E?.model||"";if(S&&S.toLowerCase()===a.toLowerCase())return S}return null}if(typeof k==="object"){for(let[E,S]of Object.entries(k))if(E===a||E.toLowerCase()===a.toLowerCase())return typeof S==="string"?S:S?.model||S?.target||E}return null}function d(){let k=i.belongsTo;if(!k)return null;let E=a.toLowerCase(),S=(C)=>{if(typeof C==="string")return{model:C};if(C&&typeof C==="object"&&typeof C.model==="string")return{model:C.model,foreignKey:C.foreignKey};return null};if(Array.isArray(k)){for(let C of k){let N=S(C);if(N&&N.model.toLowerCase()===E)return N}return null}if(typeof k==="object"){for(let[C,N]of Object.entries(k))if(C===a||C.toLowerCase()===E)return S(N)}return null}function h(){let k=i.belongsToMany;if(!k)return null;if(Array.isArray(k)){for(let E of k)if(typeof E==="string"){if(E.toLowerCase()===a.toLowerCase())return{entry:E}}else if(E&&typeof E==="object"&&E.model){if(E.model.toLowerCase()===a.toLowerCase())return{entry:E}}return null}if(typeof k==="object"){for(let[E,S]of Object.entries(k))if(E===a||E.toLowerCase()===a.toLowerCase())return{entry:S}}return null}let g=f(i.hasMany);if(g){let E=ce(g)?.getTable?.()||Be(g),S=I(c)+"_id";return{type:"hasMany",relatedModelName:g,relatedTable:E,foreignKey:S,localKey:u}}let m=f(i.hasOne);if(m){let E=ce(m)?.getTable?.()||Be(m),S=I(c)+"_id";return{type:"hasOne",relatedModelName:m,relatedTable:E,foreignKey:S,localKey:u}}let b=d();if(b){let k=b.model,E=ce(k),S=E?.getTable?.()||Be(k),C=E?.getDefinition?.()?.primaryKey||"id",N=b.foreignKey||`${I(k)}_id`;return{type:"belongsTo",relatedModelName:k,relatedTable:S,foreignKey:N,localKey:C}}let T=h();if(T){let k=typeof T.entry==="object",E=k?T.entry.model:T.entry,C=ce(E)?.getTable?.()||Be(E),N=k?T.entry:null,V,q;if(N?.table)V=N.table;else if(N?.through){q=N.through;let re=ce(N.through);if(!re)throw Error(`[orm] belongsToMany relation '${a}' on '${c}' references unknown through model '${N.through}'. Make sure '${N.through}' is registered.`);V=re.getTable?.()||re.getDefinition?.()?.table||Be(N.through)}else{let re=Mt(l),pe=Mt(C);V=[re,pe].sort().join("_")}let ie=N?.foreignKey||`${Mt(l)}_id`,Ke=N?.relatedKey||`${Mt(C)}_id`,Ee=[];if(N?.pivot?.columns)for(let re of Object.keys(N.pivot.columns))Ee.push(re);if(q){let re=ce(q),pe=re?.getDefinition?.()||re?.definition,Ar=pe?.attributes??{},_i=pe?.primaryKey??"id";for(let lt of Object.keys(Ar)){if(lt===ie||lt===Ke||lt===_i)continue;if(!Ee.includes(lt))Ee.push(lt)}}return{type:"belongsToMany",relatedModelName:E,relatedTable:C,foreignKey:ie,localKey:u,pivotTable:V,pivotFkParent:ie,pivotFkRelated:Ke,pivotColumns:Ee,pivotModelName:q,pivotTimestamps:Boolean(N?.pivot?.timestamps)}}let v=(k,E)=>{if(!k||typeof k!=="object"||Array.isArray(k))return null;let S=k[a]??k[Object.keys(k).find((pe)=>pe.toLowerCase()===a.toLowerCase())??""];if(!S||typeof S!=="object")return null;let{through:C,target:N}=S;if(!C||!N)return null;let V=ce(C),q=V?.getDefinition?.()||V?.definition,ie=V?.getTable?.()||q?.table||Be(C),Ke=q?.primaryKey||"id",re=ce(N)?.getTable?.()||Be(N);return{type:E,relatedModelName:N,relatedTable:re,foreignKey:`${I(c)}_id`,localKey:u,throughTable:ie,throughForeignKey:`${I(c)}_id`,throughLocalKey:Ke,targetForeignKey:`${Mt(ie)}_id`}},D=v(i.hasManyThrough,"hasManyThrough");if(D)return D;let R=v(i.hasOneThrough,"hasOneThrough");if(R)return R;return null}function Rn(i,a){let c=new Set;for(let l of i){let u=l.get(a);if(u!=null)c.add(u)}return[...c]}function Mt(i){return y(e.relations?.singularizeStrategy)(i)}class Et{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(i,a,c,l){this._parent=i,this._parentDef=a,this._resolved=c,this._relatedDef=l}get parentId(){let i=this._parentDef.primaryKey||"id";return this._parent.get(i)}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(i,a,c){if(c===void 0)this._wheres.push({sql:`${this.relatedTable}.${i} = ?`,params:[a]});else this._wheres.push({sql:`${this.relatedTable}.${i} ${String(a)} ?`,params:[c]});return this}wherePivot(i,a,c){if(c===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${i} = ?`,params:[a]});else this._pivotWheres.push({sql:`${this.pivotTable}.${i} ${String(a)} ?`,params:[c]});return this}wherePivotIn(i,a){if(!a.length)return this;let c=a.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${i} IN (${c})`,params:[...a]}),this}wherePivotNotIn(i,a){if(!a.length)return this;let c=a.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${i} NOT IN (${c})`,params:[...a]}),this}wherePivotNull(i){return this._pivotWheres.push({sql:`${this.pivotTable}.${i} IS NULL`,params:[]}),this}wherePivotNotNull(i){return this._pivotWheres.push({sql:`${this.pivotTable}.${i} IS NOT NULL`,params:[]}),this}orderBy(i,a="asc"){if(Mi(i,"orderBy(column)"),a!=="asc"&&a!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${a}'`);return this._orderBy.push(`${i} ${a.toUpperCase()}`),this}limit(i){if(!Number.isFinite(i)||i<0||!Number.isInteger(i))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${i}`);return this._limit=i,this}offset(i){if(!Number.isFinite(i)||i<0||!Number.isInteger(i))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${i}`);return this._offset=i,this}relatedSelectColumns(){let i=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),a=this._relatedDef.traits;if(a?.useTimestamps||a?.timestampable)i.add("created_at"),i.add("updated_at");if(a?.useSoftDeletes||a?.softDeletable)i.add("deleted_at");if(a?.useUuid)i.add("uuid");return[...i]}buildSelect(){let i=[],c=`SELECT ${this.relatedSelectColumns().map((l)=>`${this.relatedTable}.${l} AS ${An}${l}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;c+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,c+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,i.push(this.parentId);for(let l of this._pivotWheres)c+=` AND ${l.sql}`,i.push(...l.params);for(let l of this._wheres)c+=` AND ${l.sql}`,i.push(...l.params);if(this._orderBy.length>0)c+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)c+=` LIMIT ${this._limit}`;if(this._offset!==void 0)c+=` OFFSET ${this._offset}`;return{sql:c,params:i}}hydrateRows(i){let a=this.fkParent,c=this.fkRelated;return i.map((l)=>{let u={},f={};for(let[h,g]of Object.entries(l))if(h.startsWith(An))u[h.slice(An.length)]=g;else if(h!==a&&h!==c)f[h]=g;let d=new oe(this._relatedDef,u);return d.pivot=f,d})}async get(){let i=B(),{sql:a,params:c}=this.buildSelect(),l=await i.all(a,c);return this.hydrateRows(l)}async first(){return this._limit=1,(await this.get())[0]}async count(){let i=B(),a=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,c=[this.parentId];for(let u of this._pivotWheres)a+=` AND ${u.sql}`,c.push(...u.params);let l=await i.get(a,c);return Number(l?.count??0)}async exists(){return await this.count()>0}now(){return Ie()}async attach(i,a={}){let c=B(),l=Array.isArray(i)?i:[i];if(l.length===0)return 0;let u=this._resolved.pivotTimestamps?this.now():null,f=0;for(let d of l){let h={[this.fkParent]:this.parentId,[this.fkRelated]:d,...a};if(u){if(h.created_at===void 0)h.created_at=u;if(h.updated_at===void 0)h.updated_at=u}let g=Object.keys(h),m=g.map(()=>"?").join(", "),b=`INSERT INTO ${this.pivotTable} (${g.join(", ")}) VALUES (${m})`,T=g.map((v)=>h[v]);await c.run(b,T),f++}return f}async detach(i){let a=B(),c=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,l=[this.parentId];if(i!==void 0&&i!==null){let u=Array.isArray(i)?i:[i];if(u.length===0)return 0;let f=u.map(()=>"?").join(", ");c+=` AND ${this.fkRelated} IN (${f})`,l.push(...u)}return(await a.run(c,l)).changes}async updateExistingPivot(i,a){let c=B(),l={...a};if(this._resolved.pivotTimestamps&&l.updated_at===void 0)l.updated_at=this.now();let u=Object.keys(l);if(u.length===0)return 0;let f=u.map((g)=>`${g} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${f} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,h=[...u.map((g)=>l[g]),this.parentId,i];return(await c.run(d,h)).changes}async sync(i){let a=B(),c=new Map;for(let m of i)if(m!=null&&typeof m==="object"&&"id"in m){let{id:b,...T}=m;c.set(b,T)}else c.set(m,{});let l=await a.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),u=new Set(l.map((m)=>m[this.fkRelated])),f=[],d=[],h=[],g=[...u].filter((m)=>!c.has(m));if(g.length>0)await this.detach(g),d.push(...g);for(let[m,b]of c)if(!u.has(m))await this.attach(m,b),f.push(m);else if(Object.keys(b).length>0)await this.updateExistingPivot(m,b),h.push(m);return{attached:f,detached:d,updated:h}}async toggle(i){let a=B(),c=Array.isArray(i)?i:[i];if(c.length===0)return{attached:[],detached:[]};let l=c.map(()=>"?").join(", "),u=await a.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${l})`,[this.parentId,...c]),f=new Set(u.map((g)=>g[this.fkRelated])),d=c.filter((g)=>!f.has(g)),h=c.filter((g)=>f.has(g));if(d.length>0)await this.attach(d);if(h.length>0)await this.detach(h);return{attached:d,detached:h}}}class _{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(i){this._definition=i}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(i,a,c){if(c===void 0)this._wheres.push({column:i,operator:"=",value:a,boolean:"and"});else this._wheres.push({column:i,operator:a,value:c,boolean:"and"});return this}orWhere(i,a,c){if(c===void 0)this._wheres.push({column:i,operator:"=",value:a,boolean:"or"});else this._wheres.push({column:i,operator:a,value:c,boolean:"or"});return this}whereIn(i,a){return this._wheres.push({column:i,operator:"in",value:a,boolean:"and"}),this}orWhereIn(i,a){return this._wheres.push({column:i,operator:"in",value:a,boolean:"or"}),this}whereNotIn(i,a){return this._wheres.push({column:i,operator:"not in",value:a,boolean:"and"}),this}orWhereNotIn(i,a){return this._wheres.push({column:i,operator:"not in",value:a,boolean:"or"}),this}whereNull(i){return ke(i,"whereNull(column)"),this._wheres.push({column:i,operator:"=",value:null,boolean:"and"}),this}orWhereNull(i){return ke(i,"orWhereNull(column)"),this._wheres.push({column:i,operator:"=",value:null,boolean:"or"}),this}whereNotNull(i){return ke(i,"whereNotNull(column)"),this._wheres.push({column:i,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(i){return ke(i,"orWhereNotNull(column)"),this._wheres.push({column:i,operator:"!=",value:null,boolean:"or"}),this}whereLike(i,a){return this._wheres.push({column:i,operator:"like",value:a,boolean:"and"}),this}orWhereLike(i,a){return this._wheres.push({column:i,operator:"like",value:a,boolean:"or"}),this}whereNotLike(i,a){return this._wheres.push({column:i,operator:"not like",value:a,boolean:"and"}),this}orWhereNotLike(i,a){return this._wheres.push({column:i,operator:"not like",value:a,boolean:"or"}),this}whereRaw(i,...a){return this._wheres.push({raw:i,rawParams:a,boolean:"and"}),this}orWhereRaw(i,...a){return this._wheres.push({raw:i,rawParams:a,boolean:"or"}),this}whereGroup(i){return this._addGroup("and",i)}orWhereGroup(i){return this._addGroup("or",i)}_addGroup(i,a){let c=new _(this._definition);if(a(c),c._wheres.length===0)return this;let l=[],u=c.buildWhereClauses(l);if(!u)return this;return this._wheres.push({raw:`(${u})`,rawParams:l,boolean:i}),this}whereBetween(i,a){return ke(i,"whereBetween(column)"),this._wheres.push({column:i,operator:">=",value:a[0],boolean:"and"}),this._wheres.push({column:i,operator:"<=",value:a[1],boolean:"and"}),this}whereNotBetween(i,a){ke(i,"whereNotBetween(column)");let c=ge(i);return this._wheres.push({raw:`(${c} < ? OR ${c} > ?)`,rawParams:[a[0],a[1]],boolean:"and"}),this}when(i,a){if(i)return a(this);return this}orderBy(i,a="asc"){if(Mi(i,"orderBy(column)"),a!=="asc"&&a!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${a}'`);return this._orderBy.push({column:i,direction:a}),this}orderByDesc(i){return this.orderBy(i,"desc")}orderByAsc(i){return this.orderBy(i,"asc")}limit(i){return this._limit=i,this}take(i){return this.limit(i)}offset(i){return this._offset=i,this}skip(i){return this.offset(i)}select(...i){return this._select=i,this}with(...i){for(let a of i)if(!this._withRelations.includes(a))this._withRelations.push(a);return this}getWithRelations(){return this._withRelations}buildWhereClauses(i){let a=[];for(let c of this._wheres){let l;if(c.raw){if(l=c.raw,c.rawParams&&c.rawParams.length>0)i.push(...c.rawParams)}else if(c.value===null){let u=ge(c.column);l=c.operator==="="?`${u} IS NULL`:`${u} IS NOT NULL`}else if(c.operator==="in"||c.operator==="not in"){let u=c.value;l=o(ge(c.column),u,c.operator==="not in",u.map(()=>"?").join(", ")),i.push(...u)}else l=`${ge(c.column)} ${c.operator} ?`,i.push(c.value);a.push({conn:c.boolean==="or"?"OR":"AND",sql:l})}return x(a)}softDeleteClause(){if(this._trashed==="include"||!at(this._definition))return"";return this._trashed==="only"?`${Pe} IS NOT NULL`:`${Pe} IS NULL`}assertNoUnappliedClauses(i){let a=[];if(this._limit!==void 0)a.push("limit()");if(this._offset!==void 0)a.push("offset()");if(this._orderBy.length>0)a.push("orderBy()");if(a.length>0)throw TypeError(`[orm] ${i}() cannot apply ${a.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(i){let a=this._wheres.length>0?this.buildWhereClauses(i):"",c=this.softDeleteClause();if(a&&c)return`(${a}) AND ${c}`;return a||c}buildQuery(){let i=[],c=`SELECT ${this._select.map((u)=>u==="*"?u:ge(u)).join(", ")} FROM ${this._definition.table}`,l=this.composeWhere(i);if(l)c+=` WHERE ${l}`;if(this._orderBy.length>0)c+=` ORDER BY ${this._orderBy.map((u)=>`${ge(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)c+=` LIMIT ${this._limit}`;if(this._offset!==void 0)c+=` OFFSET ${this._offset}`;return{sql:c,params:i}}toSql(){return this.buildQuery()}async eagerLoadRelations(i){if(i.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((a)=>this.eagerLoadRelation(a,i)))}async eagerLoadRelation(i,a){let c=B(),l=this._definition.primaryKey||"id",u=`${this._definition.name}:${i}`,f=ot.get(u);if(f===void 0){if(f=Ni(this._definition,i),ot.size>=hc)ot.clear();ot.set(u,f)}if(!f)throw Error(mc(this._definition,i));if(f.type==="hasMany"||f.type==="hasOne"){let d=Rn(a,l);if(d.length===0)return;let h=d.map(()=>"?").join(", "),g=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${f.foreignKey} IN (${h})`,d),m=ce(f.relatedModelName),b=m?.getDefinition?.()||m?.definition||this._definition;if(f.type==="hasMany"){let T=new Map;for(let v of g){let D=v[f.foreignKey];if(!T.has(D))T.set(D,[]);T.get(D).push(v)}for(let v of a){let D=T.get(v.get(l))||[];v.setRelation(i,D.map((R)=>new oe(b,R)))}}else{let T=new Map;for(let v of g){let D=v[f.foreignKey];if(!T.has(D))T.set(D,v)}for(let v of a){let D=T.get(v.get(l));v.setRelation(i,D?new oe(b,D):null)}}}if(f.type==="belongsTo"){let d=new Set;for(let D of a){let R=D._attributes[f.foreignKey];if(R!=null)d.add(R)}let h=[...d];if(h.length===0)return;let g=h.map(()=>"?").join(", "),m=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${f.localKey} IN (${g})`,h),b=ce(f.relatedModelName),T=b?.getDefinition?.()||b?.definition||this._definition,v=new Map;for(let D of m)v.set(D[f.localKey],D);for(let D of a){let R=D._attributes[f.foreignKey],k=v.get(R);D.setRelation(i,k?new oe(T,k):null)}}if(f.type==="belongsToMany"){let d=Rn(a,l);if(d.length===0)return;if(!f.pivotTable||!f.pivotFkParent||!f.pivotFkRelated)return;let h=d.map(()=>"?").join(", "),g=await c.all(`SELECT * FROM ${f.pivotTable} WHERE ${f.pivotFkParent} IN (${h})`,d);if(g.length===0){for(let C of a)C.setRelation(i,[]);return}let m=new Set;for(let C of g){let N=C[f.pivotFkRelated];if(N!=null)m.add(N)}let b=[...m],T=ce(f.relatedModelName),v=T?.getDefinition?.()||T?.definition||this._definition,D=v?.primaryKey||"id",R=[];if(b.length>0){let C=b.map(()=>"?").join(", ");R=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${D} IN (${C})`,b)}let k=new Map;for(let C of R)k.set(C[D],C);let E=new Map;for(let C of g){let N=C[f.pivotFkParent];if(!E.has(N))E.set(N,[]);E.get(N).push(C)}let S=new Set([f.pivotFkParent,f.pivotFkRelated]);for(let C of a){let N=C.get(l),q=(E.get(N)||[]).map((ie)=>{let Ke=k.get(ie[f.pivotFkRelated]);if(!Ke)return null;let Ee=new oe(v,Ke),re={};for(let[pe,Ar]of Object.entries(ie))if(!S.has(pe))re[pe]=Ar;return Ee.pivot=re,Ee}).filter((ie)=>ie!==null);C.setRelation(i,q)}}if(f.type==="hasManyThrough"||f.type==="hasOneThrough"){let d=Rn(a,l);if(d.length===0)return;let h=f.throughLocalKey||"id",g=d.map(()=>"?").join(", "),m=await c.all(`SELECT ${h}, ${f.throughForeignKey} FROM ${f.throughTable} WHERE ${f.throughForeignKey} IN (${g})`,d);if(m.length===0){for(let S of a)S.setRelation(i,f.type==="hasManyThrough"?[]:null);return}let b=new Map;for(let S of m)b.set(S[h],S[f.throughForeignKey]);let T=[...new Set(m.map((S)=>S[h]))],v=T.map(()=>"?").join(", "),D=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${f.targetForeignKey} IN (${v})`,T),R=ce(f.relatedModelName),k=R?.getDefinition?.()||R?.definition||this._definition,E=new Map;for(let S of D){let C=b.get(S[f.targetForeignKey]);if(C==null)continue;if(!E.has(C))E.set(C,[]);E.get(C).push(new oe(k,S))}for(let S of a){let C=E.get(S.get(l))||[];S.setRelation(i,f.type==="hasManyThrough"?C:C[0]??null)}}}async get(){let i=B(),{sql:a,params:c}=this.buildQuery(),u=(await i.all(a,c)).map((f)=>new oe(this._definition,f));if(this._withRelations.length>0)await this.eagerLoadRelations(u);return u}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let i=await this.first();if(!i)throw Error(`No ${this._definition.name} found`);return i}async last(){let i=this._definition.primaryKey||"id";return this._orderBy=[{column:i,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let i=B(),a=[],c=`SELECT COUNT(*) as count FROM ${this._definition.table}`,l=this.composeWhere(a);if(l)c+=` WHERE ${l}`;let u=await i.get(c,a);return Number(u?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let i=await this.get();if(i.length===0)throw Error(`No ${this._definition.name} found`);if(i.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return i[0]}async increment(i,a=1){ke(i,"increment(column)"),this.assertNoUnappliedClauses("increment");let c=B(),l=[a],u=ge(i),f=`UPDATE ${this._definition.table} SET ${u} = ${u} + ?`;if(je(this._definition))f+=", updated_at = ?",l.push(Ie());let d=this.composeWhere(l);if(d)f+=` WHERE ${d}`;return(await c.run(f,l)).changes}decrement(i,a=1){return this.increment(i,-a)}async chunk(i,a){let c=0;while(!0){let l=new _(this._definition);l._wheres=[...this._wheres],l._orderBy=[...this._orderBy],l._select=[...this._select],l._withRelations=[...this._withRelations],l._trashed=this._trashed,l._limit=i,l._offset=c*i;let u=await l.get();if(u.length===0)break;if(await a(u)===!1)break;if(u.length<i)break;c++}}async paginate(i=1,a=15){if(typeof i==="object"&&i!==null){let f=i;a=f.perPage??15,i=f.page??1}let c=await this.count(),l=Math.ceil(c/a);this._limit=a,this._offset=(i-1)*a;let u=await this.get();return{data:u,total:c,page:i,perPage:a,lastPage:l,hasMorePages:i<l,isEmpty:u.length===0,from:u.length>0?(i-1)*a+1:null,to:u.length>0?(i-1)*a+u.length:null,meta:{perPage:a,page:i,total:c,lastPage:l}}}async pluck(i){ke(i,"pluck(column)");let a=B(),c=[],l=ge(i),u=`SELECT ${l} FROM ${this._definition.table}`,f=this.composeWhere(c);if(f)u+=` WHERE ${f}`;if(this._orderBy.length>0)u+=` ORDER BY ${this._orderBy.map((h)=>`${ge(h.column)} ${h.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)u+=` LIMIT ${this._limit}`;if(this._offset!==void 0)u+=` OFFSET ${this._offset}`;return(await a.all(u,c)).map((h)=>h[l])}async aggregate(i,a){ke(a,`${i}(column)`);let c=B(),l=[],u=`SELECT ${i}(${ge(a)}) as v FROM ${this._definition.table}`,f=this.composeWhere(l);if(f)u+=` WHERE ${f}`;let h=(await c.get(u,l))?.v;if(h==null)return null;if(typeof h==="string"){let g=Number(h);return h.trim()!==""&&!Number.isNaN(g)?g:h}return h}max(i){return this.aggregate("MAX",i)}min(i){return this.aggregate("MIN",i)}async avg(i){return Number(await this.aggregate("AVG",i)??0)||0}async sum(i){return Number(await this.aggregate("SUM",i)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let i=B(),a=[],c=`DELETE FROM ${this._definition.table}`,l=this.composeWhere(a);if(l)c+=` WHERE ${l}`;return(await i.run(c,a)).changes}async update(i){this.assertNoUnappliedClauses("update");let a=B(),c=Object.entries(i),l=c.map(([h])=>`${ge(h)} = ?`).join(", "),u=c.map(([,h])=>h);if(je(this._definition))u.push(Ie());let f=`UPDATE ${this._definition.table} SET ${l}${je(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(u);if(d)f+=` WHERE ${d}`;return(await a.run(f,u)).changes}}function yc(i){let a={query:()=>new _(i),where(c,l,u){return new _(i).where(c,l,u)},orWhere(c,l,u){return new _(i).orWhere(c,l,u)},whereIn(c,l){return new _(i).whereIn(c,l)},whereNotIn(c,l){return new _(i).whereNotIn(c,l)},whereNull(c){return new _(i).whereNull(c)},whereNotNull(c){return new _(i).whereNotNull(c)},whereLike(c,l){return new _(i).whereLike(c,l)},orderBy(c,l="asc"){return new _(i).orderBy(c,l)},orderByDesc(c){return new _(i).orderByDesc(c)},select(...c){return new _(i).select(...c)},with(...c){return new _(i).with(...c)},limit:(c)=>new _(i).limit(c),take:(c)=>new _(i).take(c),skip:(c)=>new _(i).skip(c),withTrashed:()=>new _(i).withTrashed(),onlyTrashed:()=>new _(i).onlyTrashed(),async find(c){let l=B(),u=i.primaryKey||"id",f=at(i)?` AND ${Pe} IS NULL`:"",d=await l.get(`SELECT * FROM ${i.table} WHERE ${u} = ?${f}`,[c]);return d?new oe(i,d):void 0},async findOrFail(c){let l=await a.find(c);if(!l)throw Error(`${i.name} with id ${c} not found`);return l},async findMany(c){let l=B(),u=i.primaryKey||"id",f=at(i)?` AND ${Pe} IS NULL`:"";return(await l.all(`SELECT * FROM ${i.table} WHERE ${u} IN (${c.map(()=>"?").join(", ")})${f}`,c)).map((h)=>new oe(i,h))},all:()=>new _(i).get(),first:()=>new _(i).first(),firstOrFail:()=>new _(i).firstOrFail(),last:()=>new _(i).last(),count:()=>new _(i).count(),exists:()=>new _(i).exists(),doesntExist:()=>new _(i).doesntExist(),paginate:(c,l)=>new _(i).paginate(c,l),whereBetween(c,l){return new _(i).whereBetween(c,l)},whereNotBetween(c,l){return new _(i).whereNotBetween(c,l)},async create(c){let l=new oe(i,c);return await l.save(),l},async createMany(c){let l=[];for(let u of c)l.push(await this.create(u));return l},async updateOrCreate(c,l){let u=new _(i);for(let[d,h]of Object.entries(c))u=u.where(d,h);let f=await u.first();if(f)return await f.update(l),f;return this.create({...c,...l})},async firstOrCreate(c,l){let u=new _(i);for(let[d,h]of Object.entries(c))u=u.where(d,h);return await u.first()||this.create({...c,...l})},async destroy(c){let l=B(),u=i.primaryKey||"id";return(await l.run(`DELETE FROM ${i.table} WHERE ${u} = ?`,[c])).changes>0},remove(c){return this.destroy(c)},async truncate(){await B().run(`DELETE FROM ${i.table}`,[])},getDefinition:()=>i,getTable:()=>i.table,make(c={}){return new oe(i,c)},latest:(c="created_at")=>new _(i).orderByDesc(c),oldest:(c="created_at")=>new _(i).orderBy(c,"asc"),max:(c)=>new _(i).max(c),min:(c)=>new _(i).min(c),avg:(c)=>new _(i).avg(c),sum:(c)=>new _(i).sum(c),pluck(c){return new _(i).pluck(c)}};return new Proxy(a,{get(c,l){if(typeof l==="string"&&l.startsWith("where")&&l.length>5){let u=l.slice(5),f=u.charAt(0).toLowerCase()+u.slice(1);if(f in i.attributes||f==="id"||f===i.primaryKey)return(d)=>new _(i).where(f,d)}return Reflect.get(c,l)}})}function xt(i){let a=yc(i);if(i?.name)cc(i.name,a);return a}async function $n(i){let a=B(),c=I(i.primaryKey||"id"),l=[],u=new Set([c]);if(l.push(i.autoIncrement!==!1?`${c} INTEGER PRIMARY KEY AUTOINCREMENT`:`${c} INTEGER PRIMARY KEY`),i.traits?.useUuid)l.push("uuid TEXT UNIQUE"),u.add("uuid");for(let[f,d]of Object.entries(i.attributes)){let h=I(f);if(u.has(h))continue;u.add(h);let g=Pn(d.type),m=Ae(g);if(h.endsWith("_id")&&(g===void 0||A(g)))m="INTEGER";let b=`${h} ${m}`;if(d.unique)b+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let T=d.foreignKey;if(b+=` REFERENCES ${T.table}(${T.column??"id"})`,T.onDelete)b+=` ON DELETE ${T.onDelete.toUpperCase()}`;if(T.onUpdate)b+=` ON UPDATE ${T.onUpdate.toUpperCase()}`}l.push(b)}for(let f of M(i.belongsTo)){let d=f.foreignKey??`${I(f.model)}_id`;if(u.has(d))continue;u.add(d),l.push(`${d} INTEGER`)}if(je(i))for(let f of["created_at","updated_at"]){if(u.has(f))continue;u.add(f),l.push(`${f} TEXT`)}if(at(i)&&!u.has("deleted_at"))u.add("deleted_at"),l.push("deleted_at TEXT");await a.run(`CREATE TABLE IF NOT EXISTS ${i.table} (${l.join(", ")})`,[])}async function En(i,a,c){let l=B(),u=i.traits?.useSeeder,f=a??(typeof u==="object"&&u?u.count:10);if(!c)try{let d=await import("./chunk-0h2h0qf3.js");c=wt(d.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let d=0;d<f;d++){let h={};for(let[m,b]of Object.entries(i.attributes))if(b.factory)h[I(m)]=b.factory(c);if(je(i)){let m=Ie();h.created_at=m,h.updated_at=m}if(i.traits?.useUuid)h.uuid=crypto.randomUUID();let g=Object.keys(h);await l.run(`INSERT INTO ${i.table} (${g.join(", ")}) VALUES (${g.map(()=>"?").join(", ")})`,Object.values(h))}}var ct=new Map;function jt(i){return ct.get(i)}function qt(){return[...ct.values()]}function Wt(){return Object.fromEntries(ct)}function Ut(i){return ct.has(i)}function Vt(){ct.clear(),St()}function vt(i,a){return ct.set(i,a),a}function pc(){return typeof window<"u"&&typeof document<"u"}function Ht(i){let a;if(pc())a=Ne(i);else{let c=xt(i);a=Object.assign(c,{definition:i,getDefinition:()=>i,getTable:()=>i.table,getName:()=>i.name})}return vt(i.name,a),a}function Qt(i){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...i}}
|
|
66
66
|
export{r,bt,e,H,t,s,Q,qe,yn,It,Lt,G,Ce,w,bn,We,n,Ue,p,Kt,Ft,y,Tt,x,o,Tn,Re,A,Ae,wt,Me,M,St,Dt,$t,wn,Sn,Dn,Et,xt,$n,En,jt,qt,Wt,Ut,Vt,vt,Ht,Qt};
|
package/dist/src/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{J,S,Zt,en,l,kt,Ct,i,Qe,Ge,z,Y,X,N,Z,ee,te,ne,B,re,P,O,ie,se,_,ae,oe,Je,Be,ze,v,le,a,ce,ue,de,fe,f,Ye,b,k,C,me,he,I,ge,L,pe,K,F,R,j,ye,be,Te,we,q,Se,De,T,m,tn,nn,rn,Xe,Ze,et,tt,nt,sn,rt,Rt,an,on,ln,cn,it,un,dn,fn,$e,u,st,at,ot,lt,ct,At,W,Ee,mn,hn,ut,Pe,g,Oe,_e,Mt,gn,Nt,pn,dt,ft,mt,Bt,Pt}from"../chunk-
|
|
2
|
+
import{J,S,Zt,en,l,kt,Ct,i,Qe,Ge,z,Y,X,N,Z,ee,te,ne,B,re,P,O,ie,se,_,ae,oe,Je,Be,ze,v,le,a,ce,ue,de,fe,f,Ye,b,k,C,me,he,I,ge,L,pe,K,F,R,j,ye,be,Te,we,q,Se,De,T,m,tn,nn,rn,Xe,Ze,et,tt,nt,sn,rt,Rt,an,on,ln,cn,it,un,dn,fn,$e,u,st,at,ot,lt,ct,At,W,Ee,mn,hn,ut,Pe,g,Oe,_e,Mt,gn,Nt,pn,dt,ft,mt,Bt,Pt}from"../chunk-a11rdptj.js";import{ht,c,U,D,gt,Ie,E,xe,Le,Ke,ve,pt,d,V,ke,Fe,yt,je,Ot,_t}from"../chunk-55jccfgb.js";import{r,bt,e,H,t,s,Q,qe,yn,It,Lt,G,bn,Ue,p,Kt,Ft,y,Tn,wt,St,Dt,$t,wn,Sn,Dn,Et,xt,$n,En,jt,qt,Wt,Ut,Vt,vt,Ht,Qt}from"../chunk-xbpyj4mw.js";import{Gt,Jt,zt,h,Ve,He,Yt,Ne,Xt}from"../chunk-7xvyccgk.js";export{Et as BelongsToManyRelationBuilder,Ve as BrowserQueryBuilder,h as BrowserQueryError,It as DEFAULT_SQLITE_PRAGMAS,U as DynamoDBClient,ht as DynamoDBDriverImpl,m as DynamoDBItemBuilder,ke as DynamoDBMigrationDriver,V as DynamoDBMigrationTracker,T as DynamoDBQueryBuilder,it as DynamoDBToolingAdapter,je as EntityQueryBuilder,ot as GENERATED_MARKER,d as MIGRATIONS_TABLE,Ie as Model,a as MySQLDriver,ce as PostgresDriver,fe as SQLiteDriver,Nt as Seeder,ue as SingleStoreDriver,Xe as SingleTableManager,sn as SingleTablePatterns,et as SingleTableQueryBuilder,Ze as SingleTableRepository,g as UTC_CLOCK_DEFAULT,de as VitessDriver,G as applySqliteBootstrapPragmas,Bt as auditSchemaDrift,Xt as browserAuth,He as browserQuery,$e as buildDatabaseSchema,ve as buildDynamoDBMigrationPlan,W as buildMigrationPlan,st as buildSchemaMeta,z as cacheClear,X as cacheConfig,Y as cacheStats,Pe as canonicalStorageType,Oe as canonicalizeDefault,Se as checkSchema,St as clearLocalModels,Vt as clearModelRegistry,Qe as clearQueryCache,e as config,Gt as configureBrowser,gt as configureModels,wn as configureOrm,Ke as convertSchemaToDefinition,Yt as createBrowserDb,Ne as createBrowserModel,D as createClient,_t as createDynamo,rn as createDynamoDBClient,c as createDynamoDBDriver,nn as createDynamoDBItemBuilder,tn as createDynamoDBQueryBuilder,un as createDynamoDBToolingAdapter,wt as createFakerCompatLayer,Fe as createMigrationDriver,xt as createModel,i as createQueryBuilder,nt as createRepository,tt as createSingleTableManager,$n as createTableFromModel,B as dbInfo,P as dbOptimize,re as dbStats,O as dbWipe,bt as defaultConfig,yn as defineConfig,Ht as defineModel,gn as defineModels,pn as defineSeeder,ne as dumpDatabase,Ot as dynamo,Ct as escapeStringLiteral,k as executeMigration,ie as explain,K as explainAllQueries,ee as exportData,Dt as extractChanges,$t as extractInsertId,Le as extractModelSchema,xe as extractTableDefinition,dt as familyOfDeclared,ft as familyOfSqlType,se as file,Pt as formatSchemaDrift,be as freshDatabase,dn as generateAccessPatterns,F as generateDiagram,_e as generateDiffOperations,Mt as generateDiffSql,hn as generateDiffSqlString,b as generateMigration,ze as generateModelSource,Ee as generateSql,mn as generateSqlString,qt as getAllModels,Jt as getBrowserConfig,Q as getConfig,Dn as getDatabase,f as getDialectDriver,jt as getModel,Wt as getModelRegistry,t as getPlaceholder,s as getPlaceholders,Ut as hasModel,ut as hashMigrationPlan,E as hashTableDefinition,te as importData,Ft as inflectSingular,_ as inspectTable,oe as introspect,v as introspectDatabase,zt as isBrowser,pt as isDefinitionEqual,lt as isGeneratedMigrationSql,At as isLosslessTypeChange,r as isMysqlLike,Zt as iterateAllPivots,at as lastCreatedMigrationFiles,u as loadModels,le as makeModel,ye as makeSeeder,ln as marshallObject,me as migrateGenerate,ge as migrateList,yt as migrateModels,he as migrateRollback,I as migrateStatus,ct as migrationBody,Be as modelNameForTable,L as modelShow,P as optimizeDatabase,Rt as parseStacksModels,pe as ping,K as queryExplainAll,l as quoteColumnForDialect,en as raw,Qt as registerBrowserModels,vt as registerModel,F as relationDiagram,Sn as releaseOrm,bn as resetConnection,C as resetDatabase,H as resolveDialect,rt as resolveKeyPattern,S as resolvePivot,Lt as resolveSqlitePragmas,J as runBenchmark,j as runSeeder,R as runSeeders,mt as satisfies,Ye as saveMigrationSnapshot,En as seedModel,qe as setConfig,Ge as setQueryCacheMaxSize,L as showModel,y as singularizerFor,Te as sql,Je as sqlTypeToAttr,fn as stacksModelToEntity,N as startConsole,Kt as stripTrailingS,ae as tableInfo,p as tableNameFor,kt as temporalLiteral,Z as tinker,Tn as toDialectPlaceholders,an as toDynamoDBItem,on as toModelInstance,Ue as toTableName,cn as unmarshallItem,we as unsafe,q as validateSchema,De as waitReady,O as wipeDatabase};
|
package/package.json
CHANGED
package/dist/chunk-eczymkcb.js
DELETED