bun-query-builder 0.2.58 → 0.2.60
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 +31 -40
- package/dist/browser.d.ts +2 -2
- package/dist/chunk-bbz0pmj9.js +40 -0
- package/dist/chunk-kjkkmrp8.js +2 -0
- package/dist/chunk-mjedm810.js +7 -0
- package/dist/chunk-mvk2rcqm.js +3 -0
- package/dist/chunk-vw813qrt.js +446 -0
- package/dist/client.d.ts +19 -1
- package/dist/orm.d.ts +4 -2
- package/dist/sql-fragments.d.ts +30 -0
- package/dist/src/browser.js +1 -1
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-1mmf5p5n.js +0 -445
- package/dist/chunk-asdkg5va.js +0 -3
- package/dist/chunk-d2b8tt64.js +0 -40
- package/dist/chunk-j9778t8e.js +0 -7
- package/dist/chunk-rgnkzv8c.js +0 -2
- /package/dist/{chunk-739qq8wk.js → chunk-fn0m2c0v.js} +0 -0
package/dist/chunk-1mmf5p5n.js
DELETED
|
@@ -1,445 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Tb as y1,Wb as h1}from"./chunk-asdkg5va.js";import{Yb as a8}from"./chunk-j9778t8e.js";import{pc as nU,qc as $2,rc as A8,sc as oZ}from"./chunk-739qq8wk.js";import{existsSync as c0,statSync as u0}from"fs";import{resolve as v9}from"path";import bJ from"process";import{existsSync as pJ,mkdirSync as t2,readdirSync as a2,readFileSync as dJ,writeFileSync as e2}from"fs";import{homedir as H9}from"os";import{dirname as Yz,resolve as F8}from"path";import p$ from"process";import{existsSync as n0,statSync as i0}from"fs";import{existsSync as b7,mkdirSync as mJ,readdirSync as cJ,writeFileSync as uJ}from"fs";import{homedir as A9}from"os";import{dirname as l0,resolve as iZ}from"path";import r8 from"process";import{join as nJ,relative as iJ,resolve as s0}from"path";import S$ from"process";import{existsSync as vY,mkdirSync as Qz,readdirSync as _z,writeFileSync as Vz}from"fs";import{homedir as B7}from"os";import{dirname as Fz,resolve as nZ}from"path";import h9 from"process";import{join as lJ,relative as sJ,resolve as o0}from"path";import N$ from"process";import{existsSync as yY,mkdirSync as Dz,readdirSync as Iz,writeFileSync as Mz}from"fs";import{dirname as Cz,resolve as P$}from"path";import f7 from"process";import{Buffer as h8}from"buffer";import{createCipheriv as oJ,createDecipheriv as rJ,randomBytes as R7}from"crypto";import{closeSync as O7,createReadStream as r0,createWriteStream as tJ,existsSync as E7,fsyncSync as t0,openSync as a0,writeFileSync as aJ}from"fs";import{access as eJ,constants as e0,mkdir as ZG,readdir as H$,rename as ZY,stat as W9,unlink as A$,writeFile as D7}from"fs/promises";import{join as j9}from"path";import gZ from"process";import{pipeline as $G}from"stream/promises";import{createGzip as $Y}from"zlib";import Q9 from"process";import w8 from"process";import{Buffer as I8}from"buffer";import{createCipheriv as YG,createDecipheriv as XG,randomBytes as I7}from"crypto";import{closeSync as M7,createReadStream as YY,createWriteStream as JG,existsSync as W$,fsyncSync as XY,openSync as JY,writeFileSync as GG}from"fs";import{access as UG,constants as GY,mkdir as zG,readdir as j$,rename as UY,stat as _9,unlink as Q$,writeFile as w7}from"fs/promises";import{isAbsolute as HG,join as V9,resolve as AG}from"path";import QZ from"process";import{pipeline as WG}from"stream/promises";import{createGzip as zY}from"zlib";import K9 from"process";import C8 from"process";import _$ from"process";import{existsSync as V$}from"fs";import{resolve as C7}from"path";import{existsSync as jG}from"fs";import{existsSync as QG,readdirSync as _G}from"fs";import{extname as S7,resolve as HY}from"path";import VG from"process";import{join as KG,relative as LG,resolve as AY}from"path";import T$ from"process";import{Buffer as M8}from"buffer";import{createCipheriv as FG,createDecipheriv as BG,randomBytes as N7}from"crypto";import{closeSync as P7,createReadStream as WY,createWriteStream as RG,existsSync as K$,fsyncSync as jY,openSync as QY,writeFileSync as OG}from"fs";import{access as EG,constants as _Y,mkdir as DG,readdir as L$,rename as VY,stat as L9,unlink as F$,writeFile as T7}from"fs/promises";import{isAbsolute as IG,join as F9,resolve as MG}from"path";import _Z from"process";import{pipeline as wG}from"stream/promises";import{createGzip as KY}from"zlib";import B9 from"process";import S8 from"process";import R$ from"process";import{existsSync as O$}from"fs";import{resolve as PY}from"path";import{existsSync as n5}from"fs";class TY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Z={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Z}}generateKey(Z,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${Z}${Y}`}isExpired(Z){return Date.now()-Z.timestamp.getTime()>Z.ttl}estimateSize(Z){try{return JSON.stringify(Z).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Z=Array.from(this.cache.entries()).sort(([,Y],[,X])=>Y.timestamp.getTime()-X.timestamp.getTime()),$=Z.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(Z[Y][0])}set(Z,$,Y,X){if(!this.options.enabled)return;let J=this.generateKey(Z,Y),G=X??this.options.ttl,U=this.estimateSize($);this.cache.set(J,{value:$,timestamp:new Date,ttl:G,hits:0,size:U}),this.evictIfNeeded()}get(Z,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Z,$),X=this.cache.get(Y);if(!X){this.totalMisses++;return}if(this.isExpired(X)){this.cache.delete(Y),this.totalMisses++;return}return X.hits++,this.totalHits++,X.value}isFileModified(Z,$){try{if(!c0(Z))return!0;return u0(Z).mtime>$}catch{return!0}}getWithFileCheck(Z,$){let Y=this.get(Z,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(Z,$);return}return Y.value}setWithFileCheck(Z,$,Y,X){try{let J=c0(Y)?u0(Y):null,G=J?J.mtime:new Date;this.set(Z,{value:$,fileTimestamp:G},Y,X)}catch{this.set(Z,$,Y,X)}}delete(Z,$){let Y=this.generateKey(Z,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Z=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),Z++;return Z}getStats(){let Z=Array.from(this.cache.values()),$=Z.reduce((X,J)=>X+J.size,0),Y=Z.map((X)=>X.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Z={};for(let[$,Y]of this.cache.entries())Z[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Z}import(Z){this.cache.clear();for(let[$,Y]of Object.entries(Z))if(typeof Y==="object"&&Y!==null){let X=Y;this.cache.set($,{value:X.value,timestamp:new Date(X.timestamp),ttl:X.ttl,hits:X.hits,size:X.size})}}}class qY{metrics=[];maxMetrics=1000;async track(Z,$,Y={}){let X=performance.now(),J=new Date;try{let G=await $(),U=performance.now()-X;return this.recordMetric({operation:Z,duration:U,timestamp:J,...Y}),G}catch(G){let U=performance.now()-X;throw this.recordMetric({operation:`${Z}:error`,duration:U,timestamp:J,...Y}),G}}recordMetric(Z){if(this.metrics.push(Z),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Z){let $=Z?this.metrics.filter((J)=>J.operation===Z):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((J)=>J.duration),X=Y.reduce((J,G)=>J+G,0);return{count:$.length,averageDuration:X/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:X,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Z){return this.metrics.filter(($)=>$.duration>Z)}}function xY(Z={}){let{name:$="",alias:Y}=Z,X=["config",".config"];if($)X.push($,`.${$}.config`,`${$}.config`,`.${$}`);let J=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let G of J){if(!G)continue;if(X.push(G,`.${G}.config`,`${G}.config`,`.${G}`),$)X.push(`${$}.${G}.config`,`.${$}.${G}.config`)}return Array.from(new Set(X.filter(Boolean)))}function fJ(Z){return xY(Z).flatMap((Y)=>kY.map((X)=>v9(Z.directory,`${Y}${X}`)))}function gJ(Z={}){let $=v9(Z.cwd||bJ.cwd());return Array.from(new Set([$,v9($,"config"),v9($,".config"),Z.configDir?v9($,Z.configDir):void 0].filter((Y)=>Boolean(Y))))}function NG(Z,$){this[Z]=SG.bind(null,$)}class r7{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Z={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Z}}generateKey(Z,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${Z}${Y}`}isExpired(Z){return Date.now()-Z.timestamp.getTime()>Z.ttl}estimateSize(Z){try{return JSON.stringify(Z).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Z=Array.from(this.cache.entries()).sort(([,Y],[,X])=>Y.timestamp.getTime()-X.timestamp.getTime()),$=Z.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(Z[Y][0])}set(Z,$,Y,X){if(!this.options.enabled)return;let J=this.generateKey(Z,Y),G=X??this.options.ttl,U=this.estimateSize($);this.cache.set(J,{value:$,timestamp:new Date,ttl:G,hits:0,size:U}),this.evictIfNeeded()}get(Z,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Z,$),X=this.cache.get(Y);if(!X){this.totalMisses++;return}if(this.isExpired(X)){this.cache.delete(Y),this.totalMisses++;return}return X.hits++,this.totalHits++,X.value}isFileModified(Z,$){try{if(!n0(Z))return!0;return i0(Z).mtime>$}catch{return!0}}getWithFileCheck(Z,$){let Y=this.get(Z,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(Z,$);return}return Y.value}setWithFileCheck(Z,$,Y,X){try{let J=n0(Y)?i0(Y):null,G=J?J.mtime:new Date;this.set(Z,{value:$,fileTimestamp:G},Y,X)}catch{this.set(Z,$,Y,X)}}delete(Z,$){let Y=this.generateKey(Z,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Z=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),Z++;return Z}getStats(){let Z=Array.from(this.cache.values()),$=Z.reduce((X,J)=>X+J.size,0),Y=Z.map((X)=>X.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Z={};for(let[$,Y]of this.cache.entries())Z[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Z}import(Z){this.cache.clear();for(let[$,Y]of Object.entries(Z))if(typeof Y==="object"&&Y!==null){let X=Y;this.cache.set($,{value:X.value,timestamp:new Date(X.timestamp),ttl:X.ttl,hits:X.hits,size:X.size})}}}class t7{metrics=[];maxMetrics=1000;async track(Z,$,Y={}){let X=performance.now(),J=new Date;try{let G=await $(),U=performance.now()-X;return this.recordMetric({operation:Z,duration:U,timestamp:J,...Y}),G}catch(G){let U=performance.now()-X;throw this.recordMetric({operation:`${Z}:error`,duration:U,timestamp:J,...Y}),G}}recordMetric(Z){if(this.metrics.push(Z),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Z){let $=Z?this.metrics.filter((J)=>J.operation===Z):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((J)=>J.duration),X=Y.reduce((J,G)=>J+G,0);return{count:$.length,averageDuration:X/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:X,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Z){return this.metrics.filter(($)=>$.duration>Z)}}function qG(Z,$={}){let X=Object.keys($).sort().map((J)=>`${J}:${$[J]}`).join("|");return X?`${Z}:${X}`:Z}function kG(Z,$){try{return JSON.stringify(Z)===JSON.stringify($)}catch{return Z===$}}function xG(Z){return Z.getStats().size*2}function a7(Z,$){if(Array.isArray($)&&Array.isArray(Z)&&$.length===2&&Z.length===2&&wZ($[0])&&"id"in $[0]&&$[0].id===3&&wZ($[1])&&"id"in $[1]&&$[1].id===4)return $;if(wZ($)&&wZ(Z)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return Z;if(Array.isArray($)&&!Array.isArray(Z))return $;if(Array.isArray($)&&Array.isArray(Z)){if(wZ(Z)&&"arr"in Z&&Array.isArray(Z.arr)&&wZ($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&Z.length>0&&wZ($[0])&&wZ(Z[0])){let X=[...$];for(let J of Z)if(wZ(J)&&"name"in J){if(!X.find((U)=>wZ(U)&&("name"in U)&&U.name===J.name))X.push(J)}else if(wZ(J)&&"path"in J){if(!X.find((U)=>wZ(U)&&("path"in U)&&U.path===J.path))X.push(J)}else if(!X.some((G)=>q$(G,J)))X.push(J);return X}if($.every((X)=>typeof X==="string")&&Z.every((X)=>typeof X==="string")){let X=[...$];for(let J of Z)if(!X.includes(J))X.push(J);return X}return $}if(!wZ($)||!wZ(Z))return $;let Y={...Z};for(let X in $)if(Object.prototype.hasOwnProperty.call($,X)){let J=$[X];if(J===null||J===void 0)continue;else if(wZ(J)&&wZ(Y[X]))Y[X]=a7(Y[X],J);else if(Array.isArray(J)&&Array.isArray(Y[X]))if(J.length>0&&Y[X].length>0&&wZ(J[0])&&wZ(Y[X][0])){let G=[...J];for(let U of Y[X])if(wZ(U)&&"name"in U){if(!G.find((z)=>wZ(z)&&("name"in z)&&z.name===U.name))G.push(U)}else if(wZ(U)&&"path"in U){if(!G.find((z)=>wZ(z)&&("path"in z)&&z.path===U.path))G.push(U)}else if(!G.some((H)=>q$(H,U)))G.push(U);Y[X]=G}else if(J.every((G)=>typeof G==="string")&&Y[X].every((G)=>typeof G==="string")){let G=[...J];for(let U of Y[X])if(!G.includes(U))G.push(U);Y[X]=G}else Y[X]=J;else Y[X]=J}return Y}function q$(Z,$){if(Z===$)return!0;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;for(let Y=0;Y<Z.length;Y++)if(!q$(Z[Y],$[Y]))return!1;return!0}if(wZ(Z)&&wZ($)){let Y=Object.keys(Z),X=Object.keys($);if(Y.length!==X.length)return!1;for(let J of Y){if(!Object.prototype.hasOwnProperty.call($,J))return!1;if(!q$(Z[J],$[J]))return!1}return!0}return!1}function wZ(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}async function vG(Z,$){if(!yY(Z))return null;try{let Y=await import(Z),X=Y.default||Y;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return a7($,X)}catch{return null}}catch{return null}}async function yG({name:Z="",cwd:$,defaultConfig:Y}){let X=$||f7.cwd(),J=[".ts",".js",".mjs",".cjs",".json"],G=[`${Z}.config`,`.${Z}.config`,Z,`.${Z}`];for(let U of G)for(let H of J){let z=P$(X,`${U}${H}`),A=await vG(z,Y);if(A!==null)return A}try{let U=P$(X,"package.json");if(yY(U)){let z=(await import(U))[Z];if(z&&typeof z==="object"&&!Array.isArray(z))try{return a7(Y,z)}catch{}}}catch{}return Y}function hG(Z,$={}){let Y=N$.cwd();while(Y.includes("storage"))Y=o0(Y,"..");let X=o0(Y,Z||"");if($?.relative)return sJ(N$.cwd(),X);return X}async function bG(){try{let Z=await yG({name:"clarity",defaultConfig:D$,cwd:N$.cwd(),endpoint:"",headers:{}});return{...D$,...Z}}catch{return D$}}function SZ(){if(w8.env.NODE_ENV==="test"||w8.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fG(){if(w8.env.NODE_ENV==="test"||w8.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof w8<"u"){let Z=w8.type;if(Z==="renderer"||Z==="worker")return!1;return!!(w8.versions&&(w8.versions.node||w8.versions.bun))}return!1}class bY{async format(Z){let $=await fG(),Y=await this.getMetadata($);return JSON.stringify({timestamp:Z.timestamp.toISOString(),level:Z.level,name:Z.name,message:Z.message,metadata:Y})}async getMetadata(Z){if(Z){let{hostname:$}=await import("os");return{pid:Q9.pid,hostname:$(),environment:Q9.env.NODE_ENV||"development",platform:Q9.platform,version:Q9.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Q9.env.NODE_ENV||Q9.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class k${name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Z,$={}){this.name=Z,this.config={...p7},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new bY,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??gZ.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},X=$.timestamp!==void 0;if(X)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:X||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),G=this.generateKey();this.currentKeyId=J,this.keys.set(J,G),this.encryptionKeys.set(J,{key:G,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Z){if(!Z.fingersCrossedEnabled&&Z.fingersCrossed)return{...I$,...Z.fingersCrossed};if(!Z.fingersCrossedEnabled)return null;if(!Z.fingersCrossed)return{...I$};return{...I$,...Z.fingersCrossed}}normalizeOptions(Z){let $={format:"json",level:"info",logDirectory:p7.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(Z).filter(([,X])=>X!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(Z){let Y=(async()=>{let J,G=0,U=3,H=1000;while(G<U)try{try{try{await eJ(this.config.logDirectory,e0.F_OK|e0.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await ZG(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let z=this.validateEncryptionConfig()?(await this.encrypt(Z)).encrypted:h8.from(Z);try{if(!E7(this.currentLogFile))await D7(this.currentLogFile,"",{mode:420});if(J=a0(this.currentLogFile,"a",420),aJ(J,z,{flag:"a"}),t0(J),J!==void 0)O7(J),J=void 0;if((await W9(this.currentLogFile)).size===0){if(await D7(this.currentLogFile,z,{flag:"w",mode:420}),(await W9(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let W=A;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(G<U-1){let Q=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${U}:`,Q);let L=H*2**G;await new Promise((O)=>setTimeout(O,L)),G++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{O7(J)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(z){if(G===U-1){let W=z,Q=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Q),z}G++;let A=H*2**(G-1);await new Promise((W)=>setTimeout(W,A))}})();this.pendingOperations.push(Y);let X=this.pendingOperations.length-1;try{await Y}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(X,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return j9(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return j9(this.config.logDirectory,`${this.name}.log`);let Z=new Date().toISOString().split("T")[0];return j9(this.config.logDirectory,`${this.name}-${Z}.log`)}setupRotation(){if(SZ())return;if(typeof this.config.rotation==="boolean")return;let Z=this.config.rotation,$;switch(Z.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,X=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),X=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,X),this.encryptionKeys.set(Y,{key:X,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,H],[,z])=>z.createdAt.getTime()-H.createdAt.getTime()),G=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,G);if(J.length>U)for(let[H]of J.slice(U))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return R7(16).toString("hex")}generateKey(){return R7(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Z=this.keys.get(this.currentKeyId);if(!Z)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Z,id:this.currentKeyId}}encrypt(Z){let{key:$}=this.getCurrentKey(),Y=R7(16),X=oJ("aes-256-gcm",$,Y),J=h8.concat([X.update(Z,"utf8"),X.final()]),G=X.getAuthTag();return{encrypted:h8.concat([Y,J,G]),iv:Y}}async compressData(Z){return new Promise(($,Y)=>{let X=$Y(),J=[];X.on("data",(G)=>J.push(G)),X.on("end",()=>$(h8.from(h8.concat(J)))),X.on("error",Y),X.write(Z),X.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Z={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...Z,...$}}return Z}async rotateLog(){if(SZ())return;let Z=await W9(this.currentLogFile).catch(()=>null);if(!Z)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&Z.size>=$.maxSize){let Y=this.currentLogFile,X=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await H$(this.config.logDirectory),G=J.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,A)=>{let W=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),U=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${Y}.${U}`;if(await W9(Y).catch(()=>null))try{if(await ZY(Y,H),$.compress)try{let z=`${H}.gz`;await this.compressLogFile(H,z),await A$(H)}catch(z){console.error("Error compressing rotated file:",z)}if(G.length===0&&!J.some((z)=>z.endsWith(".log.1")))try{let z=`${Y}.1`;await D7(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${J}.log`);if(await W9(Y).catch(()=>null))await ZY(Y,G)}if(this.currentLogFile=X,$.maxFiles){let G=(await H$(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,H)=>H.localeCompare(U));for(let U of G.slice($.maxFiles))await A$(j9(this.config.logDirectory,U))}}}async compressLogFile(Z,$){let Y=r0(Z),X=tJ($),J=$Y();await $G(Y,J,X)}async handleFingersCrossedBuffer(Z,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Z)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let X=await this.formatter.format(Y);await this.writeToFile(X),console.log(X)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Z,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Z){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Z)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Z){return{debug:0,info:1,success:2,warning:3,error:4}[Z]}shouldLog(Z){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[Z]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Z)=>{if(Z instanceof Promise)return Z.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),E7(this.currentLogFile))try{let Z=a0(this.currentLogFile,"r+");t0(Z),O7(Z)}catch(Z){console.error(`Error flushing file: ${Z}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Z of this.pendingOperations)if(typeof Z.cancel==="function")Z.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Z){console.error("Error waiting for pending operations:",Z)}if(!SZ()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await H$(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await A$(j9(this.config.logDirectory,Y))}catch(X){console.error(`Failed to delete temp file ${Y}:`,X)}}catch(Z){console.error("Error cleaning up temporary files:",Z)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Z){if(!Z)return"";return`${this.tagFormat.prefix}${Z}${this.tagFormat.suffix}`}formatFileTimestamp(Z){return`[${Z.toISOString()}]`}formatConsoleTimestamp(Z){return this.fancy?IZ.gray(Z.toLocaleTimeString()):Z.toLocaleTimeString()}formatConsoleMessage(Z){let{timestamp:$,icon:Y="",tag:X="",message:J,level:G,showTimestamp:U=!0}=Z,H=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(U)O.push($);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(X)O.push(X.replace(/[[\]]/g,""));return O.push(J),O.join(" ")}let z=gZ.stdout.columns||120,A="";if(G==="warning"||G==="error")A=`${Y} ${J}`;else if(G==="info"||G==="success")A=`${Y} ${X} ${J}`;else A=`${Y} ${X} ${IZ.cyan(J)}`;if(!U)return A.trim();let W=H(A).trim().length,Q=H($).length,L=Math.max(1,z-2-W-Q);return`${A.trim()}${" ".repeat(L)}${$}`}formatMessage(Z,$){if($.length===1&&Array.isArray($[0]))return Z.replace(/\{(\d+)\}/g,(G,U)=>{let H=Number.parseInt(U,10);return H<$[0].length?String($[0][H]):G});let Y=/%([sdijfo%])/g,X=0,J=Z.replace(Y,(G,U)=>{if(U==="%")return"%";if(X>=$.length)return G;let H=$[X++];switch(U){case"s":return String(H);case"d":case"i":return Number(H).toString();case"j":case"o":return JSON.stringify(H,null,2);default:return G}});if(X<$.length)J+=` ${$.slice(X).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return J}async log(Z,$,...Y){let X=new Date,J=this.formatConsoleTimestamp(X),G=this.formatFileTimestamp(X),U,H;if($ instanceof Error)U=$.message,H=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!SZ()){let A=lY[Z],W=this.options.showTags!==!1&&this.name?IZ.gray(this.formatTag(this.name)):"",Q;switch(Z){case"debug":Q=this.formatConsoleMessage({timestamp:J,icon:A,tag:W,message:IZ.gray(U),level:Z}),console.error(Q);break;case"info":Q=this.formatConsoleMessage({timestamp:J,icon:A,tag:W,message:U,level:Z}),console.error(Q);break;case"success":Q=this.formatConsoleMessage({timestamp:J,icon:A,tag:W,message:IZ.green(U),level:Z}),console.error(Q);break;case"warning":Q=this.formatConsoleMessage({timestamp:J,icon:A,tag:W,message:U,level:Z}),console.warn(Q);break;case"error":if(Q=this.formatConsoleMessage({timestamp:J,icon:A,tag:W,message:U,level:Z}),console.error(Q),H){let L=H.split(`
|
|
3
|
-
`);for(let O of L)if(O.trim()&&!O.includes(U))console.error(this.formatConsoleMessage({timestamp:J,message:IZ.gray(` ${O}`),level:Z,showTimestamp:!1}))}break}}else if(!SZ()){if(console.error(`${G} ${this.environment}.${Z.toUpperCase()}: ${U}`),H)console.error(H)}if(!this.shouldLog(Z))return;let z=`${G} ${this.environment}.${Z.toUpperCase()}: ${U}
|
|
4
|
-
`;if(H)z+=`${H}
|
|
5
|
-
`;z=z.replace(this.ANSI_PATTERN,""),await this.writeToFile(z)}time(Z){let $=performance.now();if(this.fancy&&!SZ()){let Y=this.options.showTags!==!1&&this.name?IZ.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:IZ.blue("\u25D0"),tag:Y,message:`${IZ.cyan(Z)}...`}))}return async(Y)=>{if(!this.enabled)return;let X=performance.now(),J=Math.round(X-$),G=`${Z} completed in ${J}ms`,U=new Date,H=this.formatConsoleTimestamp(U),A=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${G}`;if(Y)A+=` ${JSON.stringify(Y)}`;if(A+=`
|
|
6
|
-
`,A=A.replace(this.ANSI_PATTERN,""),this.fancy&&!SZ()){let W=this.options.showTags!==!1&&this.name?IZ.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:H,icon:IZ.green("\u2713"),tag:W,message:`${G}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!SZ())console.error(A.trim());await this.writeToFile(A)}}async debug(Z,...$){await this.log("debug",Z,...$)}async info(Z,...$){await this.log("info",Z,...$)}async success(Z,...$){await this.log("success",Z,...$)}async warn(Z,...$){await this.log("warning",Z,...$)}async error(Z,...$){await this.log("error",Z,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Z=this.config.rotation,{encrypt:$}=Z;return!!$}async only(Z){if(!this.enabled)return;return await Z()}isEnabled(){return this.enabled}setEnabled(Z){this.enabled=Z}extend(Z){let $=`${this.name}:${Z}`,Y=new k$($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(SZ())throw Error("createReadStream is not supported in browser environments");if(!E7(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return r0(this.currentLogFile,{encoding:"utf8"})}async decrypt(Z){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let X=h8.isBuffer(Z)?Z:h8.from(Z,"base64"),J=X.slice(0,16),G=X.slice(-16),U=X.slice(16,-16),H=rJ("aes-256-gcm",Y,J);return H.setAuthTag(G),h8.concat([H.update(U),H.final()]).toString("utf8")}catch(X){throw Error(`Decryption failed: ${X instanceof Error?X.message:String(X)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return SZ()}isServerMode(){return!SZ()}setTestEncryptionKey(Z,$){this.currentKeyId=Z,this.keys.set(Z,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Z){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),X=this.formatFileTimestamp($);if(this.fancy&&!SZ()){let G=Z.split(`
|
|
7
|
-
`),U=Math.max(...G.map((W)=>W.length))+2,H=`\u250C${"\u2500".repeat(U)}\u2510`,z=`\u2514${"\u2500".repeat(U)}\u2518`,A=G.map((W)=>{let Q=" ".repeat(U-W.length-2);return`\u2502 ${W}${Q} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:IZ.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:IZ.cyan(H)})),A.forEach((W)=>console.error(this.formatConsoleMessage({timestamp:Y,message:IZ.cyan(W),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:IZ.cyan(z),showTimestamp:!1}))}else if(!SZ())console.error(`${X} ${this.environment}.INFO: [BOX] ${Z}`);let J=`${X} ${this.environment}.INFO: [BOX] ${Z}
|
|
8
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}async prompt(Z){if(SZ())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${IZ.cyan("?")} ${Z} (y/n) `);let Y=(X)=>{let J=X.toString().trim().toLowerCase();gZ.stdin.removeListener("data",Y);try{if(typeof gZ.stdin.setRawMode==="function")gZ.stdin.setRawMode(!1)}catch{}gZ.stdin.pause(),console.error(""),$(J==="y"||J==="yes")};try{if(typeof gZ.stdin.setRawMode==="function")gZ.stdin.setRawMode(!0)}catch{}gZ.stdin.resume(),gZ.stdin.once("data",Y)})}setFancy(Z){this.fancy=Z}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Z,...$){if(!this.enabled)return;let Y=Z;if($&&$.length>0){let U=/%([sdijfo%])/g,H=0;if(Y=Z.replace(U,(z,A)=>{if(A==="%")return"%";if(H>=$.length)return z;let W=$[H++];switch(A){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return z}}),H<$.length)Y+=` ${$.slice(H).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}if(this.fancy&&!SZ()){let U=this.options.showTags!==!1&&this.name?IZ.gray(this.formatTag(this.name)):"",H=IZ.blue("\u25D0");console.error(`${H} ${U} ${IZ.cyan(Y)}`)}let G=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
9
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(G)}progress(Z,$=""){if(!this.enabled||!this.fancy||SZ()||Z<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:Z,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,H)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||SZ())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Z,U)),H!==void 0)this.activeProgressBar.message=H;let z=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,z)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||SZ())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,H="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||SZ())return;gZ.stdout.write(`${"\r".padEnd(gZ.stdout.columns||80)}\r`),this.log(H,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Z,$=!1){if(!this.enabled||!this.fancy||SZ()||!gZ.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Z.current/Z.total*100))),X=Math.round(Z.barLength*Y/100),J=Z.barLength-X,G=IZ.green("\u2501".repeat(X)),U=IZ.gray("\u2501".repeat(J)),H=`[${G}${U}]`,z=`${Y}%`.padStart(4),A=Z.message?` ${Z.message}`:"",W=$||Y===100?IZ.green("\u2713"):IZ.blue("\u25B6"),Q=this.options.showTags!==!1&&this.name?` ${IZ.gray(this.formatTag(this.name))}`:"",L=`\r${W}${Q} ${H} ${z}${A}`,O=gZ.stdout.columns||80,T=" ".repeat(Math.max(0,O-L.replace(this.ANSI_PATTERN,"").length));if(Z.lastRenderedLine=`${L}${T}`,gZ.stdout.write(Z.lastRenderedLine),$)gZ.stdout.write(`
|
|
10
|
-
`)}finishProgressBar(Z,$){if(!this.enabled||!this.fancy||SZ()||!gZ.stdout.isTTY){this.activeProgressBar=null;return}if(Z.current<Z.total)Z.current=Z.total;if($)Z.message=$;this.renderProgressBar(Z,!0),this.activeProgressBar=null}async clear(Z={}){if(SZ()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await H$(this.config.logDirectory),Y=[];for(let X of $){if(!(Z.name?new RegExp(Z.name.replace("*",".*")).test(X):X.startsWith(this.name))||!X.endsWith(".log"))continue;let G=j9(this.config.logDirectory,X);if(Z.before)try{if((await W9(G)).mtime>=Z.before)continue}catch(U){console.error(`Failed to get stats for file ${G}:`,U);continue}Y.push(G)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let X of Y)try{await A$(X),console.warn(`Deleted log file: ${X}`)}catch(J){console.error(`Failed to delete log file ${X}:`,J)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function E$(Z,$){if(Array.isArray($)&&Array.isArray(Z)&&$.length===2&&Z.length===2&&BZ($[0])&&"id"in $[0]&&$[0].id===3&&BZ($[1])&&"id"in $[1]&&$[1].id===4)return $;if(BZ($)&&BZ(Z)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return Z;if(Array.isArray($)&&!Array.isArray(Z))return $;if(Array.isArray($)&&Array.isArray(Z)){if(BZ(Z)&&"arr"in Z&&Array.isArray(Z.arr)&&BZ($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&Z.length>0&&BZ($[0])&&BZ(Z[0])){let X=[...$];for(let J of Z)if(BZ(J)&&"name"in J){if(!X.find((U)=>BZ(U)&&("name"in U)&&U.name===J.name))X.push(J)}else if(BZ(J)&&"path"in J){if(!X.find((U)=>BZ(U)&&("path"in U)&&U.path===J.path))X.push(J)}else if(!X.some((G)=>x$(G,J)))X.push(J);return X}if($.every((X)=>typeof X==="string")&&Z.every((X)=>typeof X==="string")){let X=[...$];for(let J of Z)if(!X.includes(J))X.push(J);return X}return $}if(!BZ($)||!BZ(Z))return $;let Y={...Z};for(let X in $)if(Object.prototype.hasOwnProperty.call($,X)){let J=$[X];if(J===null||J===void 0)continue;else if(BZ(J)&&BZ(Y[X]))Y[X]=E$(Y[X],J);else if(Array.isArray(J)&&Array.isArray(Y[X]))if(J.length>0&&Y[X].length>0&&BZ(J[0])&&BZ(Y[X][0])){let G=[...J];for(let U of Y[X])if(BZ(U)&&"name"in U){if(!G.find((z)=>BZ(z)&&("name"in z)&&z.name===U.name))G.push(U)}else if(BZ(U)&&"path"in U){if(!G.find((z)=>BZ(z)&&("path"in z)&&z.path===U.path))G.push(U)}else if(!G.some((H)=>x$(H,U)))G.push(U);Y[X]=G}else if(J.every((G)=>typeof G==="string")&&Y[X].every((G)=>typeof G==="string")){let G=[...J];for(let U of Y[X])if(!G.includes(U))G.push(U);Y[X]=G}else Y[X]=J;else Y[X]=J}return Y}function e7(Z,$,Y="replace"){if($===null||$===void 0)return Z;if(Array.isArray($))return Y==="replace"?$:E$(Z,$);if(Array.isArray(Z))return Y==="replace"?$:E$(Z,$);if(!BZ($)||!BZ(Z))return $;let X={...Z};for(let J of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,J))continue;let G=$[J],U=X[J];if(G===null||G===void 0)continue;if(Array.isArray(G)||Array.isArray(U))if(Y==="replace")X[J]=G;else X[J]=E$(U,G);else if(BZ(G)&&BZ(U))X[J]=e7(U,G,Y);else X[J]=G}return X}function x$(Z,$){if(Z===$)return!0;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;for(let Y=0;Y<Z.length;Y++)if(!x$(Z[Y],$[Y]))return!1;return!0}if(BZ(Z)&&BZ($)){let Y=Object.keys(Z),X=Object.keys($);if(Y.length!==X.length)return!1;for(let J of Y){if(!Object.prototype.hasOwnProperty.call($,J))return!1;if(!x$(Z[J],$[J]))return!1}return!0}return!1}function BZ(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}async function B$(Z,$,Y="replace"){if(!vY(Z))return null;try{let X=await import(Z),J=X.default||X;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return e7($,J,Y)}catch{return null}}catch{return null}}function gG(Z,$,Y=!1){if(!Z)return $;let X=Z.toUpperCase().replace(/-/g,"_"),J={...$};function G(U,H=[]){let z={...U};for(let[A,W]of Object.entries(U)){let Q=[...H,A],L=(w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase(),O=`${X}_${Q.map(L).join("_")}`,T=`${X}_${Q.map((w)=>w.toUpperCase()).join("_")}`;if(Y)dZ.info(`Checking environment variable ${O} for config ${Z}.${Q.join(".")}`);if(typeof W==="object"&&W!==null&&!Array.isArray(W))z[A]=G(W,Q);else{let w=h9.env[O]||h9.env[T];if(w!==void 0){if(Y)dZ.info(`Using environment variable ${w?O:T} for config ${Z}.${Q.join(".")}`);if(typeof W==="number")z[A]=Number(w);else if(typeof W==="boolean")z[A]=w.toLowerCase()==="true";else if(Array.isArray(W))try{let K=JSON.parse(w);if(Array.isArray(K))z[A]=K;else z[A]=w.split(",").map((B)=>B.trim())}catch{z[A]=w.split(",").map((K)=>K.trim())}else z[A]=w}}}return z}return G(J)}async function pG({name:Z="",alias:$,cwd:Y,configDir:X,defaultConfig:J,verbose:G=!1,checkEnv:U=!0,arrayStrategy:H="replace"}){let z=U&&typeof J==="object"&&J!==null&&!Array.isArray(J)?gG(Z,J,G):J,A=Y||h9.cwd(),W=[".ts",".js",".mjs",".cjs",".json"];if(G)dZ.info(`Loading configuration for "${Z}"${$?` (alias: "${$}")`:""} from ${A}`);let Q=[Z,`.${Z}`].filter(Boolean),L=[`${Z}.config`,`.${Z}.config`].filter(Boolean),O=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],w=Array.from(new Set([A,nZ(A,"config"),nZ(A,".config"),X?nZ(A,X):void 0].filter(Boolean)));for(let K of w){if(G)dZ.info(`Searching for configuration in: ${K}`);let V=[nZ(A,"config"),nZ(A,".config")].concat(X?[nZ(A,X)]:[]).includes(K)?[...Q,...L,...O,...T]:[...L,...Q,...T,...O];for(let F of V)for(let I of W){let E=nZ(K,`${F}${I}`),n=await B$(E,z,H);if(n!==null){if(G)dZ.success(`Configuration loaded from: ${E}`);return n}}}if(Z){let K=nZ(B7(),".config",Z),B=["config",`${Z}.config`];if($)B.push(`${$}.config`);if(G)dZ.info(`Checking user config directory: ${K}`);for(let V of B)for(let F of W){let I=nZ(K,`${V}${F}`),E=await B$(I,z,H);if(E!==null){if(G)dZ.success(`Configuration loaded from user config directory: ${I}`);return E}}}if(Z){let K=nZ(B7(),".config"),B=[`.${Z}.config`];if($)B.push(`.${$}.config`);if(G)dZ.info(`Checking user config directory for dotfile configs: ${K}`);for(let V of B)for(let F of W){let I=nZ(K,`${V}${F}`),E=await B$(I,z,H);if(E!==null){if(G)dZ.success(`Configuration loaded from user config directory dotfile: ${I}`);return E}}}if(Z){let K=B7(),B=[`.${Z}.config`,`.${Z}`];if($)B.push(`.${$}.config`),B.push(`.${$}`);if(G)dZ.info(`Checking user home directory for dotfile configs: ${K}`);for(let V of B)for(let F of W){let I=nZ(K,`${V}${F}`),E=await B$(I,z,H);if(E!==null){if(G)dZ.success(`Configuration loaded from user home directory: ${I}`);return E}}}try{let K=nZ(A,"package.json");if(vY(K)){let B=await import(K),V=B[Z];if(!V&&$){if(V=B[$],V&&G)dZ.success(`Using alias "${$}" configuration from package.json`)}if(V&&typeof V==="object"&&!Array.isArray(V))try{if(G)dZ.success(`Configuration loaded from package.json: ${V===B[Z]?Z:$}`);return e7(z,V,H)}catch(F){if(G)dZ.warn("Failed to merge package.json config:",F)}}}catch(K){if(G)dZ.warn("Failed to load package.json:",K)}if(G)dZ.info(`No configuration found for "${Z}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return z}function dG(Z,$={}){let Y=S$.cwd();while(Y.includes("storage"))Y=s0(Y,"..");let X=s0(Y,Z||"");if($?.relative)return iJ(S$.cwd(),X);return X}async function mG(){try{let Z=await pG({name:"clarity",alias:"logging",defaultConfig:M$,cwd:S$.cwd()});return{...M$,...Z||{}}}catch{return M$}}function xZ(){if(C8.env.NODE_ENV==="test"||C8.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cG(){if(C8.env.NODE_ENV==="test"||C8.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof C8<"u"){let Z=C8.type;if(Z==="renderer"||Z==="worker")return!1;return!!(C8.versions&&(C8.versions.node||C8.versions.bun))}return!1}class fY{async format(Z){let $=await cG(),Y=await this.getMetadata($);return JSON.stringify({timestamp:Z.timestamp.toISOString(),level:Z.level,name:Z.name,message:Z.message,metadata:Y})}async getMetadata(Z){if(Z){let{hostname:$}=await import("os");return{pid:K9.pid,hostname:$(),environment:K9.env.NODE_ENV||"development",platform:K9.platform,version:K9.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:K9.env.NODE_ENV||K9.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class v${name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Z,$={}){this.name=Z,this.config={...d7},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new fY,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??QZ.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},X=$.timestamp!==void 0;if(X)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:X||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),G=this.generateKey();this.currentKeyId=J,this.keys.set(J,G),this.encryptionKeys.set(J,{key:G,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Z){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[Z]>=$[Y]}initializeFingersCrossedConfig(Z){if(!Z.fingersCrossedEnabled&&Z.fingersCrossed)return{...w$,...Z.fingersCrossed};if(!Z.fingersCrossedEnabled)return null;if(!Z.fingersCrossed)return{...w$};return{...w$,...Z.fingersCrossed}}normalizeOptions(Z){let $={format:"json",level:"info",logDirectory:d7.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(Z).filter(([,X])=>X!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!xZ()&&this.config.writeToFile===!0}async writeToFile(Z){let Y=(async()=>{let J,G=0,U=3,H=1000;while(G<U)try{try{try{await UG(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await zG(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let z=this.validateEncryptionConfig()?(await this.encrypt(Z)).encrypted:I8.from(Z);try{if(!W$(this.currentLogFile))await w7(this.currentLogFile,"",{mode:420});if(J=JY(this.currentLogFile,"a",420),GG(J,z,{flag:"a"}),XY(J),J!==void 0)M7(J),J=void 0;if((await _9(this.currentLogFile)).size===0){if(await w7(this.currentLogFile,z,{flag:"w",mode:420}),(await _9(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let W=A;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(G<U-1){let Q=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${U}:`,Q);let L=H*2**G;await new Promise((O)=>setTimeout(O,L)),G++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{M7(J)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(z){if(G===U-1){let W=z,Q=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Q),z}G++;let A=H*2**(G-1);await new Promise((W)=>setTimeout(W,A))}})();this.pendingOperations.push(Y);let X=this.pendingOperations.length-1;try{await Y}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(X,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return V9(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return V9(this.config.logDirectory,`${this.name}.log`);let Z=new Date().toISOString().split("T")[0];return V9(this.config.logDirectory,`${this.name}-${Z}.log`)}setupRotation(){if(xZ())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Z=this.config.rotation,$;switch(Z.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,X=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),X=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,X),this.encryptionKeys.set(Y,{key:X,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,H],[,z])=>z.createdAt.getTime()-H.createdAt.getTime()),G=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,G);if(J.length>U)for(let[H]of J.slice(U))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return I7(16).toString("hex")}generateKey(){return I7(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Z=this.keys.get(this.currentKeyId);if(!Z)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Z,id:this.currentKeyId}}encrypt(Z){let{key:$}=this.getCurrentKey(),Y=I7(16),X=YG("aes-256-gcm",$,Y),J=I8.isBuffer(Z)?Z:I8.from(Z,"utf8"),G=X.update(J),U=X.final(),H=G.length+U.length,z=X.getAuthTag(),A=I8.allocUnsafe(16+H+16);return Y.copy(A,0),G.copy(A,16),U.copy(A,16+G.length),z.copy(A,16+H),{encrypted:A,iv:Y}}async compressData(Z){return new Promise(($,Y)=>{let X=zY(),J=[];X.on("data",(G)=>J.push(G)),X.on("end",()=>$(I8.from(I8.concat(J)))),X.on("error",Y),X.write(Z),X.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Z={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...Z,...$}}return Z}async rotateLog(){if(xZ())return;if(!this.shouldWriteToFile())return;let Z=await _9(this.currentLogFile).catch(()=>null);if(!Z)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&Z.size>=$.maxSize){let Y=this.currentLogFile,X=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await j$(this.config.logDirectory),G=J.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,A)=>{let W=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),U=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${Y}.${U}`;if(await _9(Y).catch(()=>null))try{if(await UY(Y,H),$.compress)try{let z=`${H}.gz`;await this.compressLogFile(H,z),await Q$(H)}catch(z){console.error("Error compressing rotated file:",z)}if(G.length===0&&!J.some((z)=>z.endsWith(".log.1")))try{let z=`${Y}.1`;await w7(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${J}.log`);if(await _9(Y).catch(()=>null))await UY(Y,G)}if(this.currentLogFile=X,$.maxFiles){let G=(await j$(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,H)=>H.localeCompare(U));for(let U of G.slice($.maxFiles))await Q$(V9(this.config.logDirectory,U))}}}async compressLogFile(Z,$){let Y=YY(Z),X=JG($),J=zY();await WG(Y,J,X)}async handleFingersCrossedBuffer(Z,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Z)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let X=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(Z){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[Z]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Z)=>{if(Z instanceof Promise)return Z.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),W$(this.currentLogFile))try{let Z=JY(this.currentLogFile,"r+");XY(Z),M7(Z)}catch(Z){console.error(`Error flushing file: ${Z}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Z of this.pendingOperations)if(typeof Z.cancel==="function")Z.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Z){console.error("Error waiting for pending operations:",Z)}if(!xZ()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await j$(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await Q$(V9(this.config.logDirectory,Y))}catch(X){console.error(`Failed to delete temp file ${Y}:`,X)}}catch(Z){console.error("Error cleaning up temporary files:",Z)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Z){if(!Z)return"";return`${this.tagFormat.prefix}${Z}${this.tagFormat.suffix}`}formatFileTimestamp(Z){return`[${Z.toISOString()}]`}formatConsoleTimestamp(Z){return this.shouldStyleConsole()?KZ.gray(Z.toLocaleTimeString()):Z.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||xZ())return!1;let Z=typeof QZ.env.NO_COLOR<"u",$=QZ.env.FORCE_COLOR==="0";if(Z||$)return!1;return!!(typeof QZ.stderr<"u"&&QZ.stderr.isTTY||typeof QZ.stdout<"u"&&QZ.stdout.isTTY)}formatConsoleMessage(Z){let{timestamp:$,icon:Y="",tag:X="",message:J,level:G,showTimestamp:U=!0}=Z,H=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(U)O.push($);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(X)O.push(X.replace(/[[\]]/g,""));return O.push(J),O.join(" ")}let z=QZ.stdout.columns||120,A="";if(G==="warning"||G==="error")A=`${Y} ${J}`;else if(G==="info"||G==="success")A=`${Y} ${X} ${J}`;else A=`${Y} ${X} ${KZ.cyan(J)}`;if(!U)return A.trim();let W=H(A).trim().length,Q=H($).length,L=Math.max(1,z-2-W-Q);return`${A.trim()}${" ".repeat(L)}${$}`}formatMessage(Z,$){if($.length===1&&Array.isArray($[0]))return Z.replace(/\{(\d+)\}/g,(G,U)=>{let H=Number.parseInt(U,10);return H<$[0].length?String($[0][H]):G});let Y=/%([sdijfo%])/g,X=0,J=Z.replace(Y,(G,U)=>{if(U==="%")return"%";if(X>=$.length)return G;let H=$[X++];switch(U){case"s":return String(H);case"d":case"i":return Number(H).toString();case"j":case"o":return JSON.stringify(H,null,2);default:return G}});if(X<$.length)J+=` ${$.slice(X).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return J}formatMarkdown(Z){if(!Z)return Z;let $=Z;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,X,J)=>{let G=KZ.underline(KZ.blue(X)),U=this.toAbsoluteFilePath(J);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let H=`file://${encodeURI(U)}`,z="\x1B]8;;",A="\x1B\\";return`\x1B]8;;${H}\x1B\\${G}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${J}\x1B\\${G}\x1B]8;;\x1B\\`;return G}),$=$.replace(/`([^`]+)`/g,(Y,X)=>KZ.bgGray(X)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,X)=>KZ.bold(X)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,X)=>KZ.italic(X)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,X)=>KZ.italic(X)),$=$.replace(/~([^~]+)~/g,(Y,X)=>KZ.strikethrough(X)),$}supportsHyperlinks(){if(xZ())return!1;let Z=QZ.env;if(!Z)return!1;if(Z.TERM_PROGRAM==="iTerm.app"||Z.TERM_PROGRAM==="vscode"||Z.TERM_PROGRAM==="WezTerm")return!0;if(Z.WT_SESSION)return!0;if(Z.TERM==="xterm-kitty")return!0;let $=Z.VTE_VERSION?Number.parseInt(Z.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(Z){try{let $=Z;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=QZ.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(HG($)||$.startsWith("./")||$.startsWith("../"))$=AG($);else return null;return W$($)?$:null}catch{return null}}buildOutputTexts(Z){let $=this.shouldStyleConsole()?this.formatMarkdown(Z):Z,Y=Z.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(Z,$,...Y){let X=new Date,J=this.formatConsoleTimestamp(X),G=this.formatFileTimestamp(X),U,H;if($ instanceof Error)U=$.message,H=$.stack;else U=this.formatMessage($,Y);let{consoleText:z,fileText:A}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let Q=this.options.showIcons===!1?"":sY[Z],L=this.options.showTags!==!1&&this.name?KZ.gray(this.formatTag(this.name)):"",O;switch(Z){case"debug":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:L,message:KZ.gray(z),level:Z}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:L,message:z,level:Z}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:L,message:KZ.green(z),level:Z}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:L,message:z,level:Z}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:L,message:z,level:Z}),console.error(O),H){let T=H.split(`
|
|
11
|
-
`);for(let w of T)if(w.trim()&&!w.includes(U))console.error(this.formatConsoleMessage({timestamp:J,message:KZ.gray(` ${w}`),level:Z,showTimestamp:!1}))}break}}else if(!xZ()){if(console.error(`${G} ${this.environment}.${Z.toUpperCase()}: ${U}`),H)console.error(H)}if(!this.shouldLog(Z))return;let W=`${G} ${this.environment}.${Z.toUpperCase()}: ${A}
|
|
12
|
-
`;if(H)W+=`${H}
|
|
13
|
-
`;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress(Z,$=""){let Y={update:(H,z)=>{},finish:(H)=>{},interrupt:(H,z)=>{}};if(!this.enabled)return Y;let X=30;if(this.activeProgressBar={total:Math.max(1,Z||1),current:0,message:$||"",barLength:X,lastRenderedLine:""},this.shouldStyleConsole()&&!xZ()&&QZ.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(H,z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,H),this.activeProgressBar.total),z!==void 0)this.activeProgressBar.message=z;if(this.shouldStyleConsole()&&!xZ()&&QZ.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(H)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,H)},interrupt:(H,z="info")=>{if(!xZ()&&QZ.stdout.isTTY)QZ.stdout.write(`
|
|
14
|
-
`);if(this[z==="warning"?"warn":z](H),this.activeProgressBar&&this.shouldStyleConsole()&&!xZ()&&QZ.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Z){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?KZ.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:this.options.showIcons===!1?"":KZ.blue("\u25D0"),tag:Y,message:`${KZ.cyan(Z)}...`}))}return async(Y)=>{if(!this.enabled)return;let X=performance.now(),J=Math.round(X-$),G=`${Z} completed in ${J}ms`,U=new Date,H=this.formatConsoleTimestamp(U),A=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${G}`;if(Y)A+=` ${JSON.stringify(Y)}`;if(A+=`
|
|
15
|
-
`,A=A.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?KZ.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:H,icon:this.options.showIcons===!1?"":KZ.green("\u2713"),tag:W,message:`${G}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!xZ())console.error(A.trim());if(this.shouldWriteToFile())await this.writeToFile(A)}}async debug(Z,...$){await this.log("debug",Z,...$)}async info(Z,...$){await this.log("info",Z,...$)}async success(Z,...$){await this.log("success",Z,...$)}async warn(Z,...$){await this.log("warning",Z,...$)}async error(Z,...$){await this.log("error",Z,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Z=this.config.rotation,{encrypt:$}=Z;return!!$}async only(Z){if(!this.enabled)return;return await Z()}isEnabled(){return this.enabled}setEnabled(Z){this.enabled=Z}extend(Z){let $=`${this.name}:${Z}`,Y=new v$($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(xZ())throw Error("createReadStream is not supported in browser environments");if(!W$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return YY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Z){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let X=I8.isBuffer(Z)?Z:I8.from(Z,"base64"),J=X.subarray(0,16),G=X.subarray(X.length-16),U=X.subarray(16,X.length-16),H=XG("aes-256-gcm",Y,J);H.setAuthTag(G);let z=H.update(U),A=H.final(),W=z.length+A.length,Q=I8.allocUnsafe(W);return z.copy(Q,0),A.copy(Q,z.length),Q.toString("utf8")}catch(X){throw Error(`Decryption failed: ${X instanceof Error?X.message:String(X)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return xZ()}isServerMode(){return!xZ()}setTestEncryptionKey(Z,$){this.currentKeyId=Z,this.keys.set(Z,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Z){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),X=this.formatFileTimestamp($),{consoleText:J,fileText:G}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let H=J.split(`
|
|
16
|
-
`),z=Math.max(...H.map((L)=>L.length))+2,A=`\u250C${"\u2500".repeat(z)}\u2510`,W=`\u2514${"\u2500".repeat(z)}\u2518`,Q=H.map((L)=>{return this.formatConsoleMessage({timestamp:Y,message:KZ.cyan(L),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:KZ.cyan(A),showTimestamp:!1})),Q.forEach((L)=>console.error(L)),console.error(this.formatConsoleMessage({timestamp:Y,message:KZ.cyan(W),showTimestamp:!1}))}else if(!xZ())console.error(`${X} ${this.environment}.INFO: [BOX] ${G}`);let U=`${X} ${this.environment}.INFO: [BOX] ${G}
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(Z){if(xZ())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${KZ.cyan("?")} ${Z} (y/n) `);let Y=(X)=>{let J=X.toString().trim().toLowerCase();QZ.stdin.removeListener("data",Y);try{if(typeof QZ.stdin.setRawMode==="function")QZ.stdin.setRawMode(!1)}catch{}QZ.stdin.pause(),console.error(""),$(J==="y"||J==="yes")};try{if(typeof QZ.stdin.setRawMode==="function")QZ.stdin.setRawMode(!0)}catch{}QZ.stdin.resume(),QZ.stdin.once("data",Y)})}setFancy(Z){this.fancy=Z}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Z,...$){if(!this.enabled)return;let Y=Z;if($&&$.length>0){let z=/%([sdijfo%])/g,A=0;if(Y=Z.replace(z,(W,Q)=>{if(Q==="%")return"%";if(A>=$.length)return W;let L=$[A++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return W}}),A<$.length)Y+=` ${$.slice(A).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:X,fileText:J}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?KZ.gray(this.formatTag(this.name)):"",A=this.options.showIcons===!1?"":`${KZ.blue("\u25D0")} `;console.error(`${A}${z} ${KZ.cyan(X)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${J}
|
|
18
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(H)}renderProgressBar(Z,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!QZ.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Z.current/Z.total*100))),X=Math.round(Z.barLength*Y/100),J=Z.barLength-X,G=KZ.green("\u2501".repeat(X)),U=KZ.gray("\u2501".repeat(J)),H=`[${G}${U}]`,z=`${Y}%`.padStart(4),A=Z.message?` ${Z.message}`:"",W=this.options.showIcons===!1?"":$||Y===100?KZ.green("\u2713"):KZ.blue("\u25B6"),Q=this.options.showTags!==!1&&this.name?` ${KZ.gray(this.formatTag(this.name))}`:"",L=`\r${W}${Q} ${H} ${z}${A}`,O=QZ.stdout.columns||80,T=" ".repeat(Math.max(0,O-L.replace(this.ANSI_PATTERN,"").length));if(Z.lastRenderedLine=`${L}${T}`,QZ.stdout.write(Z.lastRenderedLine),$)QZ.stdout.write(`
|
|
19
|
-
`)}finishProgressBar(Z,$){if(!this.enabled||!this.fancy||xZ()||!QZ.stdout.isTTY){this.activeProgressBar=null;return}if(Z.current<Z.total)Z.current=Z.total;if($)Z.message=$;this.renderProgressBar(Z,!0),this.activeProgressBar=null}async clear(Z={}){if(xZ()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await j$(this.config.logDirectory),Y=[];for(let X of $){if(!(Z.name?new RegExp(Z.name.replace("*",".*")).test(X):X.startsWith(this.name))||!X.endsWith(".log"))continue;let G=V9(this.config.logDirectory,X);if(Z.before)try{if((await _9(G)).mtime>=Z.before)continue}catch(U){console.error(`Failed to get stats for file ${G}:`,U);continue}Y.push(G)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let X of Y)try{await Q$(X),console.warn(`Deleted log file: ${X}`)}catch(J){console.error(`Failed to delete log file ${X}:`,J)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function gY(Z,$={}){let{maxRetries:Y=3,retryDelay:X=1000,isRetryable:J=()=>!0,fallback:G}=$,U=Error("Unknown error occurred");for(let H=0;H<=Y;H++)try{return await Z()}catch(z){if(U=z instanceof Error?z:Error(String(z)),H===Y||!J(U))break;if(X>0)await new Promise((A)=>setTimeout(A,X))}if(G!==void 0)return G;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function pY(Z){return Z instanceof eZ}function uG(Z){return Z instanceof y$}function nG(Z){if(pY(Z))return Z.code==="FILE_SYSTEM_ERROR"||Z.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>Z.message.toLowerCase().includes(Y.toLowerCase()))}class d${defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Z,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(Z.toLowerCase()),parse:(Z)=>{let $=Z.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(Z,$)=>$==="number"||!Number.isNaN(Number(Z))&&!Number.isNaN(Number.parseFloat(Z)),parse:(Z)=>{let $=Number(Z);if(Number.isNaN($))throw TypeError(`Cannot parse "${Z}" as number`);return $}},{name:"array",canParse:(Z,$)=>$==="array"||Z.startsWith("[")||Z.includes(","),parse:(Z)=>{try{let $=JSON.parse(Z);if(Array.isArray($))return $}catch{}return Z.split(",").map(($)=>$.trim())}},{name:"json",canParse:(Z,$)=>$==="object"||(Z.startsWith("{")&&Z.endsWith("}")||Z.startsWith("[")&&Z.endsWith("]")),parse:(Z)=>{try{return JSON.parse(Z)}catch($){throw Error(`Cannot parse "${Z}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(Z,$,Y={}){let{prefix:X,useCamelCase:J=!0,useBackwardCompatibility:G=!0,customParsers:U={},verbose:H=!1,trackPerformance:z=!0}=Y,A=async()=>{if(!Z)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let W=X||this.generateEnvPrefix(Z),Q={...$};return this.processObject(Q,[],W,{useCamelCase:J,useBackwardCompatibility:G,customParsers:U,verbose:H,configName:Z}),{config:Q,source:{type:"environment",priority:50,timestamp:new Date}}};if(z)return g9.track("applyEnvironmentVariables",A,{configName:Z});return A()}generateEnvPrefix(Z){return Z.toUpperCase().replace(/-/g,"_")}formatEnvKey(Z,$){if(!$)return Z.toUpperCase();return Z.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Z,$,Y,X){for(let[J,G]of Object.entries(Z)){let U=[...$,J],H=U.map((W)=>this.formatEnvKey(W,X.useCamelCase)),z=`${Y}_${H.join("_")}`,A=X.useBackwardCompatibility?`${Y}_${U.map((W)=>W.toUpperCase()).join("_")}`:null;if(X.verbose);if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.processObject(G,U,Y,X);else{let W=_$.env[z]||(A?_$.env[A]:void 0);if(W!==void 0){if(X.verbose){let Q=_$.env[z]?z:A}try{Z[J]=this.parseEnvironmentValue(W,typeof G,z,X.customParsers,X.configName)}catch(Q){if(Q instanceof h$)throw Q;throw b8.envVar(z,W,typeof G,X.configName)}}}}}parseEnvironmentValue(Z,$,Y,X,J){for(let[G,U]of Object.entries(X))try{return U(Z)}catch{continue}for(let G of this.defaultParsers)if(G.canParse(Z,$))try{return G.parse(Z)}catch{throw b8.envVar(Y,Z,`${$} (via ${G.name} parser)`,J)}return Z}getEnvironmentVariables(Z){let $={},Y=Z.toUpperCase();for(let[X,J]of Object.entries(_$.env))if(X.startsWith(Y)&&J!==void 0)$[X]=J;return $}validateEnvironmentVariable(Z,$,Y){let X=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Z))X.push(`Environment variable key "${Z}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Z,$,Y,{})}catch(J){X.push(`Cannot parse value "${$}" as ${Y}: ${J}`)}return{isValid:X.length===0,errors:X}}generateEnvVarDocs(Z,$,Y={}){let{prefix:X,format:J="text"}=Y,G=X||this.generateEnvPrefix(Z),U=[];switch(this.extractEnvVarInfo($,[],G,U),J){case"markdown":return this.formatAsMarkdown(U,Z);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Z)}}extractEnvVarInfo(Z,$,Y,X){for(let[J,G]of Object.entries(Z)){let U=[...$,J],H=`${Y}_${U.map((z)=>this.formatEnvKey(z,!0)).join("_")}`;if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.extractEnvVarInfo(G,U,Y,X);else X.push({key:H,type:Array.isArray(G)?"array":typeof G,description:`Configuration for ${U.join(".")}`,example:this.generateExample(G)})}}generateExample(Z){if(Array.isArray(Z))return JSON.stringify(Z);if(typeof Z==="object"&&Z!==null)return JSON.stringify(Z);return String(Z)}formatAsText(Z,$){let Y=`Environment Variables for ${$}:
|
|
20
|
-
|
|
21
|
-
`;for(let X of Z)Y+=`${X.key}
|
|
22
|
-
`,Y+=` Type: ${X.type}
|
|
23
|
-
`,Y+=` Description: ${X.description}
|
|
24
|
-
`,Y+=` Example: ${X.example}
|
|
25
|
-
|
|
26
|
-
`;return Y}formatAsMarkdown(Z,$){let Y=`# Environment Variables for ${$}
|
|
27
|
-
|
|
28
|
-
`;Y+=`| Variable | Type | Description | Example |
|
|
29
|
-
`,Y+=`|----------|------|-------------|----------|
|
|
30
|
-
`;for(let X of Z)Y+=`| \`${X.key}\` | ${X.type} | ${X.description} | \`${X.example}\` |
|
|
31
|
-
`;return Y}}function iG(Z,$){let Y=nY("process");if(typeof Y>"u"||!Y.env)return $;let X=Y.env[Z];return X!==void 0?X:$}function dY(Z,$,Y={}){return mY(Z,$,Y,new WeakMap)}function mY(Z,$,Y,X){let{arrayMergeMode:J="replace",skipNullish:G=!1,customMerger:U}=Y;if($===null||$===void 0)return G?Z:$;if(U){let H=U(Z,$);if(H!==void 0)return H}if(Array.isArray($)||Array.isArray(Z))return cY(Z,$,J,X);if(!X8($)||!X8(Z))return $;return rG(Z,$,Y,X)}function cY(Z,$,Y,X){if(Array.isArray($)&&!Array.isArray(Z))return $;if(Array.isArray(Z)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(Z))switch(Y){case"replace":return $;case"concat":return lG(Z,$);case"smart":return sG(Z,$,X);default:return $}return $}function lG(Z,$){let Y=[...$];for(let X of Z)if(!Y.some((J)=>g7(J,X)))Y.push(X);return Y}function sG(Z,$,Y){if($.length===0)return Z;if(Z.length===0)return $;if(X8($[0])&&X8(Z[0]))return oG(Z,$,Y);if($.every((X)=>typeof X==="string")&&Z.every((X)=>typeof X==="string")){let X=[...$];for(let J of Z)if(!X.includes(J))X.push(J);return X}return $}function oG(Z,$,Y){let X=[...$];for(let J of Z){if(!X8(J)){X.push(J);continue}let G=["id","name","key","path","type"],U=!1;for(let H of G)if(H in J){if(X.find((A)=>X8(A)&&(H in A)&&A[H]===J[H])){U=!0;break}}if(!U)X.push(J)}return X}function rG(Z,$,Y,X){let J=$;if(X8(J)&&X.has(J))return X.get(J);let G={...Z};if(X8(J))X.set(J,G);for(let U in J){if(!Object.prototype.hasOwnProperty.call(J,U))continue;let H=J[U],z=G[U];if(Y.skipNullish&&(H===null||H===void 0))continue;if(H===null||H===void 0){G[U]=H;continue}if(X8(H)&&X8(z))G[U]=mY(z,H,Y,X);else if(Array.isArray(H)||Array.isArray(z))G[U]=cY(z,H,Y.arrayMergeMode||"smart",X);else G[U]=H}return G}function Z0(Z,$,Y="replace"){return dY(Z,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function g7(Z,$){if(Z===$)return!0;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;for(let Y=0;Y<Z.length;Y++)if(!g7(Z[Y],$[Y]))return!1;return!0}if(X8(Z)&&X8($)){let Y=Object.keys(Z),X=Object.keys($);if(Y.length!==X.length)return!1;for(let J of Y){if(!Object.prototype.hasOwnProperty.call($,J))return!1;if(!g7(Z[J],$[J]))return!1}return!0}return!1}function X8(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}class m${extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Z,$,Y={}){let{arrayStrategy:X="replace",useCache:J=!0,cacheTtl:G,trackPerformance:U=!0,verbose:H=!1}=Y;if(J){let A=R9.getWithFileCheck("file",Z);if(A){if(H)console.log(`Configuration loaded from cache: ${Z}`);return A}}let z=async()=>{if(!V$(Z))return null;try{let A=`?t=${Date.now()}`,W=await import(Z+A),Q=W.default||W,L="default"in W,O=Object.keys(W).length>0;if(!L&&!O)throw new b9(Z,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new b9(Z,Error("Configuration must export a valid object"),"unknown");let K={config:Z0($,Q,X),source:{type:"file",path:Z,priority:100,timestamp:new Date}};if(J)R9.setWithFileCheck("file",K,Z,G);return K}catch(A){throw A instanceof Error?b8.configLoad(Z,A):b8.configLoad(Z,Error(String(A)))}};if(U)return g9.track("loadFromPath",z,{path:Z});return z()}async tryLoadFromPaths(Z,$,Y={}){for(let X of Z)try{let J=await this.loadFromPath(X,$,Y);if(J)return J}catch(J){if(J instanceof Error&&J.name==="ConfigLoadError")throw J;if(Y.verbose)console.warn(`Failed to load config from ${X}:`,J)}return null}generateConfigPaths(Z,$,Y){let X=this.generateNamePatterns(Z,Y),J=[];for(let G of X)for(let U of this.extensions)J.push(C7($,`${G}${U}`));return J}generateNamePatterns(Z,$){let Y=[];if(Y.push("config",".config"),Z)Y.push(Z,`.${Z}.config`,`${Z}.config`,`.${Z}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),Z)Y.push(`${Z}.${$}.config`,`.${Z}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(Z){return gY(async()=>{return V$(Z)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Z,$,Y){let X=[];if(!V$(Z))return X;if($||Y){let J=this.generateNamePatterns($||"",Y);for(let G of J)for(let U of this.extensions){let H=C7(Z,`${G}${U}`);if(await this.checkFileAccess(H))X.push(H)}}else try{let{readdirSync:J}=await import("fs"),G=J(Z);for(let U of G)if(this.looksLikeConfigFile(U)){let H=C7(Z,U);if(await this.checkFileAccess(H))X.push(H)}}catch{return[]}return X}looksLikeConfigFile(Z){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((Y)=>Y.test(Z))}async validateConfigFile(Z){let $=[];try{if(!V$(Z))return $.push("Configuration file does not exist"),$;let Y=await import(Z),X=Y.default||Y;if(X===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof X!=="object"||X===null)$.push("Configuration must be an object");else if(Array.isArray(X))$.push("Configuration cannot be an array at the root level");if(Z.endsWith(".json"))try{let{readFileSync:J}=await import("fs"),G=J(Z,"utf8");JSON.parse(G)}catch(J){$.push(`Invalid JSON syntax: ${J}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(Z){try{let{statSync:$}=await import("fs");return $(Z).mtime}catch{return null}}async preloadConfigurations(Z,$={}){let Y=new Map;return await Promise.allSettled(Z.map(async(X)=>{try{let J=await this.loadFromPath(X,{},$);if(J)Y.set(X,J.config)}catch(J){if($.verbose)console.warn(`Failed to preload ${X}:`,J)}})),Y}}class $0{async validateConfiguration(Z,$,Y={}){let{stopOnFirstError:X=!1,validateRequired:J=!0,validateTypes:G=!0,customRules:U=[],trackPerformance:H=!0,verbose:z=!1}=Y,A=async()=>{let W=[],Q=[],L={stopOnFirstError:X,validateRequired:J,validateTypes:G,customRules:U,trackPerformance:H,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(Z,$,L);else if(Array.isArray($))return this.validateWithRules(Z,[...$,...U],L);else return this.validateWithJSONSchema(Z,$,L)}catch(O){return W.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:W,warnings:Q}}};if(H)return await g9.track("validateConfiguration",A);return A()}async validateWithSchemaFile(Z,$,Y){try{if(!jG($))throw new f9($,[{path:"",message:"Schema file does not exist"}]);let X=await import($),J=X.default||X;if(Array.isArray(J))return this.validateWithRules(Z,J,Y);else return this.validateWithJSONSchema(Z,J,Y)}catch(X){throw new f9($,[{path:"",message:`Failed to load schema: ${X}`}])}}validateWithJSONSchema(Z,$,Y){let X=[],J=[];return this.validateObjectAgainstSchema(Z,$,"",X,J,Y),{isValid:X.length===0,errors:X,warnings:J}}validateObjectAgainstSchema(Z,$,Y,X,J,G){if(G.validateTypes&&$.type){let U=Array.isArray(Z)?"array":typeof Z,H=Array.isArray($.type)?$.type:[$.type];if(!H.includes(U)){if(X.push({path:Y,message:`Expected type ${H.join(" or ")}, got ${U}`,expected:H.join(" or "),actual:U,rule:"type"}),G.stopOnFirstError)return}}if($.enum&&!$.enum.includes(Z)){if(X.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:Z,rule:"enum"}),G.stopOnFirstError)return}if(typeof Z==="string"){if($.minLength!==void 0&&Z.length<$.minLength)X.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:Z.length,rule:"minLength"});if($.maxLength!==void 0&&Z.length>$.maxLength)X.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:Z.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(Z))X.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:Z,rule:"pattern"})}}if(typeof Z==="number"){if($.minimum!==void 0&&Z<$.minimum)X.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:Z,rule:"minimum"});if($.maximum!==void 0&&Z>$.maximum)X.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:Z,rule:"maximum"})}if(Array.isArray(Z)&&$.items)for(let U=0;U<Z.length;U++){let H=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Z[U],$.items,H,X,J,G),G.stopOnFirstError&&X.length>0)return}if(Z&&typeof Z==="object"&&!Array.isArray(Z)){let U=Z;if(G.validateRequired&&$.required){for(let H of $.required)if(!(H in U)){if(X.push({path:Y?`${Y}.${H}`:H,message:`Missing required property '${H}'`,expected:"required",rule:"required"}),G.stopOnFirstError)return}}if($.properties){for(let[H,z]of Object.entries($.properties))if(H in U){let A=Y?`${Y}.${H}`:H;if(this.validateObjectAgainstSchema(U[H],z,A,X,J,G),G.stopOnFirstError&&X.length>0)return}}if($.additionalProperties===!1){let H=new Set(Object.keys($.properties||{}));for(let z of Object.keys(U))if(!H.has(z))J.push({path:Y?`${Y}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Z,$,Y){let X=[],J=[];for(let G of $)try{let U=this.getValueByPath(Z,G.path),H=this.validateWithRule(U,G,G.path);if(X.push(...H),Y.stopOnFirstError&&X.length>0)break}catch(U){X.push({path:G.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:X.length===0,errors:X,warnings:J}}validateWithRule(Z,$,Y){let X=[];if($.required&&(Z===void 0||Z===null))return X.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),X;if(Z===void 0||Z===null)return X;if($.type){let J=Array.isArray(Z)?"array":typeof Z;if(J!==$.type)X.push({path:Y,message:$.message||`Expected type ${$.type}, got ${J}`,expected:$.type,actual:J,rule:"type"})}if($.min!==void 0){let J=Array.isArray(Z)?Z.length:typeof Z==="string"?Z.length:typeof Z==="number"?Z:0;if(J<$.min)X.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:J,rule:"min"})}if($.max!==void 0){let J=Array.isArray(Z)?Z.length:typeof Z==="string"?Z.length:typeof Z==="number"?Z:0;if(J>$.max)X.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:J,rule:"max"})}if($.pattern&&typeof Z==="string"){if(!$.pattern.test(Z))X.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:Z,rule:"pattern"})}if($.enum&&!$.enum.includes(Z))X.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:Z,rule:"enum"});if($.validator){let J=$.validator(Z);if(J)X.push({path:Y,message:$.message||J,rule:"custom"})}return X}getValueByPath(Z,$){if(!$)return Z;let Y=$.split("."),X=Z;for(let J of Y)if(X&&typeof X==="object"&&J in X)X=X[J];else return;return X}generateRulesFromInterface(Z){let $=[],Y=Z.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let X of Y){let[,J,G,U]=X;$.push({path:J,required:!G,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(Z){switch(Z.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:rY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Y0{fileLoader=new m$;envProcessor=new d$;validator=new $0;async loadConfig(Z){let $=Date.now(),{cache:Y,performance:X,schema:J,validate:G,...U}=Z;try{if(Y?.enabled){let z=this.checkCache(U.name||"",U);if(z)return z}let H;try{H=await this.loadConfigurationStrategies(U,!0,Y)}catch(z){let A=U.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(A)throw z;H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let W=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),Q=!W&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),L=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(A&&(L||W))throw z;if(Q&&(!A||!L))H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!A)H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(J||G)await this.validateConfiguration(H.config,J,G,U.name);if(Y?.enabled&&H)this.cacheResult(U.name||"",H,Y,U);if(X?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(X.onMetrics)X.onMetrics(z);if(X.slowThreshold&&z.duration>X.slowThreshold)H8.warn(`Slow configuration loading detected: ${z.duration}ms for ${U.name}`);H.metrics=z}return H}catch(H){let z=Date.now()-$;throw H8.error(`Configuration loading failed after ${z}ms:`,[H instanceof Error?H:Error(String(H))]),H}}async loadConfigurationStrategies(Z,$=!1,Y){let{name:X="",alias:J,cwd:G,configDir:U,defaultConfig:H,checkEnv:z=!0,arrayStrategy:A="replace",verbose:W=!1}=Z,Q=G||r8.cwd(),L=[],O=await this.loadLocalConfiguration(X,J,Q,U,H,A,W,z,Y);if(O)return L.push(...this.getLocalSearchPaths(X,J,Q,U)),this.finalizeResult(O,L,z,X,W);let T=await this.loadHomeConfiguration(X,J,H,A,W,z);if(T)return L.push(...this.getHomeSearchPaths(X,J)),this.finalizeResult(T,L,z,X,W);let w=await this.loadPackageJsonConfiguration(X,J,Q,H,A,W,z);if(w)return L.push(iZ(Q,"package.json")),this.finalizeResult(w,L,z,X,W);if(L.push(...this.getAllSearchPaths(X,J,Q,U)),$)throw b8.configNotFound(X,L,J);return{...await this.applyEnvironmentVariables(X,H,z,W),warnings:[`No configuration file found for "${X}"${J?` or alias "${J}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Z,$,Y,X,J,G,U,H,z){let A=H?y9(Z,J,U):J,W=this.getLocalDirectories(Y,X);for(let Q of W){if(U)H8.info(`Searching for configuration in: ${Q}`);let L=this.fileLoader.generateConfigPaths(Z,Q,$),O=await this.fileLoader.tryLoadFromPaths(L,A,{arrayStrategy:G,verbose:U,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(O){if(U)H8.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration(Z,$,Y,X,J,G){if(!Z)return null;let U=G?y9(Z,Y,J):Y,H=[iZ(A9(),".config",Z),iZ(A9(),".config"),A9()];for(let z of H){if(J)H8.info(`Checking home directory: ${z}`);let A=this.fileLoader.generateConfigPaths(Z,z,$),W=await this.fileLoader.tryLoadFromPaths(A,U,{arrayStrategy:X,verbose:J});if(W){if(J)H8.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration(Z,$,Y,X,J,G,U){let H=U?y9(Z,X,G):X;try{let z=iZ(Y,"package.json");if(!b7(z))return null;let A=await import(z),W=A[Z],Q=Z;if(!W&&$)W=A[$],Q=$;if(W&&typeof W==="object"&&!Array.isArray(W)){if(G)H8.success(`Configuration loaded from package.json: ${Q}`);return{config:Z0(H,W,J),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(G)H8.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(Z,$,Y,X){if(!Y||!Z||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:y9(Z,$,X),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Z,$,Y,X,J){return{config:Z.config,source:Z.source,path:Z.source.path}}async validateConfiguration(Z,$,Y,X){let J=[];if(Y){let G=Y(Z);if(G)J.push(...G)}if($){let G=await this.validator.validateConfiguration(Z,$);if(!G.isValid)J.push(...G.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(J.length>0)throw b8.configValidation(X||"unknown",J,X)}checkCache(Z,$){let Y=this.generateCacheKey(Z,$);return R9.get(Y)||null}cacheResult(Z,$,Y,X){let J=this.generateCacheKey(Z,X);R9.set(J,$,void 0,Y.ttl)}generateCacheKey(Z,$){let Y=[Z];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(Z,$){return Array.from(new Set([Z,iZ(Z,"config"),iZ(Z,".config"),$?iZ(Z,$):void 0].filter(Boolean)))}getAllSearchPaths(Z,$,Y,X){let J=[];return J.push(...this.getLocalSearchPaths(Z,$,Y,X)),J.push(...this.getHomeSearchPaths(Z,$)),J.push(iZ(Y,"package.json")),J}getLocalSearchPaths(Z,$,Y,X){let J=this.getLocalDirectories(Y,X),G=[];for(let U of J)G.push(...this.fileLoader.generateConfigPaths(Z,U,$));return G}getHomeSearchPaths(Z,$){if(!Z)return[];let Y=[iZ(A9(),".config",Z),iZ(A9(),".config"),A9()],X=[];for(let J of Y)X.push(...this.fileLoader.generateConfigPaths(Z,J,$));return X}async loadConfigWithResult(Z){return this.loadConfig(Z)}}function LY(Z){let Y=!(Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"))&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")),X=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");return Y||X}async function tG(Z){return N8.loadConfig({...Z,__strictErrorHandling:!0})}async function uY(Z){let $="defaultConfig"in Z&&Z.defaultConfig!==void 0?Z.defaultConfig:{},Y="cache"in Z||"performance"in Z||"schema"in Z||"validate"in Z;try{let X;if(Y)X=await N8.loadConfig(Z);else X=await N8.loadConfig({...Z,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return X?.config??$}catch(X){let J=X instanceof Error?X.name:"UnknownError",G=X instanceof Error?X.message:String(X);if(!(J==="ConfigNotFoundError"||J==="ConfigLoadError"||J==="ConfigValidationError"||G.includes("config"))&&Z.verbose)H8.warn("Unexpected error loading config, using defaults:",[X instanceof Error?X:Error(String(X))]);let H=Y?{...Z,defaultConfig:$}:{...Z,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Z?Z.checkEnv!==!1:!0)return(await N8.applyEnvironmentVariables(H.name||"",$,!0,H.verbose||!1))?.config??$;return $}}async function aG(Z={defaultConfig:{}}){if(typeof Z==="string"){let{cwd:$}=await import("process");try{return(await N8.loadConfig({name:Z,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&LY(Y)))return(await N8.applyEnvironmentVariables(Z,{},!0,!1)).config;throw Y}}try{return(await N8.loadConfig({...Z,cwd:Z.cwd||r8.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&LY($)))return(await N8.applyEnvironmentVariables(Z.name||"",Z.defaultConfig||{},Z.checkEnv!==!1,Z.verbose||!1)).config;throw $}}async function eG(Z,$,Y="replace"){let X=new m$;try{let J=await X.loadFromPath(Z,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return J?J.config:null}catch{return null}}function y9(Z,$,Y=!1){let X=new d$,J=Z.toUpperCase().replace(/[^A-Z0-9]/g,"_");function G(U,H=[]){let z={...U};for(let[A,W]of Object.entries(U)){let Q=[...H,A],L=[`${J}_${Q.join("_").toUpperCase()}`,`${J}_${Q.map((w)=>w.toUpperCase()).join("")}`,`${J}_${Q.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,T;for(let w of L)if(O=r8.env[w],O!==void 0){T=w;break}if(O!==void 0&&T)if(typeof W==="boolean")z[A]=["true","1","yes"].includes(O.toLowerCase());else if(typeof W==="number"){let w=Number(O);if(!Number.isNaN(w))z[A]=w}else if(Array.isArray(W))try{z[A]=JSON.parse(O)}catch{z[A]=O.split(",").map((w)=>w.trim())}else z[A]=O;else if(W&&typeof W==="object"&&!Array.isArray(W))z[A]=G(W,Q)}return z}return G($)}function Z5(Z){let $=iZ(r8.cwd(),Z.configDir),Y=iZ(r8.cwd(),Z.generatedDir),X=iZ(Y,"config-types.ts");if(!b7(l0(X)))mJ(l0(X),{recursive:!0,mode:511});let J=b7($)?cJ($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],G=`// Generated by bunfig v${P5}
|
|
32
|
-
export type ConfigNames = ${J.length?`'${J.join("' | '")}'`:"string"}
|
|
33
|
-
`;uJ(X,G,{mode:438})}function $5(Z){let $=null,Y=null,X=()=>{if(!Y)Y=uY(Z).then((G)=>{return $=G,G},(G)=>{let U="defaultConfig"in Z?Z.defaultConfig:{};if($=U,"verbose"in Z&&Z.verbose)H8.warn("Config loading failed, using defaults:",[G instanceof Error?G:Error(String(G))]);return U});return Y},J="defaultConfig"in Z?Z.defaultConfig:{};return $=J,X(),new Proxy({},{get(G,U){if($)return $[U];let H=J[U];return X(),H},has(G,U){return U in($||J)},ownKeys(){return Object.keys($||J)},getOwnPropertyDescriptor(G,U){return Object.getOwnPropertyDescriptor($||J,U)},set(G,U,H){if(!$)$={...J};return $[U]=H,!0}})}function Y5(Z){let $=HY(VG.cwd(),Z?.configDir||"./config");function Y(){if(!QG($))return[];let J=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),G=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=_G($).filter((z)=>J.has(S7(z))).map((z)=>({base:z.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:z})),H=new Map;for(let{base:z,file:A}of U){let W=S7(A).toLowerCase(),Q=H.get(z);if(!Q){H.set(z,A);continue}let L=S7(Q).toLowerCase();if(G.indexOf(W)<G.indexOf(L))H.set(z,A)}return Array.from(H.entries()).map(([z,A])=>({base:z,file:A})).sort((z,A)=>z.base.localeCompare(A.base))}function X(){let J=Y(),G=J.map((A)=>A.base),U=G.length?G.map((A)=>`'${A}'`).join(" | "):"string",H=J.length?`{
|
|
34
|
-
${J.map((A)=>{let W=HY($,A.file).replace(/\\/g,"/");return` '${A.base}': typeof import('${W}').default`}).join(`,
|
|
35
|
-
`)}
|
|
36
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
37
|
-
export type ConfigByName = ${H}
|
|
38
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
|
-
export type ConfigOf = Config
|
|
40
|
-
`}return{name:"bunfig-plugin",setup(J){J.onResolve({filter:/^virtual:bunfig-types$/},(G)=>{return{path:G.path,namespace:"bunfig-virtual"}}),J.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:X(),loader:"ts"}})}}}function q5(Z,$={}){let Y=T$.cwd();while(Y.includes("storage"))Y=AY(Y,"..");let X=AY(Y,Z||"");if($?.relative)return LG(T$.cwd(),X);return X}function yZ(){if(S8.env.NODE_ENV==="test"||S8.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function x5(){if(S8.env.NODE_ENV==="test"||S8.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof S8<"u"){let Z=S8.type;if(Z==="renderer"||Z==="worker")return!1;return!!(S8.versions&&(S8.versions.node||S8.versions.bun))}return!1}class ZX{async format(Z){let $=await x5(),Y=await this.getMetadata($);return JSON.stringify({timestamp:Z.timestamp.toISOString(),level:Z.level,name:Z.name,message:Z.message,metadata:Y})}async getMetadata(Z){if(Z){let{hostname:$}=await import("os");return{pid:B9.pid,hostname:$(),environment:B9.env.NODE_ENV||"development",platform:B9.platform,version:B9.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:B9.env.NODE_ENV||B9.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class c${name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Z,$={}){this.name=Z,this.config={...b$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new ZX,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??_Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},X=$.timestamp!==void 0;if(X)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:X||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),G=this.generateKey();this.currentKeyId=J,this.keys.set(J,G),this.encryptionKeys.set(J,{key:G,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Z){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[Z]>=$[Y]}initializeFingersCrossedConfig(Z){if(!Z.fingersCrossedEnabled&&Z.fingersCrossed)return{...y7,...Z.fingersCrossed};if(!Z.fingersCrossedEnabled)return null;if(!Z.fingersCrossed)return{...y7};return{...y7,...Z.fingersCrossed}}normalizeOptions(Z){let $={format:"json",level:"info",logDirectory:b$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(Z).filter(([,X])=>X!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!yZ()&&this.config.writeToFile===!0}async writeToFile(Z){let Y=(async()=>{let J,G=0,U=3,H=1000;while(G<U)try{try{try{await EG(this.config.logDirectory,_Y.F_OK|_Y.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await DG(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let z=this.validateEncryptionConfig()?(await this.encrypt(Z)).encrypted:M8.from(Z);try{if(!K$(this.currentLogFile))await T7(this.currentLogFile,"",{mode:420});if(J=QY(this.currentLogFile,"a",420),OG(J,z,{flag:"a"}),jY(J),J!==void 0)P7(J),J=void 0;if((await L9(this.currentLogFile)).size===0){if(await T7(this.currentLogFile,z,{flag:"w",mode:420}),(await L9(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let W=A;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(G<U-1){let Q=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${U}:`,Q);let L=H*2**G;await new Promise((O)=>setTimeout(O,L)),G++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{P7(J)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(z){if(G===U-1){let W=z,Q=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Q),z}G++;let A=H*2**(G-1);await new Promise((W)=>setTimeout(W,A))}})();this.pendingOperations.push(Y);let X=this.pendingOperations.length-1;try{await Y}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(X,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return F9(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return F9(this.config.logDirectory,`${this.name}.log`);let Z=new Date().toISOString().split("T")[0];return F9(this.config.logDirectory,`${this.name}-${Z}.log`)}setupRotation(){if(yZ())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Z=this.config.rotation,$;switch(Z.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,X=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),X=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,X),this.encryptionKeys.set(Y,{key:X,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,H],[,z])=>z.createdAt.getTime()-H.createdAt.getTime()),G=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,G);if(J.length>U)for(let[H]of J.slice(U))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return N7(16).toString("hex")}generateKey(){return N7(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Z=this.keys.get(this.currentKeyId);if(!Z)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Z,id:this.currentKeyId}}encrypt(Z){let{key:$}=this.getCurrentKey(),Y=N7(16),X=FG("aes-256-gcm",$,Y),J=M8.isBuffer(Z)?Z:M8.from(Z,"utf8"),G=X.update(J),U=X.final(),H=G.length+U.length,z=X.getAuthTag(),A=M8.allocUnsafe(16+H+16);return Y.copy(A,0),G.copy(A,16),U.copy(A,16+G.length),z.copy(A,16+H),{encrypted:A,iv:Y}}async compressData(Z){return new Promise(($,Y)=>{let X=KY(),J=[];X.on("data",(G)=>J.push(G)),X.on("end",()=>$(M8.from(M8.concat(J)))),X.on("error",Y),X.write(Z),X.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Z={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...Z,...$}}return Z}async rotateLog(){if(yZ())return;if(!this.shouldWriteToFile())return;let Z=await L9(this.currentLogFile).catch(()=>null);if(!Z)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&Z.size>=$.maxSize){let Y=this.currentLogFile,X=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await L$(this.config.logDirectory),G=J.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,A)=>{let W=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),U=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${Y}.${U}`;if(await L9(Y).catch(()=>null))try{if(await VY(Y,H),$.compress)try{let z=`${H}.gz`;await this.compressLogFile(H,z),await F$(H)}catch(z){console.error("Error compressing rotated file:",z)}if(G.length===0&&!J.some((z)=>z.endsWith(".log.1")))try{let z=`${Y}.1`;await T7(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${J}.log`);if(await L9(Y).catch(()=>null))await VY(Y,G)}if(this.currentLogFile=X,$.maxFiles){let G=(await L$(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,H)=>H.localeCompare(U));for(let U of G.slice($.maxFiles))await F$(F9(this.config.logDirectory,U))}}}async compressLogFile(Z,$){let Y=WY(Z),X=RG($),J=KY();await wG(Y,J,X)}async handleFingersCrossedBuffer(Z,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Z)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let X=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(Z){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[Z]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Z)=>{if(Z instanceof Promise)return Z.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),K$(this.currentLogFile))try{let Z=QY(this.currentLogFile,"r+");jY(Z),P7(Z)}catch(Z){console.error(`Error flushing file: ${Z}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Z of this.pendingOperations)if(typeof Z.cancel==="function")Z.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Z){console.error("Error waiting for pending operations:",Z)}if(!yZ()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await L$(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await F$(F9(this.config.logDirectory,Y))}catch(X){console.error(`Failed to delete temp file ${Y}:`,X)}}catch(Z){console.error("Error cleaning up temporary files:",Z)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Z){if(!Z)return"";return`${this.tagFormat.prefix}${Z}${this.tagFormat.suffix}`}formatFileTimestamp(Z){return`[${Z.toISOString()}]`}formatConsoleTimestamp(Z){return this.shouldStyleConsole()?LZ.gray(Z.toLocaleTimeString()):Z.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||yZ())return!1;let Z=typeof _Z.env.NO_COLOR<"u",$=_Z.env.FORCE_COLOR==="0";if(Z||$)return!1;return!!(typeof _Z.stderr<"u"&&_Z.stderr.isTTY||typeof _Z.stdout<"u"&&_Z.stdout.isTTY)}formatConsoleMessage(Z){let{timestamp:$,icon:Y="",tag:X="",message:J,level:G,showTimestamp:U=!0}=Z,H=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(U)O.push($);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(X)O.push(X.replace(/[[\]]/g,""));return O.push(J),O.join(" ")}let z=_Z.stdout.columns||120,A="";if(G==="warning"||G==="error")A=`${Y} ${J}`;else if(G==="info"||G==="success")A=`${Y} ${X} ${J}`;else A=`${Y} ${X} ${LZ.cyan(J)}`;if(!U)return A.trim();let W=H(A).trim().length,Q=H($).length,L=Math.max(1,z-2-W-Q);return`${A.trim()}${" ".repeat(L)}${$}`}formatMessage(Z,$){if($.length===1&&Array.isArray($[0]))return Z.replace(/\{(\d+)\}/g,(G,U)=>{let H=Number.parseInt(U,10);return H<$[0].length?String($[0][H]):G});let Y=/%([sdijfo%])/g,X=0,J=Z.replace(Y,(G,U)=>{if(U==="%")return"%";if(X>=$.length)return G;let H=$[X++];switch(U){case"s":return String(H);case"d":case"i":return Number(H).toString();case"j":case"o":return JSON.stringify(H,null,2);default:return G}});if(X<$.length)J+=` ${$.slice(X).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return J}formatMarkdown(Z){if(!Z)return Z;let $=Z;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,X,J)=>{let G=LZ.underline(LZ.blue(X)),U=this.toAbsoluteFilePath(J);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let H=`file://${encodeURI(U)}`,z="\x1B]8;;",A="\x1B\\";return`\x1B]8;;${H}\x1B\\${G}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${J}\x1B\\${G}\x1B]8;;\x1B\\`;return G}),$=$.replace(/`([^`]+)`/g,(Y,X)=>LZ.bgGray(X)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,X)=>LZ.bold(X)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,X)=>LZ.italic(X)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,X)=>LZ.italic(X)),$=$.replace(/~([^~]+)~/g,(Y,X)=>LZ.strikethrough(X)),$}supportsHyperlinks(){if(yZ())return!1;let Z=_Z.env;if(!Z)return!1;if(Z.TERM_PROGRAM==="iTerm.app"||Z.TERM_PROGRAM==="vscode"||Z.TERM_PROGRAM==="WezTerm")return!0;if(Z.WT_SESSION)return!0;if(Z.TERM==="xterm-kitty")return!0;let $=Z.VTE_VERSION?Number.parseInt(Z.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(Z){try{let $=Z;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=_Z.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(IG($)||$.startsWith("./")||$.startsWith("../"))$=MG($);else return null;return K$($)?$:null}catch{return null}}buildOutputTexts(Z){let $=this.shouldStyleConsole()?this.formatMarkdown(Z):Z,Y=Z.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(Z,$,...Y){if(!this.shouldLog(Z))return;let X=new Date,J=this.formatConsoleTimestamp(X),G=this.formatFileTimestamp(X),U,H;if($ instanceof Error)U=$.message,H=$.stack;else U=this.formatMessage($,Y);let{consoleText:z,fileText:A}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let Q=this.options.showIcons===!1?"":f5[Z],L=this.options.showTags!==!1&&this.name?LZ.gray(this.formatTag(this.name)):"",O;switch(Z){case"debug":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:L,message:LZ.gray(z),level:Z}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:L,message:z,level:Z}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:L,message:LZ.green(z),level:Z}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:L,message:z,level:Z}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:L,message:z,level:Z}),console.error(O),H){let T=H.split(`
|
|
41
|
-
`);for(let w of T)if(w.trim()&&!w.includes(U))console.error(this.formatConsoleMessage({timestamp:J,message:LZ.gray(` ${w}`),level:Z,showTimestamp:!1}))}break}}else if(!yZ()){if(console.error(`${G} ${this.environment}.${Z.toUpperCase()}: ${U}`),H)console.error(H)}let W=`${G} ${this.environment}.${Z.toUpperCase()}: ${A}
|
|
42
|
-
`;if(H)W+=`${H}
|
|
43
|
-
`;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress(Z,$=""){let Y={update:(H,z)=>{},finish:(H)=>{},interrupt:(H,z)=>{}};if(!this.enabled)return Y;let X=30;if(this.activeProgressBar={total:Math.max(1,Z||1),current:0,message:$||"",barLength:X,lastRenderedLine:""},this.shouldStyleConsole()&&!yZ()&&_Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(H,z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,H),this.activeProgressBar.total),z!==void 0)this.activeProgressBar.message=z;if(this.shouldStyleConsole()&&!yZ()&&_Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(H)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,H)},interrupt:(H,z="info")=>{if(!yZ()&&_Z.stdout.isTTY)_Z.stdout.write(`
|
|
44
|
-
`);if(this[z==="warning"?"warn":z](H),this.activeProgressBar&&this.shouldStyleConsole()&&!yZ()&&_Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Z){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?LZ.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:this.options.showIcons===!1?"":LZ.blue("\u25D0"),tag:Y,message:`${LZ.cyan(Z)}...`}))}return async(Y)=>{if(!this.enabled)return;let X=performance.now(),J=Math.round(X-$),G=`${Z} completed in ${J}ms`,U=new Date,H=this.formatConsoleTimestamp(U),A=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${G}`;if(Y)A+=` ${JSON.stringify(Y)}`;if(A+=`
|
|
45
|
-
`,A=A.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?LZ.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:H,icon:this.options.showIcons===!1?"":LZ.green("\u2713"),tag:W,message:`${G}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!yZ())console.error(A.trim());if(this.shouldWriteToFile())await this.writeToFile(A)}}async debug(Z,...$){await this.log("debug",Z,...$)}async info(Z,...$){await this.log("info",Z,...$)}async success(Z,...$){await this.log("success",Z,...$)}async warn(Z,...$){await this.log("warning",Z,...$)}async error(Z,...$){await this.log("error",Z,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Z=this.config.rotation,{encrypt:$}=Z;return!!$}async only(Z){if(!this.enabled)return;return await Z()}isEnabled(){return this.enabled}setEnabled(Z){this.enabled=Z}extend(Z){let $=`${this.name}:${Z}`,Y=new c$($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(yZ())throw Error("createReadStream is not supported in browser environments");if(!K$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return WY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Z){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let X=M8.isBuffer(Z)?Z:M8.from(Z,"base64"),J=X.subarray(0,16),G=X.subarray(X.length-16),U=X.subarray(16,X.length-16),H=BG("aes-256-gcm",Y,J);H.setAuthTag(G);let z=H.update(U),A=H.final(),W=z.length+A.length,Q=M8.allocUnsafe(W);return z.copy(Q,0),A.copy(Q,z.length),Q.toString("utf8")}catch(X){throw Error(`Decryption failed: ${X instanceof Error?X.message:String(X)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return yZ()}isServerMode(){return!yZ()}setTestEncryptionKey(Z,$){this.currentKeyId=Z,this.keys.set(Z,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Z){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),X=this.formatFileTimestamp($),{consoleText:J,fileText:G}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let H=J.split(`
|
|
46
|
-
`),z=Math.max(...H.map((L)=>L.length))+2,A=`\u250C${"\u2500".repeat(z)}\u2510`,W=`\u2514${"\u2500".repeat(z)}\u2518`,Q=H.map((L)=>{return this.formatConsoleMessage({timestamp:Y,message:LZ.cyan(L),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:LZ.cyan(A),showTimestamp:!1})),Q.forEach((L)=>console.error(L)),console.error(this.formatConsoleMessage({timestamp:Y,message:LZ.cyan(W),showTimestamp:!1}))}else if(!yZ())console.error(`${X} ${this.environment}.INFO: [BOX] ${G}`);let U=`${X} ${this.environment}.INFO: [BOX] ${G}
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(Z){if(yZ())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${LZ.cyan("?")} ${Z} (y/n) `);let Y=(X)=>{let J=X.toString().trim().toLowerCase();_Z.stdin.removeListener("data",Y);try{if(typeof _Z.stdin.setRawMode==="function")_Z.stdin.setRawMode(!1)}catch{}_Z.stdin.pause(),console.error(""),$(J==="y"||J==="yes")};try{if(typeof _Z.stdin.setRawMode==="function")_Z.stdin.setRawMode(!0)}catch{}_Z.stdin.resume(),_Z.stdin.once("data",Y)})}setFancy(Z){this.fancy=Z}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Z,...$){if(!this.enabled)return;let Y=Z;if($&&$.length>0){let z=/%([sdijfo%])/g,A=0;if(Y=Z.replace(z,(W,Q)=>{if(Q==="%")return"%";if(A>=$.length)return W;let L=$[A++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return W}}),A<$.length)Y+=` ${$.slice(A).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:X,fileText:J}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?LZ.gray(this.formatTag(this.name)):"",A=this.options.showIcons===!1?"":`${LZ.blue("\u25D0")} `;console.error(`${A}${z} ${LZ.cyan(X)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${J}
|
|
48
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(H)}renderProgressBar(Z,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!_Z.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Z.current/Z.total*100))),X=Math.round(Z.barLength*Y/100),J=Z.barLength-X,G=LZ.green("\u2501".repeat(X)),U=LZ.gray("\u2501".repeat(J)),H=`[${G}${U}]`,z=`${Y}%`.padStart(4),A=Z.message?` ${Z.message}`:"",W=this.options.showIcons===!1?"":$||Y===100?LZ.green("\u2713"):LZ.blue("\u25B6"),Q=this.options.showTags!==!1&&this.name?` ${LZ.gray(this.formatTag(this.name))}`:"",L=`\r${W}${Q} ${H} ${z}${A}`,O=_Z.stdout.columns||80,T=" ".repeat(Math.max(0,O-L.replace(this.ANSI_PATTERN,"").length));if(Z.lastRenderedLine=`${L}${T}`,_Z.stdout.write(Z.lastRenderedLine),$)_Z.stdout.write(`
|
|
49
|
-
`)}finishProgressBar(Z,$){if(!this.enabled||!this.fancy||yZ()||!_Z.stdout.isTTY){this.activeProgressBar=null;return}if(Z.current<Z.total)Z.current=Z.total;if($)Z.message=$;this.renderProgressBar(Z,!0),this.activeProgressBar=null}async clear(Z={}){if(yZ()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await L$(this.config.logDirectory),Y=[];for(let X of $){if(!(Z.name?new RegExp(Z.name.replace("*",".*")).test(X):X.startsWith(this.name))||!X.endsWith(".log"))continue;let G=F9(this.config.logDirectory,X);if(Z.before)try{if((await L9(G)).mtime>=Z.before)continue}catch(U){console.error(`Failed to get stats for file ${G}:`,U);continue}Y.push(G)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let X of Y)try{await F$(X),console.warn(`Deleted log file: ${X}`)}catch(J){console.error(`Failed to delete log file ${X}:`,J)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function g5(Z,$={}){let{maxRetries:Y=3,retryDelay:X=1000,isRetryable:J=()=>!0,fallback:G}=$,U=Error("Unknown error occurred");for(let H=0;H<=Y;H++)try{return await Z()}catch(z){if(U=z instanceof Error?z:Error(String(z)),H===Y||!J(U))break;if(X>0)await new Promise((A)=>setTimeout(A,X))}if(G!==void 0)return G;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class J0{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Z,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(Z.toLowerCase()),parse:(Z)=>{let $=Z.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(Z,$)=>$==="number"||!Number.isNaN(Number(Z))&&!Number.isNaN(Number.parseFloat(Z)),parse:(Z)=>{let $=Number(Z);if(Number.isNaN($))throw TypeError(`Cannot parse "${Z}" as number`);return $}},{name:"array",canParse:(Z,$)=>$==="array"||Z.startsWith("[")||Z.includes(","),parse:(Z)=>{try{let $=JSON.parse(Z);if(Array.isArray($))return $}catch{}return Z.split(",").map(($)=>$.trim())}},{name:"json",canParse:(Z,$)=>$==="object"||(Z.startsWith("{")&&Z.endsWith("}")||Z.startsWith("[")&&Z.endsWith("]")),parse:(Z)=>{try{return JSON.parse(Z)}catch($){throw Error(`Cannot parse "${Z}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(Z,$,Y={}){let{prefix:X,useCamelCase:J=!0,useBackwardCompatibility:G=!0,customParsers:U={},verbose:H=!1,trackPerformance:z=!0}=Y,A=async()=>{if(!Z)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let W=X||this.generateEnvPrefix(Z),Q={...$};return this.processObject(Q,[],W,{useCamelCase:J,useBackwardCompatibility:G,customParsers:U,verbose:H,configName:Z}),{config:Q,source:{type:"environment",priority:50,timestamp:new Date}}};if(z)return o7.track("applyEnvironmentVariables",A,{configName:Z});return A()}generateEnvPrefix(Z){return Z.toUpperCase().replace(/-/g,"_")}formatEnvKey(Z,$){if(!$)return Z.toUpperCase();return Z.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Z,$,Y,X){for(let[J,G]of Object.entries(Z)){let U=[...$,J],H=U.map((W)=>this.formatEnvKey(W,X.useCamelCase)),z=`${Y}_${H.join("_")}`,A=X.useBackwardCompatibility?`${Y}_${U.map((W)=>W.toUpperCase()).join("_")}`:null;if(X.verbose);if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.processObject(G,U,Y,X);else{let W=R$.env[z]||(A?R$.env[A]:void 0);if(W!==void 0){if(X.verbose){let Q=R$.env[z]?z:A}try{Z[J]=this.parseEnvironmentValue(W,typeof G,z,X.customParsers,X.configName)}catch(Q){if(Q instanceof X0)throw Q;throw o8.envVar(z,W,typeof G,X.configName)}}}}}parseEnvironmentValue(Z,$,Y,X,J){for(let[G,U]of Object.entries(X))try{return U(Z)}catch{continue}for(let G of this.defaultParsers)if(G.canParse(Z,$))try{return G.parse(Z)}catch{throw o8.envVar(Y,Z,`${$} (via ${G.name} parser)`,J)}return Z}getEnvironmentVariables(Z){let $={},Y=Z.toUpperCase();for(let[X,J]of Object.entries(R$.env))if(X.startsWith(Y)&&J!==void 0)$[X]=J;return $}validateEnvironmentVariable(Z,$,Y){let X=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Z))X.push(`Environment variable key "${Z}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Z,$,Y,{})}catch(J){X.push(`Cannot parse value "${$}" as ${Y}: ${J}`)}return{isValid:X.length===0,errors:X}}generateEnvVarDocs(Z,$,Y={}){let{prefix:X,format:J="text"}=Y,G=X||this.generateEnvPrefix(Z),U=[];switch(this.extractEnvVarInfo($,[],G,U),J){case"markdown":return this.formatAsMarkdown(U,Z);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Z)}}extractEnvVarInfo(Z,$,Y,X){for(let[J,G]of Object.entries(Z)){let U=[...$,J],H=`${Y}_${U.map((z)=>this.formatEnvKey(z,!0)).join("_")}`;if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.extractEnvVarInfo(G,U,Y,X);else X.push({key:H,type:Array.isArray(G)?"array":typeof G,description:`Configuration for ${U.join(".")}`,example:this.generateExample(G)})}}generateExample(Z){if(Array.isArray(Z))return JSON.stringify(Z);if(typeof Z==="object"&&Z!==null)return JSON.stringify(Z);return String(Z)}formatAsText(Z,$){let Y=`Environment Variables for ${$}:
|
|
50
|
-
|
|
51
|
-
`;for(let X of Z)Y+=`${X.key}
|
|
52
|
-
`,Y+=` Type: ${X.type}
|
|
53
|
-
`,Y+=` Description: ${X.description}
|
|
54
|
-
`,Y+=` Example: ${X.example}
|
|
55
|
-
|
|
56
|
-
`;return Y}formatAsMarkdown(Z,$){let Y=`# Environment Variables for ${$}
|
|
57
|
-
|
|
58
|
-
`;Y+=`| Variable | Type | Description | Example |
|
|
59
|
-
`,Y+=`|----------|------|-------------|----------|
|
|
60
|
-
`;for(let X of Z)Y+=`| \`${X.key}\` | ${X.type} | ${X.description} | \`${X.example}\` |
|
|
61
|
-
`;return Y}}function p5(Z,$,Y={}){return HX(Z,$,Y,new WeakMap)}function HX(Z,$,Y,X){let{arrayMergeMode:J="replace",skipNullish:G=!1,customMerger:U}=Y;if($===null||$===void 0)return G?Z:$;if(U){let H=U(Z,$);if(H!==void 0)return H}if(Array.isArray($)||Array.isArray(Z))return AX(Z,$,J,X);if(!J8($)||!J8(Z))return $;return u5(Z,$,Y,X)}function AX(Z,$,Y,X){if(Array.isArray($)&&!Array.isArray(Z))return $;if(Array.isArray(Z)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(Z))switch(Y){case"replace":return $;case"concat":return d5(Z,$);case"smart":return m5(Z,$,X);default:return $}return $}function d5(Z,$){let Y=[...$];for(let X of Z)if(!Y.some((J)=>s7(J,X)))Y.push(X);return Y}function m5(Z,$,Y){if($.length===0)return Z;if(Z.length===0)return $;if(J8($[0])&&J8(Z[0]))return c5(Z,$,Y);if($.every((X)=>typeof X==="string")&&Z.every((X)=>typeof X==="string")){let X=[...$];for(let J of Z)if(!X.includes(J))X.push(J);return X}return $}function c5(Z,$,Y){let X=[...$];for(let J of Z){if(!J8(J)){X.push(J);continue}let G=["id","name","key","path","type"],U=!1;for(let H of G)if(H in J){if(X.find((A)=>J8(A)&&(H in A)&&A[H]===J[H])){U=!0;break}}if(!U)X.push(J)}return X}function u5(Z,$,Y,X){let J=$;if(J8(J)&&X.has(J))return X.get(J);let G={...Z};if(J8(J))X.set(J,G);for(let U in J){if(!Object.prototype.hasOwnProperty.call(J,U))continue;let H=J[U],z=G[U];if(Y.skipNullish&&(H===null||H===void 0))continue;if(H===null||H===void 0){G[U]=H;continue}if(J8(H)&&J8(z))G[U]=HX(z,H,Y,X);else if(Array.isArray(H)||Array.isArray(z))G[U]=AX(z,H,Y.arrayMergeMode||"smart",X);else G[U]=H}return G}function WX(Z,$,Y="replace"){return p5(Z,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function s7(Z,$){if(Z===$)return!0;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;for(let Y=0;Y<Z.length;Y++)if(!s7(Z[Y],$[Y]))return!1;return!0}if(J8(Z)&&J8($)){let Y=Object.keys(Z),X=Object.keys($);if(Y.length!==X.length)return!1;for(let J of Y){if(!Object.prototype.hasOwnProperty.call($,J))return!1;if(!s7(Z[J],$[J]))return!1}return!0}return!1}function J8(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}class jX{extensions=kY;async loadFromPath(Z,$,Y={}){let{arrayStrategy:X="replace",useCache:J=!0,cacheTtl:G,trackPerformance:U=!0,verbose:H=!1}=Y;if(J){let A=C$.getWithFileCheck("file",Z);if(A){if(H)console.log(`Configuration loaded from cache: ${Z}`);return A}}let z=async()=>{if(!O$(Z))return null;try{let A=`?t=${Date.now()}`,W=await import(Z+A),Q=W.default||W,L="default"in W,O=Object.keys(W).length>0;if(!L&&!O)throw new f$(Z,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new f$(Z,Error("Configuration must export a valid object"),"unknown");let K={config:WX($,Q,X),source:{type:"file",path:Z,priority:100,timestamp:new Date}};if(J)C$.setWithFileCheck("file",K,Z,G);return K}catch(A){throw A instanceof Error?o8.configLoad(Z,A):o8.configLoad(Z,Error(String(A)))}};if(U)return o7.track("loadFromPath",z,{path:Z});return z()}async tryLoadFromPaths(Z,$,Y={}){for(let X of Z)try{let J=await this.loadFromPath(X,$,Y);if(J)return J}catch(J){if(J instanceof Error&&J.name==="ConfigLoadError")throw J;if(Y.verbose)console.warn(`Failed to load config from ${X}:`,J)}return null}generateConfigPaths(Z,$,Y){return fJ({name:Z,directory:$,alias:Y})}generateNamePatterns(Z,$){return xY({name:Z,alias:$})}checkFileAccess(Z){return g5(async()=>{return O$(Z)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Z,$,Y){let X=[];if(!O$(Z))return X;if($||Y){let J=this.generateNamePatterns($||"",Y);for(let G of J)for(let U of this.extensions){let H=PY(Z,`${G}${U}`);if(await this.checkFileAccess(H))X.push(H)}}else try{let{readdirSync:J}=await import("fs"),G=J(Z);for(let U of G)if(this.looksLikeConfigFile(U)){let H=PY(Z,U);if(await this.checkFileAccess(H))X.push(H)}}catch{return[]}return X}looksLikeConfigFile(Z){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((Y)=>Y.test(Z))}async validateConfigFile(Z){let $=[];try{if(!O$(Z))return $.push("Configuration file does not exist"),$;let Y=await import(Z),X=Y.default||Y;if(X===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof X!=="object"||X===null)$.push("Configuration must be an object");else if(Array.isArray(X))$.push("Configuration cannot be an array at the root level");if(Z.endsWith(".json"))try{let{readFileSync:J}=await import("fs"),G=J(Z,"utf8");JSON.parse(G)}catch(J){$.push(`Invalid JSON syntax: ${J}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(Z){try{let{statSync:$}=await import("fs");return $(Z).mtime}catch{return null}}async preloadConfigurations(Z,$={}){let Y=new Map;return await Promise.allSettled(Z.map(async(X)=>{try{let J=await this.loadFromPath(X,{},$);if(J)Y.set(X,J.config)}catch(J){if($.verbose)console.warn(`Failed to preload ${X}:`,J)}})),Y}}class QX{async validateConfiguration(Z,$,Y={}){let{stopOnFirstError:X=!1,validateRequired:J=!0,validateTypes:G=!0,customRules:U=[],trackPerformance:H=!0,verbose:z=!1}=Y,A=async()=>{let W=[],Q=[],L={stopOnFirstError:X,validateRequired:J,validateTypes:G,customRules:U,trackPerformance:H,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(Z,$,L);else if(Array.isArray($))return this.validateWithRules(Z,[...$,...U],L);else return this.validateWithJSONSchema(Z,$,L)}catch(O){return W.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:W,warnings:Q}}};if(H)return await o7.track("validateConfiguration",A);return A()}async validateWithSchemaFile(Z,$,Y){try{if(!n5($))throw new g$($,[{path:"",message:"Schema file does not exist"}]);let X=await import($),J=X.default||X;if(Array.isArray(J))return this.validateWithRules(Z,J,Y);else return this.validateWithJSONSchema(Z,J,Y)}catch(X){throw new g$($,[{path:"",message:`Failed to load schema: ${X}`}])}}validateWithJSONSchema(Z,$,Y){let X=[],J=[];return this.validateObjectAgainstSchema(Z,$,"",X,J,Y),{isValid:X.length===0,errors:X,warnings:J}}validateObjectAgainstSchema(Z,$,Y,X,J,G){if(G.validateTypes&&$.type){let U=Array.isArray(Z)?"array":typeof Z,H=Array.isArray($.type)?$.type:[$.type];if(!H.includes(U)){if(X.push({path:Y,message:`Expected type ${H.join(" or ")}, got ${U}`,expected:H.join(" or "),actual:U,rule:"type"}),G.stopOnFirstError)return}}if($.enum&&!$.enum.includes(Z)){if(X.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:Z,rule:"enum"}),G.stopOnFirstError)return}if(typeof Z==="string"){if($.minLength!==void 0&&Z.length<$.minLength)X.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:Z.length,rule:"minLength"});if($.maxLength!==void 0&&Z.length>$.maxLength)X.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:Z.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(Z))X.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:Z,rule:"pattern"})}}if(typeof Z==="number"){if($.minimum!==void 0&&Z<$.minimum)X.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:Z,rule:"minimum"});if($.maximum!==void 0&&Z>$.maximum)X.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:Z,rule:"maximum"})}if(Array.isArray(Z)&&$.items)for(let U=0;U<Z.length;U++){let H=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Z[U],$.items,H,X,J,G),G.stopOnFirstError&&X.length>0)return}if(Z&&typeof Z==="object"&&!Array.isArray(Z)){let U=Z;if(G.validateRequired&&$.required){for(let H of $.required)if(!(H in U)){if(X.push({path:Y?`${Y}.${H}`:H,message:`Missing required property '${H}'`,expected:"required",rule:"required"}),G.stopOnFirstError)return}}if($.properties){for(let[H,z]of Object.entries($.properties))if(H in U){let A=Y?`${Y}.${H}`:H;if(this.validateObjectAgainstSchema(U[H],z,A,X,J,G),G.stopOnFirstError&&X.length>0)return}}if($.additionalProperties===!1){let H=new Set(Object.keys($.properties||{}));for(let z of Object.keys(U))if(!H.has(z))J.push({path:Y?`${Y}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Z,$,Y){let X=[],J=[];for(let G of $)try{let U=this.getValueByPath(Z,G.path),H=this.validateWithRule(U,G,G.path);if(X.push(...H),Y.stopOnFirstError&&X.length>0)break}catch(U){X.push({path:G.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:X.length===0,errors:X,warnings:J}}validateWithRule(Z,$,Y){let X=[];if($.required&&(Z===void 0||Z===null))return X.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),X;if(Z===void 0||Z===null)return X;if($.type){let J=Array.isArray(Z)?"array":typeof Z;if(J!==$.type)X.push({path:Y,message:$.message||`Expected type ${$.type}, got ${J}`,expected:$.type,actual:J,rule:"type"})}if($.min!==void 0){let J=Array.isArray(Z)?Z.length:typeof Z==="string"?Z.length:typeof Z==="number"?Z:0;if(J<$.min)X.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:J,rule:"min"})}if($.max!==void 0){let J=Array.isArray(Z)?Z.length:typeof Z==="string"?Z.length:typeof Z==="number"?Z:0;if(J>$.max)X.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:J,rule:"max"})}if($.pattern&&typeof Z==="string"){if(!$.pattern.test(Z))X.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:Z,rule:"pattern"})}if($.enum&&!$.enum.includes(Z))X.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:Z,rule:"enum"});if($.validator){let J=$.validator(Z);if(J)X.push({path:Y,message:$.message||J,rule:"custom"})}return X}getValueByPath(Z,$){if(!$)return Z;let Y=$.split("."),X=Z;for(let J of Y)if(X&&typeof X==="object"&&J in X)X=X[J];else return;return X}generateRulesFromInterface(Z){let $=[],Y=Z.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let X of Y){let[,J,G,U]=X;$.push({path:J,required:!G,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(Z){switch(Z.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:i5},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function l5(Z){if(!Z)return"";let $=Array.isArray(Z)?Z.filter(Boolean):[Z];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class _X{fileLoader=new jX;envProcessor=new J0;validator=new QX;async loadConfig(Z){let $=Date.now(),{cache:Y,performance:X,schema:J,validate:G,...U}=Z;try{if(Y?.enabled){let z=this.checkCache(U.name||"",U);if(z)return z}let H;try{H=await this.loadConfigurationStrategies(U,!0,Y)}catch(z){if(U.configFile)throw z;let A=U.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(A)throw z;H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let W=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),Q=!W&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),L=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(A&&(L||W))throw z;if(Q&&(!A||!L))H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!A)H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(J||G)await this.validateConfiguration(H.config,J,G,U.name);if(Y?.enabled&&H)this.cacheResult(U.name||"",H,Y,U);if(X?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(X.onMetrics)X.onMetrics(z);if(X.slowThreshold&&z.duration>X.slowThreshold)z8.warn(`Slow configuration loading detected: ${z.duration}ms for ${U.name}`);H.metrics=z}return H}catch(H){if(H instanceof Error&&H.name==="ConfigNotFoundError")throw H;let z=Date.now()-$;throw z8.error(`Configuration loading failed after ${z}ms:`,[H instanceof Error?H:Error(String(H))]),H}}async loadConfigurationStrategies(Z,$=!1,Y){let{name:X="",alias:J,configFile:G,cwd:U,configDir:H,defaultConfig:z,checkEnv:A=!0,arrayStrategy:W="replace",verbose:Q=!1}=Z,L=U||p$.cwd(),O=[];if(G){let V=F8(L,G);O.push(V);let F=A?x9(X,z,Q):z,I=await this.fileLoader.tryLoadFromPaths([V],F,{arrayStrategy:W,verbose:Q,cacheTtl:Y?.ttl,useCache:!Y?.ttl||Y.ttl>100});if(!I)throw o8.configNotFound(X||G,O,J);if(Q)z8.success(`Configuration loaded from explicit path: ${V}`);return this.finalizeResult(I,O,A,X,Q)}let T=await this.loadLocalConfiguration(X,J,L,H,z,W,Q,A,Y);if(T)return O.push(...this.getLocalSearchPaths(X,J,L,H)),this.finalizeResult(T,O,A,X,Q);let w=await this.loadHomeConfiguration(X,J,z,W,Q,A);if(w)return O.push(...this.getHomeSearchPaths(X,J)),this.finalizeResult(w,O,A,X,Q);let K=await this.loadPackageJsonConfiguration(X,J,L,z,W,Q,A);if(K)return O.push(F8(L,"package.json")),this.finalizeResult(K,O,A,X,Q);if(O.push(...this.getAllSearchPaths(X,J,L,H)),$)throw o8.configNotFound(X,O,J);return{...await this.applyEnvironmentVariables(X,z,A,Q),warnings:[`No configuration file found for "${X}"${l5(J)}, using defaults with environment variables`]}}async loadLocalConfiguration(Z,$,Y,X,J,G,U,H,z){let A=H?x9(Z,J,U):J,W=this.getLocalDirectories(Y,X);for(let Q of W){if(U)z8.info(`Searching for configuration in: ${Q}`);let L=this.fileLoader.generateConfigPaths(Z,Q,$),O=await this.fileLoader.tryLoadFromPaths(L,A,{arrayStrategy:G,verbose:U,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(O){if(U)z8.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration(Z,$,Y,X,J,G){if(!Z)return null;let U=G?x9(Z,Y,J):Y,H=[F8(H9(),".config",Z),F8(H9(),".config"),H9()];for(let z of H){if(J)z8.info(`Checking home directory: ${z}`);let A=this.fileLoader.generateConfigPaths(Z,z,$),W=await this.fileLoader.tryLoadFromPaths(A,U,{arrayStrategy:X,verbose:J});if(W){if(J)z8.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration(Z,$,Y,X,J,G,U){let H=U?x9(Z,X,G):X;try{let z=F8(Y,"package.json");if(!pJ(z))return null;let A={};try{A=JSON.parse(dJ(z,"utf8"))}catch(L){if(G)z8.warn("Failed to parse package.json:",[L instanceof Error?L:Error(String(L))]);return null}let W=A[Z],Q=Z;if(!W&&$){let L=Array.isArray($)?$:[$];for(let O of L){if(!O)continue;if(A[O]){W=A[O],Q=O;break}}}if(W&&typeof W==="object"&&!Array.isArray(W)){if(G)z8.success(`Configuration loaded from package.json: ${Q}`);return{config:WX(H,W,J),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(G)z8.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(Z,$,Y,X){if(!Y||!Z||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:x9(Z,$,X),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Z,$,Y,X,J){return{config:Z.config,source:Z.source,path:Z.source.path}}async validateConfiguration(Z,$,Y,X){let J=[];if(Y){let G=Y(Z);if(G)J.push(...G)}if($){let G=await this.validator.validateConfiguration(Z,$);if(!G.isValid)J.push(...G.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(J.length>0)throw o8.configValidation(X||"unknown",J,X)}checkCache(Z,$){let Y=this.generateCacheKey(Z,$);return C$.get(Y)||null}cacheResult(Z,$,Y,X){let J=this.generateCacheKey(Z,X);C$.set(J,$,void 0,Y.ttl)}generateCacheKey(Z,$){let Y=[Z];if($.alias){let X=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${X}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configFile)Y.push(`configFile:${$.configFile}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(Z,$){return gJ({cwd:Z,configDir:$})}getAllSearchPaths(Z,$,Y,X){let J=[];return J.push(...this.getLocalSearchPaths(Z,$,Y,X)),J.push(...this.getHomeSearchPaths(Z,$)),J.push(F8(Y,"package.json")),J}getLocalSearchPaths(Z,$,Y,X){let J=this.getLocalDirectories(Y,X),G=[];for(let U of J)G.push(...this.fileLoader.generateConfigPaths(Z,U,$));return G}getHomeSearchPaths(Z,$){if(!Z)return[];let Y=[F8(H9(),".config",Z),F8(H9(),".config"),H9()],X=[];for(let J of Y)X.push(...this.fileLoader.generateConfigPaths(Z,J,$));return X}async loadConfigWithResult(Z){return this.loadConfig(Z)}}async function VX(Z){let $="defaultConfig"in Z&&Z.defaultConfig!==void 0?Z.defaultConfig:{},Y="cache"in Z||"performance"in Z||"schema"in Z||"validate"in Z;try{let X;if(Y)X=await h7.loadConfig(Z);else X=await h7.loadConfig({...Z,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return X?.config??$}catch(X){if(Z.configFile)throw X;let J=X instanceof Error?X.name:"UnknownError",G=X instanceof Error?X.message:String(X);if(!(J==="ConfigNotFoundError"||J==="ConfigLoadError"||J==="ConfigValidationError"||G.includes("config"))&&Z.verbose)z8.warn("Unexpected error loading config, using defaults:",[X instanceof Error?X:Error(String(X))]);let H=Y?{...Z,defaultConfig:$}:{...Z,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Z?Z.checkEnv!==!1:!0)return(await h7.applyEnvironmentVariables(H.name||"",$,!0,H.verbose||!1))?.config??$;return $}}function x9(Z,$,Y=!1){let X=new J0,J=Z.toUpperCase().replace(/[^A-Z0-9]/g,"_");function G(U,H=[]){let z={...U};for(let[A,W]of Object.entries(U)){let Q=[...H,A],L=[`${J}_${Q.join("_").toUpperCase()}`,`${J}_${Q.map((w)=>w.toUpperCase()).join("")}`,`${J}_${Q.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,T;for(let w of L)if(O=p$.env[w],O!==void 0){T=w;break}if(O!==void 0&&T)if(typeof W==="boolean")z[A]=["true","1","yes"].includes(O.toLowerCase());else if(typeof W==="number"){let w=Number(O);if(!Number.isNaN(w))z[A]=w}else if(Array.isArray(W))try{z[A]=JSON.parse(O)}catch{z[A]=O.split(",").map((w)=>w.trim())}else z[A]=O;else if(W&&typeof W==="object"&&!Array.isArray(W))z[A]=G(W,Q)}return z}return G($)}var C$,o7,kY,CG,SG=(Z)=>Z,PG=(Z,$)=>{for(var Y in $)CG(Z,Y,{get:$[Y],enumerable:!0,configurable:!0,set:NG.bind($,Y)})},TG=(Z,$)=>()=>(Z&&($=Z(Z=0)),$),hY,nY,R9,g9,iY,X5,J5,FY,D$,p7,pZ,IZ,G5,BY,U5,RY,z5,H5,q7,A5,OY,EY,k7,W5,j5,Q5,_5,I$,lY,V5,dZ,K5,L5,DY,M$,d7,vZ,KZ,F5,IY,B5,MY,R5,O5,x7,E5,wY,CY,D5,v7,I5,M5,w5,C5,S5,w$,sY,N5,P5="0.15.6",eZ,y$,b9,m7,c7,h$,u7,n7,f9,i7,l7,b8,oY,rY,H8,N8,tY,aY,T5,k5,eY,b$,_4,bZ,LZ,V4,v5,K4,y5,L4,F4,SY,B4,h5,b5,R4,NY,O4,E4,D4,I4,M4,y7,f5,w4,W8,$X,f$,YX,XX,X0,JX,GX,g$,UX,zX,o8,i5,z8,h7,T4,q4;var KX=A8(()=>{C$=new TY,o7=new qY,kY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];CG=Object.defineProperty;hY={};PG(hY,{withErrorRecovery:()=>gY,tryLoadConfig:()=>eG,loadConfigWithResult:()=>tG,loadConfig:()=>uY,isRetryableError:()=>nG,isConfigNotFoundError:()=>uG,isBunfigError:()=>pY,globalPerformanceMonitor:()=>g9,globalCache:()=>R9,getEnvOrDefault:()=>iG,generateConfigTypes:()=>Z5,defaultGeneratedDir:()=>aY,defaultConfigDir:()=>tY,deepMergeWithArrayStrategy:()=>Z0,deepMerge:()=>dY,createLibraryConfig:()=>$5,config:()=>aG,bunfigPlugin:()=>Y5,applyEnvVarsToConfig:()=>y9,TypeGenerationError:()=>n7,SchemaValidationError:()=>f9,PluginError:()=>l7,PerformanceMonitor:()=>t7,FileSystemError:()=>u7,ErrorFactory:()=>b8,EnvVarError:()=>h$,EnvProcessor:()=>d$,ConfigValidator:()=>$0,ConfigValidationError:()=>m7,ConfigNotFoundError:()=>y$,ConfigMergeError:()=>c7,ConfigLoader:()=>Y0,ConfigLoadError:()=>b9,ConfigFileLoader:()=>m$,ConfigCache:()=>r7,CacheUtils:()=>iY,BunfigError:()=>eZ,BrowserConfigError:()=>i7,ArrayMergeStrategies:()=>oY});T5=TG(async()=>{nY=import.meta.require,R9=new r7,g9=new t7,iY={createKey:qG,isEquivalent:kG,estimateMemoryUsage:xG},X5=P$(f7.cwd(),"config"),J5=P$(f7.cwd(),"src/generated"),FY=N$.env.CLARITY_LOG_DIR||lJ(hG(),"logs"),D$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:FY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},p7=await bG(),pZ={red:(Z)=>`\x1B[31m${Z}\x1B[0m`,green:(Z)=>`\x1B[32m${Z}\x1B[0m`,yellow:(Z)=>`\x1B[33m${Z}\x1B[0m`,blue:(Z)=>`\x1B[34m${Z}\x1B[0m`,magenta:(Z)=>`\x1B[35m${Z}\x1B[0m`,cyan:(Z)=>`\x1B[36m${Z}\x1B[0m`,white:(Z)=>`\x1B[37m${Z}\x1B[0m`,gray:(Z)=>`\x1B[90m${Z}\x1B[0m`,bgRed:(Z)=>`\x1B[41m${Z}\x1B[0m`,bgYellow:(Z)=>`\x1B[43m${Z}\x1B[0m`,bold:(Z)=>`\x1B[1m${Z}\x1B[0m`,dim:(Z)=>`\x1B[2m${Z}\x1B[0m`,italic:(Z)=>`\x1B[3m${Z}\x1B[0m`,underline:(Z)=>`\x1B[4m${Z}\x1B[0m`,reset:"\x1B[0m"},IZ=pZ,G5=pZ.red,BY=pZ.green,U5=pZ.yellow,RY=pZ.blue,z5=pZ.magenta,H5=pZ.cyan,q7=pZ.white,A5=pZ.gray,OY=pZ.bgRed,EY=pZ.bgYellow,k7=pZ.bold,W5=pZ.dim,j5=pZ.italic,Q5=pZ.underline,_5=pZ.reset,I$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lY={debug:"\uD83D\uDD0D",info:RY("\u2139"),success:BY("\u2713"),warning:EY(q7(k7(" WARN "))),error:OY(q7(k7(" ERROR ")))},V5=new k$("stacks"),dZ=new k$("bunfig",{showTags:!0}),K5=nZ(h9.cwd(),"config"),L5=nZ(h9.cwd(),"src/generated"),DY=S$.env.CLARITY_LOG_DIR||nJ(dG(),"logs"),M$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:DY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},d7=await mG(),vZ={red:(Z)=>`\x1B[31m${Z}\x1B[0m`,green:(Z)=>`\x1B[32m${Z}\x1B[0m`,yellow:(Z)=>`\x1B[33m${Z}\x1B[0m`,blue:(Z)=>`\x1B[34m${Z}\x1B[0m`,magenta:(Z)=>`\x1B[35m${Z}\x1B[0m`,cyan:(Z)=>`\x1B[36m${Z}\x1B[0m`,white:(Z)=>`\x1B[37m${Z}\x1B[0m`,gray:(Z)=>`\x1B[90m${Z}\x1B[0m`,bgRed:(Z)=>`\x1B[41m${Z}\x1B[0m`,bgYellow:(Z)=>`\x1B[43m${Z}\x1B[0m`,bgGray:(Z)=>`\x1B[100m${Z}\x1B[0m`,bold:(Z)=>`\x1B[1m${Z}\x1B[0m`,dim:(Z)=>`\x1B[2m${Z}\x1B[0m`,italic:(Z)=>`\x1B[3m${Z}\x1B[0m`,underline:(Z)=>`\x1B[4m${Z}\x1B[0m`,strikethrough:(Z)=>`\x1B[9m${Z}\x1B[0m`,reset:"\x1B[0m"},KZ=vZ,F5=vZ.red,IY=vZ.green,B5=vZ.yellow,MY=vZ.blue,R5=vZ.magenta,O5=vZ.cyan,x7=vZ.white,E5=vZ.gray,wY=vZ.bgRed,CY=vZ.bgYellow,D5=vZ.bgGray,v7=vZ.bold,I5=vZ.dim,M5=vZ.italic,w5=vZ.underline,C5=vZ.strikethrough,S5=vZ.reset,w$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sY={debug:"\uD83D\uDD0D",info:MY("\u2139"),success:IY("\u2713"),warning:CY(x7(v7(" WARN "))),error:wY(x7(v7(" ERROR ")))},N5=new v$("stacks"),eZ=class extends Error{timestamp;context;constructor($,Y={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,X])=>`${Y}: ${X}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},y$=class extends eZ{code="CONFIG_NOT_FOUND";constructor($,Y,X){let J=X?` or alias "${X}"`:"";super(`Configuration "${$}"${J} not found`,{configName:$,alias:X,searchPaths:Y,searchPathCount:Y.length})}},b9=class extends eZ{code="CONFIG_LOAD_ERROR";constructor($,Y,X){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},m7=class extends eZ{code="CONFIG_VALIDATION_ERROR";constructor($,Y,X){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:X,validationErrors:Y,errorCount:Y.length})}},c7=class extends eZ{code="CONFIG_MERGE_ERROR";constructor($,Y,X,J){super(`Failed to merge configuration from "${$}" with "${Y}": ${X.message}`,{sourcePath:$,targetPath:Y,configName:J,originalError:X.name,originalMessage:X.message});this.cause=X}},h$=class extends eZ{code="ENV_VAR_ERROR";constructor($,Y,X,J){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${X}`,{envKey:$,envValue:Y,expectedType:X,configName:J})}},u7=class extends eZ{code="FILE_SYSTEM_ERROR";constructor($,Y,X){super(`File system ${$} failed for "${Y}": ${X.message}`,{operation:$,path:Y,originalError:X.name,originalMessage:X.message});this.cause=X}},n7=class extends eZ{code="TYPE_GENERATION_ERROR";constructor($,Y,X){super(`Failed to generate types from "${$}" to "${Y}": ${X.message}`,{configDir:$,outputPath:Y,originalError:X.name,originalMessage:X.message});this.cause=X}},f9=class extends eZ{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,X){super(`Schema validation failed${X?` for config "${X}"`:""}`,{schemaPath:$,configName:X,validationErrors:Y,errorCount:Y.length})}},i7=class extends eZ{code="BROWSER_CONFIG_ERROR";constructor($,Y,X,J){super(`Failed to fetch configuration from "${$}": ${Y} ${X}`,{endpoint:$,status:Y,statusText:X,configName:J})}},l7=class extends eZ{code="PLUGIN_ERROR";constructor($,Y,X){super(`Plugin "${$}" failed during ${Y}: ${X.message}`,{pluginName:$,operation:Y,originalError:X.name,originalMessage:X.message});this.cause=X}},b8={configNotFound(Z,$,Y){return new y$(Z,$,Y)},configLoad(Z,$,Y){return new b9(Z,$,Y)},configValidation(Z,$,Y){return new m7(Z,$,Y)},configMerge(Z,$,Y,X){return new c7(Z,$,Y,X)},envVar(Z,$,Y,X){return new h$(Z,$,Y,X)},fileSystem(Z,$,Y){return new u7(Z,$,Y)},typeGeneration(Z,$,Y){return new n7(Z,$,Y)},schemaValidation(Z,$,Y){return new f9(Z,$,Y)},browserConfig(Z,$,Y,X){return new i7(Z,$,Y,X)},plugin(Z,$,Y){return new l7(Z,$,Y)}},oY={replace:"replace",concat:"concat",smart:"smart"},rY=/^https?:\/\//,H8=new v$("bunfig",{showTags:!0}),N8=new Y0,tY=iZ(r8.cwd(),"config"),aY=iZ(r8.cwd(),"src/generated")});k5=T$.env.CLARITY_LOG_DIR||KG(q5(),"logs"),eY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:k5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},b$={...eY},_4=(async()=>{try{let{loadConfig:Z}=await T5().then(()=>hY),$=await Z({name:"clarity",alias:"logging",defaultConfig:eY,cwd:T$.cwd()});if($)Object.assign(b$,$)}catch{}return b$})();bZ={red:(Z)=>`\x1B[31m${Z}\x1B[0m`,green:(Z)=>`\x1B[32m${Z}\x1B[0m`,yellow:(Z)=>`\x1B[33m${Z}\x1B[0m`,blue:(Z)=>`\x1B[34m${Z}\x1B[0m`,magenta:(Z)=>`\x1B[35m${Z}\x1B[0m`,cyan:(Z)=>`\x1B[36m${Z}\x1B[0m`,white:(Z)=>`\x1B[37m${Z}\x1B[0m`,gray:(Z)=>`\x1B[90m${Z}\x1B[0m`,bgRed:(Z)=>`\x1B[41m${Z}\x1B[0m`,bgYellow:(Z)=>`\x1B[43m${Z}\x1B[0m`,bgGray:(Z)=>`\x1B[100m${Z}\x1B[0m`,bold:(Z)=>`\x1B[1m${Z}\x1B[0m`,dim:(Z)=>`\x1B[2m${Z}\x1B[0m`,italic:(Z)=>`\x1B[3m${Z}\x1B[0m`,underline:(Z)=>`\x1B[4m${Z}\x1B[0m`,strikethrough:(Z)=>`\x1B[9m${Z}\x1B[0m`,reset:"\x1B[0m"},LZ=bZ,V4=bZ.red,v5=bZ.green,K4=bZ.yellow,y5=bZ.blue,L4=bZ.magenta,F4=bZ.cyan,SY=bZ.white,B4=bZ.gray,h5=bZ.bgRed,b5=bZ.bgYellow,R4=bZ.bgGray,NY=bZ.bold,O4=bZ.dim,E4=bZ.italic,D4=bZ.underline,I4=bZ.strikethrough,M4=bZ.reset,y7={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},f5={debug:"\uD83D\uDD0D",info:y5("\u2139"),success:v5("\u2713"),warning:b5(SY(NY(" WARN "))),error:h5(SY(NY(" ERROR ")))};w4=new c$("stacks");W8=class W8 extends Error{timestamp;context;constructor(Z,$={}){super(Z);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let Z=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Z}`}};$X=class $X extends W8{code="CONFIG_NOT_FOUND";constructor(Z,$,Y){let X=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],J="";if(X.length===1)J=` or alias "${X[0]}"`;else if(X.length>1)J=` or aliases ${X.map((G)=>`"${G}"`).join(", ")}`;super(`Configuration "${Z}"${J} not found`,{configName:Z,alias:Y,searchPaths:$,searchPathCount:$.length})}};f$=class f$ extends W8{code="CONFIG_LOAD_ERROR";constructor(Z,$,Y){super(`Failed to load configuration from "${Z}": ${$.message}`,{configPath:Z,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};YX=class YX extends W8{code="CONFIG_VALIDATION_ERROR";constructor(Z,$,Y){super(`Configuration validation failed for "${Z}"`,{configPath:Z,configName:Y,validationErrors:$,errorCount:$.length})}};XX=class XX extends W8{code="CONFIG_MERGE_ERROR";constructor(Z,$,Y,X){super(`Failed to merge configuration from "${Z}" with "${$}": ${Y.message}`,{sourcePath:Z,targetPath:$,configName:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};X0=class X0 extends W8{code="ENV_VAR_ERROR";constructor(Z,$,Y,X){super(`Failed to parse environment variable "${Z}" with value "${$}" as ${Y}`,{envKey:Z,envValue:$,expectedType:Y,configName:X})}};JX=class JX extends W8{code="FILE_SYSTEM_ERROR";constructor(Z,$,Y){super(`File system ${Z} failed for "${$}": ${Y.message}`,{operation:Z,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};GX=class GX extends W8{code="TYPE_GENERATION_ERROR";constructor(Z,$,Y){super(`Failed to generate types from "${Z}" to "${$}": ${Y.message}`,{configDir:Z,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};g$=class g$ extends W8{code="SCHEMA_VALIDATION_ERROR";constructor(Z,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:Z,configName:Y,validationErrors:$,errorCount:$.length})}};UX=class UX extends W8{code="BROWSER_CONFIG_ERROR";constructor(Z,$,Y,X){super(`Failed to fetch configuration from "${Z}": ${$} ${Y}`,{endpoint:Z,status:$,statusText:Y,configName:X})}};zX=class zX extends W8{code="PLUGIN_ERROR";constructor(Z,$,Y){super(`Plugin "${Z}" failed during ${$}: ${Y.message}`,{pluginName:Z,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};o8={configNotFound(Z,$,Y){return new $X(Z,$,Y)},configLoad(Z,$,Y){return new f$(Z,$,Y)},configValidation(Z,$,Y){return new YX(Z,$,Y)},configMerge(Z,$,Y,X){return new XX(Z,$,Y,X)},envVar(Z,$,Y,X){return new X0(Z,$,Y,X)},fileSystem(Z,$,Y){return new JX(Z,$,Y)},typeGeneration(Z,$,Y){return new GX(Z,$,Y)},schemaValidation(Z,$,Y){return new g$(Z,$,Y)},browserConfig(Z,$,Y,X){return new UX(Z,$,Y,X)},plugin(Z,$,Y){return new zX(Z,$,Y)}};i5=/^https?:\/\//;z8=new c$("bunfig",{showTags:!0});h7=new _X;T4=F8(p$.cwd(),"config"),q4=F8(p$.cwd(),"src/generated")});import LX from"process";function YZ(Z=y.dialect){return Z==="mysql"||Z==="singlestore"||Z==="vitess"}function FX(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return!1;let $=Object.getPrototypeOf(Z);return $===Object.prototype||$===null}function G0(Z,$,Y=new Set){let X={...Z};Y.add($);for(let J of Object.keys($)){if(OX.has(J))continue;let G=$[J];if(FX(G)&&!Y.has(G)){let U=X[J];X[J]=G0(FX(U)?U:{},G,Y)}else X[J]=G}return Y.delete($),X}function n$(Z){if(Z)return Z;let $=LX.env.DB_DIALECT||LX.env.DB_CONNECTION;if($)return $;return y.dialect||"postgres"}function e(Z){if(y.dialect==="postgres")return`$${Z}`;return"?"}function NZ(Z,$=1){if(Z<=0)return"";if(y.dialect==="postgres"){let Y=`$${$}`;for(let X=1;X<Z;X++)Y+=`, $${$+X}`;return Y}return Z===1?"?":`?${", ?".repeat(Z-1)}`}async function i$(){if(!u$.fileLoaded){u$.fileLoaded=!0;let Z=await VX({name:"query-builder",alias:"qb",defaultConfig:RX}),$={};for(let[Y,X]of Object.entries(Z??{}))if(!u$.explicit.has(Y))$[Y]=X;EX($)}return y}function EX(Z){let $=G0(y,Z),Y=y;for(let X of Object.keys($)){if(OX.has(X))continue;Y[X]=$[X]}}function DX(Z){if(Z.dialect&&p9&&Z.dialect!==p9){let $=`${p9}->${Z.dialect}`;if(!BX.has($))BX.add($),console.warn(`[query-builder] Configuring dialect '${Z.dialect}' overrides the previously configured dialect '${p9}'. 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(Z.dialect)p9=Z.dialect;for(let $ of Object.keys(Z))u$.explicit.add($);EX(Z)}function y4(Z){return Z}var RX,OX,s5,y,o5,u$,p9=null,BX;var qZ=A8(()=>{KX();RX={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}},OX=new Set(["__proto__","constructor","prototype"]);s5=Symbol.for("bun-query-builder.config"),y=globalThis[s5]??=G0({},RX),o5=Symbol.for("bun-query-builder.config-state"),u$=globalThis[o5]??={explicit:new Set,fileLoaded:!1};BX=new Set});function t5(){let Z=y.sqlite?.pragmas;return Array.isArray(Z)?Z:r5}function d9(Z){for(let $ of t5())try{Z.run($)}catch{}}var r5;var l$=A8(()=>{qZ();r5=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"]});var{SQL:IX}=globalThis.Bun;import{Database as e5}from"bun:sqlite";import{mkdirSync as Z6}from"fs";import{dirname as $6}from"path";import c9 from"process";function m9(Z){return Z}function a5(Z){return Z!==null&&typeof Z==="object"?Z:null}function MX(Z,$){if($.length===0||!/\$\d/.test(Z))return{sql:Z,params:$};let Y=[],X="",J=0;for(let G=0;G<Z.length;G++){let U=Z[G];if(U==="'"||U==='"'||U==="`"){let H=Y6(Z,G,U);X+=Z.slice(G,H),G=H-1;continue}if(U==="-"&&Z[G+1]==="-"){let H=Z.indexOf(`
|
|
62
|
-
`,G),z=H===-1?Z.length:H;X+=Z.slice(G,z),G=z-1;continue}if(U==="/"&&Z[G+1]==="*"){let H=Z.indexOf("*/",G+2),z=H===-1?Z.length:H+2;X+=Z.slice(G,z),G=z-1;continue}if(U==="$"){let H=/^\d+/.exec(Z.slice(G+1))?.[0];if(H){let z=Number(H);if(J=Math.max(J,z),z>=1&&z<=$.length){Y.push($[z-1]),X+="?",G+=H.length;continue}}}X+=U}if(J>$.length)throw Error(`SQL references $${J} but only ${$.length} value${$.length===1?" was":"s were"} provided`);if(Y.length===0)return{sql:Z,params:$};return{sql:X,params:Y}}function Y6(Z,$,Y){for(let X=$+1;X<Z.length;X++){if(Z[X]!==Y)continue;if(Z[X+1]===Y){X++;continue}return X+1}return Z.length}class NX{db;constructor(Z){if(Z!==":memory:"&&!Z.startsWith(":")){let $=$6(Z);if($&&$!==".")Z6($,{recursive:!0})}this.db=new e5(Z),d9(this.db)}query(Z,$=[]){let Y=MX(Z,$);return this.db.prepare(Y.sql).all(...Y.params)}run(Z,$=[]){let Y=MX(Z,$);return this.db.prepare(Y.sql).run(...Y.params)}close(){this.db.close()}get database(){return this.db}}function wX(Z){return{__raw:!0,value:Z,toString:()=>Z}}function CX(Z){let $=Z.trimStart();for(;;)if($.startsWith("--")){let Y=$.indexOf(`
|
|
63
|
-
`);$=Y===-1?"":$.slice(Y+1).trimStart()}else if($.startsWith("/*")){let Y=$.indexOf("*/");$=Y===-1?"":$.slice(Y+2).trimStart()}else return $}function X6(Z){let $=[],Y="",X=!1,J=!1,G=!1,U=!1;for(let z=0;z<Z.length;z++){let A=Z[z],W=Z[z+1];if(!X&&!J&&!U&&A==="-"&&W==="-"){G=!0,Y+=A;continue}if(G&&(A===`
|
|
64
|
-
`||A==="\r")){G=!1,Y+=A;continue}if(!X&&!J&&!G&&A==="/"&&W==="*"){U=!0,Y+=A;continue}if(U&&A==="*"&&W==="/"){U=!1,Y+=A+W,z++;continue}if(G||U){Y+=A;continue}if(A==="'"&&!J){if(X&&W==="'"){Y+=A+W,z++;continue}X=!X,Y+=A;continue}if(A==='"'&&!X){J=!J,Y+=A;continue}if(A===";"&&!X&&!J){let Q=CX(Y.trim());if(Q)$.push(Q);Y="";continue}Y+=A}let H=CX(Y.trim());if(H)$.push(H);return $}function SX(Z){let $=new NX(Z);function Y(G,...U){let H=G[0],z=[];for(let A=0;A<U.length;A++){let W=U[A],Q=a5(W);if(Q&&typeof Q.sql==="string"&&Array.isArray(Q.values))H+=Q.sql+(G[A+1]||""),z.push(...Q.values);else if(Q&&(Q.__raw||Q.raw)){let L=Q.raw,O=Q.__raw?Q.value:typeof L==="string"?L:L();H+=O+(G[A+1]||"")}else if(Array.isArray(W)){let L=W.map(()=>"?").join(", ");H+=L+(G[A+1]||""),z.push(...W)}else H+=`?${G[A+1]||""}`,z.push(W)}return{sql:H,values:z,execute:()=>{try{let A=H.trim().toUpperCase();if(A.startsWith("SELECT")||A.startsWith("PRAGMA")||/\bRETURNING\b/.test(A)){let W=$.query(H,m9(z));return Promise.resolve(W)}else{let W=$.run(H,m9(z));return Promise.resolve(W)}}catch(A){return Promise.reject(A)}},raw:()=>H,toString:()=>H,cancel:()=>{}}}function X(G,...U){if(Array.isArray(G)&&"raw"in G)return Y(G,...U);if(typeof G==="string")return wX(G);return Y([""])}X.raw=(G)=>wX(G),X.unsafe=(G,U=[])=>{let H=()=>{try{let z=G.trim().toUpperCase();if(z.startsWith("SELECT")||z.startsWith("PRAGMA")||/\bRETURNING\b/.test(z)){let A=$.query(G,m9(U));return Promise.resolve(A)}else{let A=$.run(G,m9(U));return Promise.resolve(A)}}catch(z){return Promise.reject(z)}};return{sql:G,values:U,execute:H,then:(z,A)=>H().then(z,A),raw:()=>G,toString:()=>G,cancel:()=>{}}},X.close=()=>{return $.close(),Promise.resolve()},X.query=(G,U)=>{try{let H=$.query(G,m9(U||[]));return Promise.resolve(H)}catch(H){return Promise.reject(H)}},X.file=async(G,U)=>{try{let{readFileSync:H}=await import("fs"),z=H(G,"utf-8"),A=X6(z);for(let W of A){let Q=W.trim();if(!Q||Q.startsWith("--"))continue;let L=Q.toUpperCase();if(L.startsWith("SELECT")||L.startsWith("PRAGMA"))$.query(W);else $.run(W)}return Promise.resolve([])}catch(H){return Promise.reject(H)}};let J=0;return X.begin=async(G,U)=>{let H=typeof G==="function"?G:U;if(typeof H!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let z=J>0,A=`qb_sp_${J}`;if(z)$.run(`SAVEPOINT ${A}`);else $.run("BEGIN");J++;try{let W=await H(X);if(J--,z)$.run(`RELEASE SAVEPOINT ${A}`);else $.run("COMMIT");return W}catch(W){J--;try{if(z)$.run(`ROLLBACK TO SAVEPOINT ${A}`),$.run(`RELEASE SAVEPOINT ${A}`);else $.run("ROLLBACK")}catch{}throw W}},X.savepoint=X.begin,X.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},X._wrapper=$,X}function J6(Z){let $=Z.replace(/^(?:sqlite|sqlite3|file):/i,"");if($===Z)return Z;return($.startsWith("///")?$.slice(2):$.startsWith("//")?$.slice(2):$)||":memory:"}function s$(Z=y.database){let $=c9.env.DB_DATABASE||Z?.database||"";return String($).replace(/^['"]|['"]$/g,"")}function G6(Z,$){if((Z==="postgres"||Z==="mysql"||Z==="singlestore"||Z==="vitess")&&c9.env.DB_CONNECTION===Z){let A=c9.env,W=(A.DB_DATABASE||$.database||"").replace(/^['"]|['"]$/g,""),Q=A.DB_USERNAME||$.username,L=A.DB_PASSWORD??$.password??"",O=A.DB_HOST||$.host||"localhost",T=A.DB_PORT||$.port,w=Z==="postgres"?"postgres":"mysql",K=A.DB_SSL==="true"||A.DB_SSL==="1"||$.ssl?"?ssl=true":"";return`${w}://${Q}:${L}@${O}${T?`:${T}`:""}/${W}${K}`}if($.url)return Z==="sqlite"?J6($.url):$.url;let{database:Y,username:X,password:J,host:G="localhost",port:U,ssl:H}=$,z=H||c9.env.DB_SSL==="true"||c9.env.DB_SSL==="1"?"?ssl=true":"";switch(Z){case"postgres":return`postgres://${X}:${J}@${G}${U?`:${U}`:""}/${Y}${z}`;case"mysql":case"singlestore":case"vitess":return`mysql://${X}:${J}@${G}${U?`:${U}`:""}/${Y}${z}`;case"sqlite":if(Y===":memory:")return":memory:";return Y||":memory:";default:throw Error(`Unsupported dialect: ${Z}`)}}function PX(Z){if(!Z)return{};let $={},Y=(X)=>Math.max(0,Math.round(X/1000));if(typeof Z.max==="number"&&Number.isFinite(Z.max))$.max=Z.max;if(typeof Z.idleTimeoutMs==="number"&&Number.isFinite(Z.idleTimeoutMs))$.idleTimeout=Y(Z.idleTimeoutMs);if(typeof Z.acquireTimeoutMs==="number"&&Number.isFinite(Z.acquireTimeoutMs))$.connectionTimeout=Y(Z.acquireTimeoutMs);if(typeof Z.maxLifetimeMs==="number"&&Number.isFinite(Z.maxLifetimeMs))$.maxLifetime=Y(Z.maxLifetimeMs);return $}function U6(){let Z=y.dialect,$=G6(Z,y.database);try{if(Z==="sqlite")return SX($);let Y=PX(y.database.pool);return Object.keys(Y).length>0?new IX($,Y):new IX($)}catch(Y){if(console.error(`[query-builder] Failed to create database connection for dialect '${Z}': ${Y.message}`),Z==="sqlite")return SX(":memory:");throw Y}}function z6(){let Z=y.database;return JSON.stringify({dialect:y.dialect,database:Z.database,username:Z.username,password:Z.password,host:Z.host,port:Z.port,url:Z.url,pool:PX(Z.pool)})}function f8(Z=!1){let $=z6();if(Z||t8!==null&&U0!==$||!t8){if(t8)TX();t8=U6(),U0=$}return t8}function H6(){let Z=t8;return t8=null,U0=null,Z}async function A6(Z){if(!Z||typeof Z.close!=="function")return;await Z.close()}function TX(){A6(H6()).catch(($)=>{console.error(`[query-builder] Failed to close database connection: ${$.message}`)})}async function z0(Z){try{return await Z(f8())}catch($){if($?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||$?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let Y=f8(!0);return await Z(Y)}throw $}}function W6(){return new Proxy(function(){},{get(Z,$){let Y=f8(),X=Y[$];if(typeof X==="function")return X.bind(Y);return X},apply(Z,$,Y){return f8()(...Y)}})}var t8=null,U0=null,$Z;var g8=A8(()=>{qZ();l$();$Z=W6()});function O9(Z){return Z==="integer"||Z==="bigint"||Z==="float"||Z==="double"||Z==="decimal"}function qX(Z){if(typeof Z!=="string")return;switch(Z.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function a$(Z){switch(Z){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}var H0=()=>{};function A0(Z){let $=String(Z).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if($.endsWith("y")&&!/[aeou]y$/.test($))return`${$.slice(0,-1)}ies`;if($.endsWith("s")||$.endsWith("x")||$.endsWith("ch")||$.endsWith("sh"))return`${$}es`;return`${$}s`}function p8(Z){return typeof Z?.table==="string"&&Z.table.length>0?Z.table:A0(String(Z?.name??""))}function V6(Z){return Z.endsWith("s")?Z.slice(0,-1):Z}function K6(Z){if(Z.endsWith("ies")&&Z.length>3){let $=Z.slice(0,-3),Y=$[$.length-1];if(Y&&!"aeiou".includes(Y))return`${$}y`}if(Z.endsWith("es")&&Z.length>2){let $=Z.slice(0,-2);if($.endsWith("s")||$.endsWith("x")||$.endsWith("ch")||$.endsWith("sh"))return $}if(Z.endsWith("s")&&!Z.endsWith("ss")&&!Z.endsWith("us")&&!Z.endsWith("is"))return Z.slice(0,-1);return Z}function d8(Z){if(Z==="none")return($)=>$;if(Z==="inflect")return K6;return V6}var m8=()=>{};function Z9(Z){if(Z.length===0)return"";let $=[];for(let Y of Z)if(Y.conn==="OR"&&$.length>0)$[$.length-1].push(Y);else $.push([Y]);return $.map((Y,X)=>{let J=Y.map((U)=>U.sql).join(" OR "),G=Y.length>1&&$.length>1?`(${J})`:J;return X===0?G:`${Y[0].conn} ${G}`}).join(" ")}function rZ(Z,$,Y,X){if($.length===0)return Y?"1 = 1":"1 = 0";return`${Z} ${Y?"NOT IN":"IN"} (${X})`}function F6(Z,$){if($!=="postgres")return Z;let Y="",X=0,J=0;while(J<Z.length){let G=Z[J];if(G==="'"){let U=kX(Z,J,"'");Y+=Z.slice(J,U),J=U;continue}if(G==='"'){let U=kX(Z,J,'"');Y+=Z.slice(J,U),J=U;continue}if(G==="$"){let U=Z.slice(J).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(U){let H=Z.indexOf(U,J+U.length),z=H===-1?Z.length:H+U.length;Y+=Z.slice(J,z),J=z;continue}}if(G==="?"){X++,Y+=`$${X}`,J++;continue}Y+=G,J++}return Y}function kX(Z,$,Y){let X=$+1;while(X<Z.length){if(Z[X]===Y){if(Z[X+1]===Y){X+=2;continue}return X+1}X++}return Z.length}var xX="1 = 0";var Z7=()=>{};function D9(Z){if(typeof Z==="number")return{length:Z};return Z}function O0(Z){if(typeof Z==="number")return{max:Z};return Z}function cU(Z){return typeof Z==="function"}function uU(Z){return Z.replace(/[A-Z]/g,($)=>$.toLowerCase())}function F1(Z,$){if(!$||typeof $.fractionDigits!=="number")return Z;return Number(Z.toFixed($.fractionDigits))}function u8(Z,$={}){if(!Z)return $;return new Proxy(Z,{get(Y,X){if(X in $)return $[X];let J=Y[X];if(J!==void 0)return J;let G=Y[uU(X)];if(cU(G))return G.bind(Y);return}})}function B1(Z){let $=(W)=>{let Q=Array.isArray(W)?W:[],L=Math.floor(Math.random()*Q.length);return Q[L]},Y=()=>Z.string,X=()=>Z.number,J=()=>Z.random,G=u8(Z.string,{alpha:(W)=>Y()?.alpha?.(D9(W)),alphanumeric:(W)=>Y()?.alphanumeric?.(D9(W)),numeric:(W)=>Y()?.numeric?.(D9(W)),sample:(W)=>Y()?.sample?.(D9(W)),hexadecimal:(W)=>Y()?.hexadecimal?.(D9(W))}),U=u8(Z.number,{int:(W)=>X()?.int?.(O0(W)),float:(W)=>{let Q=O0(W);return F1(Number(X()?.float?.(Q)??0),Q)}}),H=u8(Z.helpers,{arrayElement:$,arrayElements:(W,Q)=>{let L=[...Array.isArray(W)?W:[]],O=typeof Q==="number"?Q:Math.max(1,Math.floor(Math.random()*L.length));for(let T=L.length-1;T>0;T-=1){let w=Math.floor(Math.random()*(T+1));[L[T],L[w]]=[L[w],L[T]]}return L.slice(0,Math.min(O,L.length))},shuffle:(W)=>{let Q=[...Array.isArray(W)?W:[]];for(let L=Q.length-1;L>0;L-=1){let O=Math.floor(Math.random()*(L+1));[Q[L],Q[O]]=[Q[O],Q[L]]}return Q},maybe:(W,Q)=>{let L=typeof Q?.probability==="number"?Q.probability:0.5;return Math.random()<L?W():void 0},slugify:(W)=>String(W??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),A={string:G,number:U,helpers:H,datatype:{boolean:(W)=>{let Q=typeof W==="number"?W:W?.probability;if(typeof Q==="number")return Math.random()<Q;return Boolean(J()?.boolean?.())},number:(W)=>Number(X()?.int?.(O0(W))??0),float:(W)=>F1(Number(X()?.float?.(W)??0),W),uuid:()=>crypto.randomUUID(),string:(W)=>String(Y()?.alphanumeric?.({length:W??10})??""),hexadecimal:(W)=>String(Y()?.hexadecimal?.(D9(W))??""),array:(W)=>Array.from({length:W??3},()=>Y()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:Y()?.alphanumeric?.({length:8})})},location:u8(Z.address),address:u8(Z.address),vehicle:u8(Z.vehicle,{vrm:()=>Z.vehicle?.registration?.()}),company:u8(Z.company,{catchPhrase:()=>Z.company?.catchphrase?.(),buzzPhrase:()=>Z.company?.bs?.()??Z.company?.buzzword?.()})};return new Proxy(Z,{get(W,Q){if(Q in A)return A[Q];let L=W[Q];if(L&&typeof L==="object")return u8(L);return L}})}var E0=()=>{};function H7(Z){if(typeof Z==="string")return{model:Z};if(Z&&typeof Z==="object"&&typeof Z.model==="string"){let $=Z;return{model:$.model,foreignKey:$.foreignKey,onDelete:$.onDelete}}return null}function I9(Z){if(!Z)return[];return(Array.isArray(Z)?Z:typeof Z==="object"?Object.values(Z):[]).map(H7).filter((Y)=>Y!==null)}var A7=()=>{};import{Database as C0}from"bun:sqlite";function J9(){let Z=new Date().toISOString();return YZ(y.dialect)?Z.slice(0,19).replace("T"," "):Z}function q8(Z,$){if(typeof Z!=="string"||Z.length===0)throw TypeError(`[bun-query-builder] ${$}: identifier must be a non-empty string, got ${typeof Z}`);if(Z.length>64)throw TypeError(`[bun-query-builder] ${$}: identifier '${Z}' exceeds 64 chars`);if(!C1.test(Z))throw TypeError(`[bun-query-builder] ${$}: identifier '${Z}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function S1(Z,$){if(typeof Z!=="string"||Z.length===0)throw TypeError(`[bun-query-builder] ${$}: identifier must be a non-empty string, got ${typeof Z}`);let Y=Z.split(".");if(Y.length>2||Y.some((X)=>X.length===0||X.length>64||!C1.test(X)))throw TypeError(`[bun-query-builder] ${$}: invalid ORDER BY column '${Z}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function iU(Z,$){N0.set(Z,$),M9.clear()}function N1(){N0.clear(),M9.clear()}function Z8(Z){if(!W7)try{W7=(e9(),nU(v1)).getModel}catch{W7=()=>{return}}return W7(Z)??N0.get(Z)}function R1(Z){let $=j7.get(Z);if($!==void 0)return $;let Y=0,X=Z.replace(/\?/g,()=>`$${++Y}`);if(j7.size>=lU)j7.clear();return j7.set(Z,X),X}function O1(Z){if(Z==null)return 0;if(typeof Z.affectedRows==="number")return Z.affectedRows;if(typeof Z.count==="number")return Z.count;if(Array.isArray(Z))return Z.length;return 0}function E1(Z){if(Z==null||typeof Z!=="object")return null;if("insertId"in Z&&Z.insertId!=null)return Z.insertId;if("lastInsertRowid"in Z&&Z.lastInsertRowid!=null)return Z.lastInsertRowid;return null}class S0{sqliteDb;dialect="sqlite";constructor(Z){this.sqliteDb=Z}all(Z,$){return Promise.resolve(this.sqliteDb.query(Z).all(...$))}get(Z,$){return Promise.resolve(this.sqliteDb.query(Z).get(...$)??void 0)}run(Z,$){let Y=this.sqliteDb.run(Z,$);return Promise.resolve({changes:Y.changes,lastInsertId:Y.lastInsertRowid})}insert(Z,$){return this.run(Z,$)}}class P1{dialect;constructor(Z){this.dialect=Z}conn(){return f8()}text(Z){return this.dialect==="postgres"?R1(Z):Z}async all(Z,$){let Y=await this.conn().unsafe(this.text(Z),$);return Array.isArray(Y)?Y:[]}async get(Z,$){let Y=await this.conn().unsafe(this.text(Z),$);if(Array.isArray(Y))return Y[0]??void 0;return Y??void 0}async run(Z,$){let Y=await this.conn().unsafe(this.text(Z),$);return{changes:O1(Y),lastInsertId:E1(Y)}}async insert(Z,$,Y){if(this.dialect==="postgres"){let G=await this.conn().unsafe(`${R1(Z)} RETURNING ${Y}`,$),U=Array.isArray(G)?G[0]:G;return{changes:1,lastInsertId:U?U[Y]??null:null}}let X=await this.conn().unsafe(Z,$),J=E1(X);if(J==null){let G=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);J=(Array.isArray(G)?G[0]:G)?.id??null}return{changes:O1(X)||1,lastInsertId:J}}}function Z3(Z){if(Z.database instanceof C0)X9=Z.database;else X9=new C0(Z.database||":memory:",{create:!0}),d9(X9);k8=null,a9=null}function OZ(){if(X9){if(!k8||a9!==X9)k8=new S0(X9),a9=X9,D0="sqlite",I0=null;return k8}let Z=y.dialect,$=y.database?.database??null;if(k8&&a9===null&&D0===Z&&I0===$)return k8;if(a9=null,D0=Z,I0=$,Z==="sqlite"){let Y=new C0($||":memory:",{create:!0});d9(Y),k8=new S0(Y)}else k8=new P1(Z);return k8}function $3(){let Z=OZ();if(Z.sqliteDb)return Z.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${Z.dialect}'. Use the async model API instead.`)}function w9(Z){let $=Z.traits;return Boolean($?.useSoftDeletes||$?.softDeletable)}function G9(Z){let $=Z.traits;return Boolean($?.useTimestamps||$?.timestampable)}function sU(Z){let $=D1.get(Z);if($)return $;let Y=new Set,X=Z.belongsToMany;if(X){if(Array.isArray(X)){for(let J of X)if(typeof J==="string")Y.add(J.toLowerCase());else if(J&&typeof J==="object"&&J.model)Y.add(J.model.toLowerCase())}else if(typeof X==="object")for(let J of Object.keys(X))Y.add(J)}return D1.set(Z,Y),Y}function T1(Z){let $={};for(let[Y,X]of Object.entries(Z))$[DZ(Y)]=X;return $}function oU(Z){for(let $ in Z)if(DZ($)!==$)return T1(Z);return Z}function rU(Z,$){if(Z[$])return Z[$];let Y=DZ($);if(Z[Y])return Z[Y];for(let X of Object.keys(Z))if(DZ(X)===Y)return Z[X];return}class aZ{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_relations={};constructor(Z,$={}){this._definition=Z,this._attributes=oU({...$}),this._original=null;let Y=sU(Z);if(Y.size===0)return;let X=this;return new Proxy(this,{get(J,G,U){if(typeof G==="string"&&Y.has(G)&&!(G in J))return()=>{let H=q1(Z,G);if(!H||H.type!=="belongsToMany")throw Error(`[orm] relation '${G}' did not resolve to a belongsToMany on '${Z.name}'`);let z=Z8(H.relatedModelName),A=z?.getDefinition?.()||z?.definition;if(!A)throw Error(`[orm] related model '${H.relatedModelName}' is not registered`);return new k1(X,Z,H,A)};return Reflect.get(J,G,U)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(Z){let $=this._definition.get?.[Z];if($)try{let Y=$(this._attributes);if(Y!==void 0)return Y}catch{}return this._attributes[DZ(Z)]}getAttribute(Z){return this._attributes[DZ(Z)]}getAttributes(){return{...this._attributes}}set(Z,$){if(this._original===null)this._original={...this._attributes};this._attributes[DZ(Z)]=$}only(Z){let $={};for(let Y of Z)$[Y]=this._attributes[DZ(Y)];return $}except(Z){let $=new Set(Z.map((X)=>DZ(X))),Y={};for(let X of Object.keys(this._attributes))if(!$.has(X))Y[X]=this._attributes[X];return Y}getRelation(Z){return this._relations[Z]}setRelation(Z,$){this._relations[Z]=$}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let Z=this._definition.primaryKey||"id";return this._attributes[Z]}isDirty(Z){if(this._original===null)return!1;if(Z){let $=DZ(Z);return this._attributes[$]!==this._original[$]}return Object.keys(this._attributes).some(($)=>this._attributes[$]!==this._original[$])}isClean(Z){return!this.isDirty(Z)}getOriginal(Z){return this.getOriginalAttributes()[DZ(Z)]}getChanges(){if(this._original===null)return{};let Z={};for(let $ of Object.keys(this._attributes))if(this._attributes[$]!==this._original[$])Z[$]=this._attributes[$];return Z}fill(Z){let $=this._definition.attributes;for(let[Y,X]of Object.entries(Z)){let J=rU($,Y),G=!J&&DZ(Y).endsWith("_id");if(J?.fillable&&!J?.guarded||G){if(this._original===null)this._original={...this._attributes};this._attributes[DZ(Y)]=X}}return this}forceFill(Z){if(this._original===null)this._original={...this._attributes};let $=T1(Z);Object.assign(this._attributes,$);for(let Y of Object.keys($))this._forced.add(Y);return this}async save(){let Z=OZ(),$=this._definition.primaryKey||"id",Y=this._definition.hooks,X=this._definition.set||{};for(let[J,G]of Object.entries(X))if(this.isDirty(J))this._attributes[DZ(J)]=G(this._attributes);if(this._attributes[$]){await Y?.beforeUpdate?.(this,this.getChanges());let J=this.getChanges(),G=Object.keys(J);if(G.length>0){let U=G.map((z)=>`${z} = ?`).join(", "),H=[...Object.values(J),this._attributes[$]];if(G9(this._definition)){let z=J9();await Z.run(`UPDATE ${this._definition.table} SET ${U}, updated_at = ? WHERE ${$} = ?`,[...Object.values(J),z,this._attributes[$]])}else await Z.run(`UPDATE ${this._definition.table} SET ${U} WHERE ${$} = ?`,H)}await Y?.afterUpdate?.(this)}else{let J=this._definition.attributes,G={};for(let[A,W]of Object.entries(J)){if(W.guarded&&!this._forced.has(DZ(A)))continue;let Q=DZ(A);if(this._attributes[Q]!==void 0)G[Q]=this._attributes[Q]}for(let A of Object.keys(this._attributes))if(A.endsWith("_id")&&A!==$&&!(A in G))G[A]=this._attributes[A];if(G9(this._definition)){let A=J9();G.created_at=A,G.updated_at=A}if(this._definition.traits?.useUuid&&!G.uuid)G.uuid=crypto.randomUUID();await Y?.beforeCreate?.(G);let U=Object.keys(G),H=U.map(()=>"?").join(", "),z=await Z.insert(`INSERT INTO ${this._definition.table} (${U.join(", ")}) VALUES (${H})`,Object.values(G),$);for(let[A,W]of Object.entries(G))this._attributes[A]=W;if(z.lastInsertId!=null)this._attributes[$]=z.lastInsertId;await Y?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update(Z){return this.fill(Z),this.save()}async fresh(){let Z=OZ(),$=this._definition.primaryKey||"id",Y=this._attributes[$];if(Y==null)return null;let X=await Z.get(`SELECT * FROM ${this._definition.table} WHERE ${$} = ?`,[Y]);if(!X)return null;return new aZ(this._definition,X)}async delete(){let Z=OZ(),$=this._definition.primaryKey||"id",Y=this._attributes[$],X=this._definition.hooks;if(!Y)throw Error("Cannot delete a model without a primary key");if(await X?.beforeDelete?.(this),w9(this._definition)){let J=J9();await Z.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${$} = ?`,[J,Y]),this._attributes[n8]=J}else await Z.run(`DELETE FROM ${this._definition.table} WHERE ${$} = ?`,[Y]);return await X?.afterDelete?.(this),!0}async restore(){if(!w9(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let Z=this._definition.primaryKey||"id",$=this._attributes[Z];if(!$)throw Error("Cannot restore a model without a primary key");return await OZ().run(`UPDATE ${this._definition.table} SET ${n8} = ? WHERE ${Z} = ?`,[null,$]),this._attributes[n8]=null,this._original=null,this}trashed(){return this._attributes[n8]!=null}async refresh(){let Z=OZ(),$=this._definition.primaryKey||"id",Y=this._attributes[$];if(!Y)throw Error("Cannot refresh a model without a primary key");let X=await Z.get(`SELECT * FROM ${this._definition.table} WHERE ${$} = ?`,[Y]);if(!X)return null;return this._attributes=X,this._original=null,this}replicate(){let Z=this._definition.primaryKey||"id",$={...this._attributes};return delete $[Z],delete $.uuid,delete $.created_at,delete $.updated_at,new aZ(this._definition,$)}toArray(){let Z={...this._attributes};for(let[$,Y]of Object.entries(this._relations))if(Array.isArray(Y))Z[$]=Y.map((X)=>X.toArray());else if(Y)Z[$]=Y.toArray();else Z[$]=null;return Z}toJSON(){let Z=new Set;for(let[Y,X]of Object.entries(this._definition.attributes))if(X.hidden)Z.add(Y);let $={};for(let[Y,X]of Object.entries(this._attributes))if(!Z.has(Y))$[Y]=X;for(let[Y,X]of Object.entries(this._relations))if(Array.isArray(X))$[Y]=X.map((J)=>J.toJSON());else if(X)$[Y]=X.toJSON();else $[Y]=null;return $}}function _8(Z){return DZ(Z)}function DZ(Z){let $=I1.get(Z);if($!==void 0)return $;return $=Z.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),I1.set(Z,$),$}function Y9(Z){let $=M1.get(Z);if($!==void 0)return $;return $=A0(Z),M1.set(Z,$),$}function w1(Z,$){let Y=Z[$];if(!Y)return[];if(Array.isArray(Y))return Y.map((X)=>typeof X==="string"?X:String(X?.model??"")).filter(Boolean);if(typeof Y==="object")return Object.keys(Y);if(typeof Y==="string")return[Y];return[]}function eU(Z,$){let Y=Z.name??Z.table??"model",J=aU.filter((U)=>w1(Z,U).some((H)=>H.toLowerCase()===$.toLowerCase())).filter((U)=>!Q7.includes(U));if(J.length>0)return`[orm] '${Y}' declares '${$}' as ${J.join("/")}, which eager loading does not support yet. Supported kinds: ${Q7.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let G=Q7.flatMap((U)=>w1(Z,U));return G.length>0?`[orm] '${Y}' has no relation '${$}'. Available: ${G.join(", ")}.`:`[orm] '${Y}' has no relation '${$}' \u2014 it declares no relations at all.`}function q1(Z,$){let{name:Y,table:X}=Z,J=Z.primaryKey||"id";function G(w){if(!w)return null;if(Array.isArray(w)){for(let K of w){let B=typeof K==="string"?K:K?.model||"";if(B&&B.toLowerCase()===$.toLowerCase())return B}return null}if(typeof w==="object"){for(let[K,B]of Object.entries(w))if(K===$||K.toLowerCase()===$.toLowerCase())return typeof B==="string"?B:B?.model||B?.target||K}return null}function U(){let w=Z.belongsTo;if(!w)return null;let K=$.toLowerCase(),B=(V)=>{if(typeof V==="string")return{model:V};if(V&&typeof V==="object"&&typeof V.model==="string")return{model:V.model,foreignKey:V.foreignKey};return null};if(Array.isArray(w)){for(let V of w){let F=B(V);if(F&&F.model.toLowerCase()===K)return F}return null}if(typeof w==="object"){for(let[V,F]of Object.entries(w))if(V===$||V.toLowerCase()===K)return B(F)}return null}function H(){let w=Z.belongsToMany;if(!w)return null;if(Array.isArray(w)){for(let K of w)if(typeof K==="string"){if(K.toLowerCase()===$.toLowerCase())return{entry:K}}else if(K&&typeof K==="object"&&K.model){if(K.model.toLowerCase()===$.toLowerCase())return{entry:K}}return null}if(typeof w==="object"){for(let[K,B]of Object.entries(w))if(K===$||K.toLowerCase()===$.toLowerCase())return{entry:B}}return null}let z=G(Z.hasMany);if(z){let K=Z8(z)?.getTable?.()||Y9(z),B=DZ(Y)+"_id";return{type:"hasMany",relatedModelName:z,relatedTable:K,foreignKey:B,localKey:J}}let A=G(Z.hasOne);if(A){let K=Z8(A)?.getTable?.()||Y9(A),B=DZ(Y)+"_id";return{type:"hasOne",relatedModelName:A,relatedTable:K,foreignKey:B,localKey:J}}let W=U();if(W){let w=W.model,K=Z8(w),B=K?.getTable?.()||Y9(w),V=K?.getDefinition?.()?.primaryKey||"id",F=W.foreignKey||`${DZ(w)}_id`;return{type:"belongsTo",relatedModelName:w,relatedTable:B,foreignKey:F,localKey:V}}let Q=H();if(Q){let w=typeof Q.entry==="object",K=w?Q.entry.model:Q.entry,V=Z8(K)?.getTable?.()||Y9(K),F=w?Q.entry:null,I,E;if(F?.table)I=F.table;else if(F?.through){E=F.through;let P=Z8(F.through);if(!P)throw Error(`[orm] belongsToMany relation '${$}' on '${Y}' references unknown through model '${F.through}'. Make sure '${F.through}' is registered.`);I=P.getTable?.()||P.getDefinition?.()?.table||Y9(F.through)}else{let P=t9(X),M=t9(V);I=[P,M].sort().join("_")}let n=F?.foreignKey||`${t9(X)}_id`,x=F?.relatedKey||`${t9(V)}_id`,d=[];if(F?.pivot?.columns)for(let P of Object.keys(F.pivot.columns))d.push(P);if(E){let P=Z8(E),M=P?.getDefinition?.()||P?.definition,S=M?.attributes??{},C=M?.primaryKey??"id";for(let v of Object.keys(S)){if(v===n||v===x||v===C)continue;if(!d.includes(v))d.push(v)}}return{type:"belongsToMany",relatedModelName:K,relatedTable:V,foreignKey:n,localKey:J,pivotTable:I,pivotFkParent:n,pivotFkRelated:x,pivotColumns:d,pivotModelName:E,pivotTimestamps:Boolean(F?.pivot?.timestamps)}}let L=(w,K)=>{if(!w||typeof w!=="object"||Array.isArray(w))return null;let B=w[$]??w[Object.keys(w).find((M)=>M.toLowerCase()===$.toLowerCase())??""];if(!B||typeof B!=="object")return null;let{through:V,target:F}=B;if(!V||!F)return null;let I=Z8(V),E=I?.getDefinition?.()||I?.definition,n=I?.getTable?.()||E?.table||Y9(V),x=E?.primaryKey||"id",P=Z8(F)?.getTable?.()||Y9(F);return{type:K,relatedModelName:F,relatedTable:P,foreignKey:`${DZ(Y)}_id`,localKey:J,throughTable:n,throughForeignKey:`${DZ(Y)}_id`,throughLocalKey:x,targetForeignKey:`${t9(n)}_id`}},O=L(Z.hasManyThrough,"hasManyThrough");if(O)return O;let T=L(Z.hasOneThrough,"hasOneThrough");if(T)return T;return null}function w0(Z,$){let Y=new Set;for(let X of Z){let J=X.get($);if(J!=null)Y.add(J)}return[...Y]}function t9(Z){return d8(y.relations?.singularizeStrategy)(Z)}class k1{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(Z,$,Y,X){this._parent=Z,this._parentDef=$,this._resolved=Y,this._relatedDef=X}get parentId(){let Z=this._parentDef.primaryKey||"id";return this._parent.get(Z)}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(Z,$,Y){if(Y===void 0)this._wheres.push({sql:`${this.relatedTable}.${Z} = ?`,params:[$]});else this._wheres.push({sql:`${this.relatedTable}.${Z} ${String($)} ?`,params:[Y]});return this}wherePivot(Z,$,Y){if(Y===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${Z} = ?`,params:[$]});else this._pivotWheres.push({sql:`${this.pivotTable}.${Z} ${String($)} ?`,params:[Y]});return this}wherePivotIn(Z,$){if(!$.length)return this;let Y=$.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${Z} IN (${Y})`,params:[...$]}),this}wherePivotNotIn(Z,$){if(!$.length)return this;let Y=$.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${Z} NOT IN (${Y})`,params:[...$]}),this}wherePivotNull(Z){return this._pivotWheres.push({sql:`${this.pivotTable}.${Z} IS NULL`,params:[]}),this}wherePivotNotNull(Z){return this._pivotWheres.push({sql:`${this.pivotTable}.${Z} IS NOT NULL`,params:[]}),this}orderBy(Z,$="asc"){if(S1(Z,"orderBy(column)"),$!=="asc"&&$!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${$}'`);return this._orderBy.push(`${Z} ${$.toUpperCase()}`),this}limit(Z){if(!Number.isFinite(Z)||Z<0||!Number.isInteger(Z))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${Z}`);return this._limit=Z,this}offset(Z){if(!Number.isFinite(Z)||Z<0||!Number.isInteger(Z))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${Z}`);return this._offset=Z,this}relatedSelectColumns(){let Z=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),$=this._relatedDef.traits;if($?.useTimestamps||$?.timestampable)Z.add("created_at"),Z.add("updated_at");if($?.useSoftDeletes||$?.softDeletable)Z.add("deleted_at");if($?.useUuid)Z.add("uuid");return[...Z]}buildSelect(){let Z=[],Y=`SELECT ${this.relatedSelectColumns().map((X)=>`${this.relatedTable}.${X} AS ${M0}${X}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;Y+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,Y+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,Z.push(this.parentId);for(let X of this._pivotWheres)Y+=` AND ${X.sql}`,Z.push(...X.params);for(let X of this._wheres)Y+=` AND ${X.sql}`,Z.push(...X.params);if(this._orderBy.length>0)Y+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)Y+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Y+=` OFFSET ${this._offset}`;return{sql:Y,params:Z}}hydrateRows(Z){let $=this.fkParent,Y=this.fkRelated;return Z.map((X)=>{let J={},G={};for(let[H,z]of Object.entries(X))if(H.startsWith(M0))J[H.slice(M0.length)]=z;else if(H!==$&&H!==Y)G[H]=z;let U=new aZ(this._relatedDef,J);return U.pivot=G,U})}async get(){let Z=OZ(),{sql:$,params:Y}=this.buildSelect(),X=await Z.all($,Y);return this.hydrateRows(X)}async first(){return this._limit=1,(await this.get())[0]}async count(){let Z=OZ(),$=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,Y=[this.parentId];for(let J of this._pivotWheres)$+=` AND ${J.sql}`,Y.push(...J.params);let X=await Z.get($,Y);return Number(X?.count??0)}async exists(){return await this.count()>0}now(){return J9()}async attach(Z,$={}){let Y=OZ(),X=Array.isArray(Z)?Z:[Z];if(X.length===0)return 0;let J=this._resolved.pivotTimestamps?this.now():null,G=0;for(let U of X){let H={[this.fkParent]:this.parentId,[this.fkRelated]:U,...$};if(J){if(H.created_at===void 0)H.created_at=J;if(H.updated_at===void 0)H.updated_at=J}let z=Object.keys(H),A=z.map(()=>"?").join(", "),W=`INSERT INTO ${this.pivotTable} (${z.join(", ")}) VALUES (${A})`,Q=z.map((L)=>H[L]);await Y.run(W,Q),G++}return G}async detach(Z){let $=OZ(),Y=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,X=[this.parentId];if(Z!==void 0&&Z!==null){let J=Array.isArray(Z)?Z:[Z];if(J.length===0)return 0;let G=J.map(()=>"?").join(", ");Y+=` AND ${this.fkRelated} IN (${G})`,X.push(...J)}return(await $.run(Y,X)).changes}async updateExistingPivot(Z,$){let Y=OZ(),X={...$};if(this._resolved.pivotTimestamps&&X.updated_at===void 0)X.updated_at=this.now();let J=Object.keys(X);if(J.length===0)return 0;let G=J.map((z)=>`${z} = ?`).join(", "),U=`UPDATE ${this.pivotTable} SET ${G} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,H=[...J.map((z)=>X[z]),this.parentId,Z];return(await Y.run(U,H)).changes}async sync(Z){let $=OZ(),Y=new Map;for(let A of Z)if(A!=null&&typeof A==="object"&&"id"in A){let{id:W,...Q}=A;Y.set(W,Q)}else Y.set(A,{});let X=await $.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),J=new Set(X.map((A)=>A[this.fkRelated])),G=[],U=[],H=[],z=[...J].filter((A)=>!Y.has(A));if(z.length>0)await this.detach(z),U.push(...z);for(let[A,W]of Y)if(!J.has(A))await this.attach(A,W),G.push(A);else if(Object.keys(W).length>0)await this.updateExistingPivot(A,W),H.push(A);return{attached:G,detached:U,updated:H}}async toggle(Z){let $=OZ(),Y=Array.isArray(Z)?Z:[Z];if(Y.length===0)return{attached:[],detached:[]};let X=Y.map(()=>"?").join(", "),J=await $.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${X})`,[this.parentId,...Y]),G=new Set(J.map((z)=>z[this.fkRelated])),U=Y.filter((z)=>!G.has(z)),H=Y.filter((z)=>G.has(z));if(U.length>0)await this.attach(U);if(H.length>0)await this.detach(H);return{attached:U,detached:H}}}class WZ{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(Z){this._definition=Z}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(Z,$,Y){if(Y===void 0)this._wheres.push({column:Z,operator:"=",value:$,boolean:"and"});else this._wheres.push({column:Z,operator:$,value:Y,boolean:"and"});return this}orWhere(Z,$,Y){if(Y===void 0)this._wheres.push({column:Z,operator:"=",value:$,boolean:"or"});else this._wheres.push({column:Z,operator:$,value:Y,boolean:"or"});return this}whereIn(Z,$){return this._wheres.push({column:Z,operator:"in",value:$,boolean:"and"}),this}orWhereIn(Z,$){return this._wheres.push({column:Z,operator:"in",value:$,boolean:"or"}),this}whereNotIn(Z,$){return this._wheres.push({column:Z,operator:"not in",value:$,boolean:"and"}),this}orWhereNotIn(Z,$){return this._wheres.push({column:Z,operator:"not in",value:$,boolean:"or"}),this}whereNull(Z){return q8(Z,"whereNull(column)"),this._wheres.push({column:Z,operator:"=",value:null,boolean:"and"}),this}orWhereNull(Z){return q8(Z,"orWhereNull(column)"),this._wheres.push({column:Z,operator:"=",value:null,boolean:"or"}),this}whereNotNull(Z){return q8(Z,"whereNotNull(column)"),this._wheres.push({column:Z,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(Z){return q8(Z,"orWhereNotNull(column)"),this._wheres.push({column:Z,operator:"!=",value:null,boolean:"or"}),this}whereLike(Z,$){return this._wheres.push({column:Z,operator:"like",value:$,boolean:"and"}),this}orWhereLike(Z,$){return this._wheres.push({column:Z,operator:"like",value:$,boolean:"or"}),this}whereNotLike(Z,$){return this._wheres.push({column:Z,operator:"not like",value:$,boolean:"and"}),this}orWhereNotLike(Z,$){return this._wheres.push({column:Z,operator:"not like",value:$,boolean:"or"}),this}whereRaw(Z,...$){return this._wheres.push({raw:Z,rawParams:$,boolean:"and"}),this}orWhereRaw(Z,...$){return this._wheres.push({raw:Z,rawParams:$,boolean:"or"}),this}whereGroup(Z){return this._addGroup("and",Z)}orWhereGroup(Z){return this._addGroup("or",Z)}_addGroup(Z,$){let Y=new WZ(this._definition);if($(Y),Y._wheres.length===0)return this;let X=[],J=Y.buildWhereClauses(X);if(!J)return this;return this._wheres.push({raw:`(${J})`,rawParams:X,boolean:Z}),this}whereBetween(Z,$){return q8(Z,"whereBetween(column)"),this._wheres.push({column:Z,operator:">=",value:$[0],boolean:"and"}),this._wheres.push({column:Z,operator:"<=",value:$[1],boolean:"and"}),this}whereNotBetween(Z,$){q8(Z,"whereNotBetween(column)");let Y=_8(Z);return this._wheres.push({raw:`(${Y} < ? OR ${Y} > ?)`,rawParams:[$[0],$[1]],boolean:"and"}),this}when(Z,$){if(Z)return $(this);return this}orderBy(Z,$="asc"){if(S1(Z,"orderBy(column)"),$!=="asc"&&$!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${$}'`);return this._orderBy.push({column:Z,direction:$}),this}orderByDesc(Z){return this.orderBy(Z,"desc")}orderByAsc(Z){return this.orderBy(Z,"asc")}limit(Z){return this._limit=Z,this}take(Z){return this.limit(Z)}offset(Z){return this._offset=Z,this}skip(Z){return this.offset(Z)}select(...Z){return this._select=Z,this}with(...Z){for(let $ of Z)if(!this._withRelations.includes($))this._withRelations.push($);return this}getWithRelations(){return this._withRelations}buildWhereClauses(Z){let $=[];for(let Y of this._wheres){let X;if(Y.raw){if(X=Y.raw,Y.rawParams&&Y.rawParams.length>0)Z.push(...Y.rawParams)}else if(Y.value===null){let J=_8(Y.column);X=Y.operator==="="?`${J} IS NULL`:`${J} IS NOT NULL`}else if(Y.operator==="in"||Y.operator==="not in"){let J=Y.value;X=rZ(_8(Y.column),J,Y.operator==="not in",J.map(()=>"?").join(", ")),Z.push(...J)}else X=`${_8(Y.column)} ${Y.operator} ?`,Z.push(Y.value);$.push({conn:Y.boolean==="or"?"OR":"AND",sql:X})}return Z9($)}softDeleteClause(){if(this._trashed==="include"||!w9(this._definition))return"";return this._trashed==="only"?`${n8} IS NOT NULL`:`${n8} IS NULL`}assertNoUnappliedClauses(Z){let $=[];if(this._limit!==void 0)$.push("limit()");if(this._offset!==void 0)$.push("offset()");if(this._orderBy.length>0)$.push("orderBy()");if($.length>0)throw TypeError(`[orm] ${Z}() cannot apply ${$.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(Z){let $=this._wheres.length>0?this.buildWhereClauses(Z):"",Y=this.softDeleteClause();if($&&Y)return`(${$}) AND ${Y}`;return $||Y}buildQuery(){let Z=[],Y=`SELECT ${this._select.map((J)=>J==="*"?J:_8(J)).join(", ")} FROM ${this._definition.table}`,X=this.composeWhere(Z);if(X)Y+=` WHERE ${X}`;if(this._orderBy.length>0)Y+=` ORDER BY ${this._orderBy.map((J)=>`${_8(J.column)} ${J.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)Y+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Y+=` OFFSET ${this._offset}`;return{sql:Y,params:Z}}toSql(){return this.buildQuery()}async eagerLoadRelations(Z){if(Z.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map(($)=>this.eagerLoadRelation($,Z)))}async eagerLoadRelation(Z,$){let Y=OZ(),X=this._definition.primaryKey||"id",J=`${this._definition.name}:${Z}`,G=M9.get(J);if(G===void 0){if(G=q1(this._definition,Z),M9.size>=tU)M9.clear();M9.set(J,G)}if(!G)throw Error(eU(this._definition,Z));if(G.type==="hasMany"||G.type==="hasOne"){let U=w0($,X);if(U.length===0)return;let H=U.map(()=>"?").join(", "),z=await Y.all(`SELECT * FROM ${G.relatedTable} WHERE ${G.foreignKey} IN (${H})`,U),A=Z8(G.relatedModelName),W=A?.getDefinition?.()||A?.definition||this._definition;if(G.type==="hasMany"){let Q=new Map;for(let L of z){let O=L[G.foreignKey];if(!Q.has(O))Q.set(O,[]);Q.get(O).push(L)}for(let L of $){let O=Q.get(L.get(X))||[];L.setRelation(Z,O.map((T)=>new aZ(W,T)))}}else{let Q=new Map;for(let L of z){let O=L[G.foreignKey];if(!Q.has(O))Q.set(O,L)}for(let L of $){let O=Q.get(L.get(X));L.setRelation(Z,O?new aZ(W,O):null)}}}if(G.type==="belongsTo"){let U=new Set;for(let O of $){let T=O._attributes[G.foreignKey];if(T!=null)U.add(T)}let H=[...U];if(H.length===0)return;let z=H.map(()=>"?").join(", "),A=await Y.all(`SELECT * FROM ${G.relatedTable} WHERE ${G.localKey} IN (${z})`,H),W=Z8(G.relatedModelName),Q=W?.getDefinition?.()||W?.definition||this._definition,L=new Map;for(let O of A)L.set(O[G.localKey],O);for(let O of $){let T=O._attributes[G.foreignKey],w=L.get(T);O.setRelation(Z,w?new aZ(Q,w):null)}}if(G.type==="belongsToMany"){let U=w0($,X);if(U.length===0)return;if(!G.pivotTable||!G.pivotFkParent||!G.pivotFkRelated)return;let H=U.map(()=>"?").join(", "),z=await Y.all(`SELECT * FROM ${G.pivotTable} WHERE ${G.pivotFkParent} IN (${H})`,U);if(z.length===0){for(let V of $)V.setRelation(Z,[]);return}let A=new Set;for(let V of z){let F=V[G.pivotFkRelated];if(F!=null)A.add(F)}let W=[...A],Q=Z8(G.relatedModelName),L=Q?.getDefinition?.()||Q?.definition||this._definition,O=L?.primaryKey||"id",T=[];if(W.length>0){let V=W.map(()=>"?").join(", ");T=await Y.all(`SELECT * FROM ${G.relatedTable} WHERE ${O} IN (${V})`,W)}let w=new Map;for(let V of T)w.set(V[O],V);let K=new Map;for(let V of z){let F=V[G.pivotFkParent];if(!K.has(F))K.set(F,[]);K.get(F).push(V)}let B=new Set([G.pivotFkParent,G.pivotFkRelated]);for(let V of $){let F=V.get(X),E=(K.get(F)||[]).map((n)=>{let x=w.get(n[G.pivotFkRelated]);if(!x)return null;let d=new aZ(L,x),P={};for(let[M,S]of Object.entries(n))if(!B.has(M))P[M]=S;return d.pivot=P,d}).filter((n)=>n!==null);V.setRelation(Z,E)}}if(G.type==="hasManyThrough"||G.type==="hasOneThrough"){let U=w0($,X);if(U.length===0)return;let H=G.throughLocalKey||"id",z=U.map(()=>"?").join(", "),A=await Y.all(`SELECT ${H}, ${G.throughForeignKey} FROM ${G.throughTable} WHERE ${G.throughForeignKey} IN (${z})`,U);if(A.length===0){for(let B of $)B.setRelation(Z,G.type==="hasManyThrough"?[]:null);return}let W=new Map;for(let B of A)W.set(B[H],B[G.throughForeignKey]);let Q=[...new Set(A.map((B)=>B[H]))],L=Q.map(()=>"?").join(", "),O=await Y.all(`SELECT * FROM ${G.relatedTable} WHERE ${G.targetForeignKey} IN (${L})`,Q),T=Z8(G.relatedModelName),w=T?.getDefinition?.()||T?.definition||this._definition,K=new Map;for(let B of O){let V=W.get(B[G.targetForeignKey]);if(V==null)continue;if(!K.has(V))K.set(V,[]);K.get(V).push(new aZ(w,B))}for(let B of $){let V=K.get(B.get(X))||[];B.setRelation(Z,G.type==="hasManyThrough"?V:V[0]??null)}}}async get(){let Z=OZ(),{sql:$,params:Y}=this.buildQuery(),J=(await Z.all($,Y)).map((G)=>new aZ(this._definition,G));if(this._withRelations.length>0)await this.eagerLoadRelations(J);return J}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let Z=await this.first();if(!Z)throw Error(`No ${this._definition.name} found`);return Z}async last(){let Z=this._definition.primaryKey||"id";return this._orderBy=[{column:Z,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let Z=OZ(),$=[],Y=`SELECT COUNT(*) as count FROM ${this._definition.table}`,X=this.composeWhere($);if(X)Y+=` WHERE ${X}`;let J=await Z.get(Y,$);return Number(J?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let Z=await this.get();if(Z.length===0)throw Error(`No ${this._definition.name} found`);if(Z.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return Z[0]}async increment(Z,$=1){q8(Z,"increment(column)"),this.assertNoUnappliedClauses("increment");let Y=OZ(),X=[$],J=_8(Z),G=`UPDATE ${this._definition.table} SET ${J} = ${J} + ?`;if(G9(this._definition))G+=", updated_at = ?",X.push(J9());let U=this.composeWhere(X);if(U)G+=` WHERE ${U}`;return(await Y.run(G,X)).changes}decrement(Z,$=1){return this.increment(Z,-$)}async chunk(Z,$){let Y=0;while(!0){let X=new WZ(this._definition);X._wheres=[...this._wheres],X._orderBy=[...this._orderBy],X._select=[...this._select],X._withRelations=[...this._withRelations],X._trashed=this._trashed,X._limit=Z,X._offset=Y*Z;let J=await X.get();if(J.length===0)break;if(await $(J)===!1)break;if(J.length<Z)break;Y++}}async paginate(Z=1,$=15){let Y=await this.count(),X=Math.ceil(Y/$);this._limit=$,this._offset=(Z-1)*$;let J=await this.get();return{data:J,total:Y,page:Z,perPage:$,lastPage:X,hasMorePages:Z<X,isEmpty:J.length===0,from:J.length>0?(Z-1)*$+1:null,to:J.length>0?(Z-1)*$+J.length:null}}async pluck(Z){q8(Z,"pluck(column)");let $=OZ(),Y=[],X=_8(Z),J=`SELECT ${X} FROM ${this._definition.table}`,G=this.composeWhere(Y);if(G)J+=` WHERE ${G}`;if(this._orderBy.length>0)J+=` ORDER BY ${this._orderBy.map((H)=>`${_8(H.column)} ${H.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)J+=` LIMIT ${this._limit}`;if(this._offset!==void 0)J+=` OFFSET ${this._offset}`;return(await $.all(J,Y)).map((H)=>H[X])}async aggregate(Z,$){q8($,`${Z}(column)`);let Y=OZ(),X=[],J=`SELECT ${Z}(${_8($)}) as v FROM ${this._definition.table}`,G=this.composeWhere(X);if(G)J+=` WHERE ${G}`;let H=(await Y.get(J,X))?.v;if(H==null)return null;if(typeof H==="string"){let z=Number(H);return H.trim()!==""&&!Number.isNaN(z)?z:H}return H}max(Z){return this.aggregate("MAX",Z)}min(Z){return this.aggregate("MIN",Z)}async avg(Z){return Number(await this.aggregate("AVG",Z)??0)||0}async sum(Z){return Number(await this.aggregate("SUM",Z)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let Z=OZ(),$=[],Y=`DELETE FROM ${this._definition.table}`,X=this.composeWhere($);if(X)Y+=` WHERE ${X}`;return(await Z.run(Y,$)).changes}async update(Z){this.assertNoUnappliedClauses("update");let $=OZ(),Y=Object.entries(Z),X=Y.map(([H])=>`${_8(H)} = ?`).join(", "),J=Y.map(([,H])=>H);if(G9(this._definition))J.push(J9());let G=`UPDATE ${this._definition.table} SET ${X}${G9(this._definition)?", updated_at = ?":""}`,U=this.composeWhere(J);if(U)G+=` WHERE ${U}`;return(await $.run(G,J)).changes}}function Z2(Z){let $={query:()=>new WZ(Z),where(Y,X,J){return new WZ(Z).where(Y,X,J)},orWhere(Y,X,J){return new WZ(Z).orWhere(Y,X,J)},whereIn(Y,X){return new WZ(Z).whereIn(Y,X)},whereNotIn(Y,X){return new WZ(Z).whereNotIn(Y,X)},whereNull(Y){return new WZ(Z).whereNull(Y)},whereNotNull(Y){return new WZ(Z).whereNotNull(Y)},whereLike(Y,X){return new WZ(Z).whereLike(Y,X)},orderBy(Y,X="asc"){return new WZ(Z).orderBy(Y,X)},orderByDesc(Y){return new WZ(Z).orderByDesc(Y)},select(...Y){return new WZ(Z).select(...Y)},with(...Y){return new WZ(Z).with(...Y)},limit:(Y)=>new WZ(Z).limit(Y),take:(Y)=>new WZ(Z).take(Y),skip:(Y)=>new WZ(Z).skip(Y),withTrashed:()=>new WZ(Z).withTrashed(),onlyTrashed:()=>new WZ(Z).onlyTrashed(),async find(Y){let X=OZ(),J=Z.primaryKey||"id",G=w9(Z)?` AND ${n8} IS NULL`:"",U=await X.get(`SELECT * FROM ${Z.table} WHERE ${J} = ?${G}`,[Y]);return U?new aZ(Z,U):void 0},async findOrFail(Y){let X=await $.find(Y);if(!X)throw Error(`${Z.name} with id ${Y} not found`);return X},async findMany(Y){let X=OZ(),J=Z.primaryKey||"id",G=w9(Z)?` AND ${n8} IS NULL`:"";return(await X.all(`SELECT * FROM ${Z.table} WHERE ${J} IN (${Y.map(()=>"?").join(", ")})${G}`,Y)).map((H)=>new aZ(Z,H))},all:()=>new WZ(Z).get(),first:()=>new WZ(Z).first(),firstOrFail:()=>new WZ(Z).firstOrFail(),last:()=>new WZ(Z).last(),count:()=>new WZ(Z).count(),exists:()=>new WZ(Z).exists(),doesntExist:()=>new WZ(Z).doesntExist(),paginate:(Y,X)=>new WZ(Z).paginate(Y,X),whereBetween(Y,X){return new WZ(Z).whereBetween(Y,X)},whereNotBetween(Y,X){return new WZ(Z).whereNotBetween(Y,X)},async create(Y){let X=new aZ(Z,Y);return await X.save(),X},async createMany(Y){let X=[];for(let J of Y)X.push(await this.create(J));return X},async updateOrCreate(Y,X){let J=new WZ(Z);for(let[U,H]of Object.entries(Y))J=J.where(U,H);let G=await J.first();if(G)return await G.update(X),G;return this.create({...Y,...X})},async firstOrCreate(Y,X){let J=new WZ(Z);for(let[U,H]of Object.entries(Y))J=J.where(U,H);return await J.first()||this.create({...Y,...X})},async destroy(Y){let X=OZ(),J=Z.primaryKey||"id";return(await X.run(`DELETE FROM ${Z.table} WHERE ${J} = ?`,[Y])).changes>0},remove(Y){return this.destroy(Y)},async truncate(){await OZ().run(`DELETE FROM ${Z.table}`,[])},getDefinition:()=>Z,getTable:()=>Z.table,make(Y={}){return new aZ(Z,Y)},latest:(Y="created_at")=>new WZ(Z).orderByDesc(Y),oldest:(Y="created_at")=>new WZ(Z).orderBy(Y,"asc"),max:(Y)=>new WZ(Z).max(Y),min:(Y)=>new WZ(Z).min(Y),avg:(Y)=>new WZ(Z).avg(Y),sum:(Y)=>new WZ(Z).sum(Y),pluck(Y){return new WZ(Z).pluck(Y)}};return new Proxy($,{get(Y,X){if(typeof X==="string"&&X.startsWith("where")&&X.length>5){let J=X.slice(5),G=J.charAt(0).toLowerCase()+J.slice(1);if(G in Z.attributes||G==="id"||G===Z.primaryKey)return(U)=>new WZ(Z).where(G,U)}return Reflect.get(Y,X)}})}function x1(Z){let $=Z2(Z);if(Z?.name)iU(Z.name,$);return $}async function Y3(Z){let $=OZ(),Y=DZ(Z.primaryKey||"id"),X=[],J=new Set([Y]);if(X.push(Z.autoIncrement!==!1?`${Y} INTEGER PRIMARY KEY AUTOINCREMENT`:`${Y} INTEGER PRIMARY KEY`),Z.traits?.useUuid)X.push("uuid TEXT UNIQUE"),J.add("uuid");for(let[G,U]of Object.entries(Z.attributes)){let H=DZ(G);if(J.has(H))continue;J.add(H);let z=qX(U.type),A=a$(z);if(H.endsWith("_id")&&(z===void 0||O9(z)))A="INTEGER";let W=`${H} ${A}`;if(U.unique)W+=" UNIQUE";if(typeof U.foreignKey==="object"&&U.foreignKey!==null){let Q=U.foreignKey;if(W+=` REFERENCES ${Q.table}(${Q.column??"id"})`,Q.onDelete)W+=` ON DELETE ${Q.onDelete.toUpperCase()}`;if(Q.onUpdate)W+=` ON UPDATE ${Q.onUpdate.toUpperCase()}`}X.push(W)}for(let G of I9(Z.belongsTo)){let U=G.foreignKey??`${DZ(G.model)}_id`;if(J.has(U))continue;J.add(U),X.push(`${U} INTEGER`)}if(G9(Z))for(let G of["created_at","updated_at"]){if(J.has(G))continue;J.add(G),X.push(`${G} TEXT`)}if(w9(Z)&&!J.has("deleted_at"))J.add("deleted_at"),X.push("deleted_at TEXT");await $.run(`CREATE TABLE IF NOT EXISTS ${Z.table} (${X.join(", ")})`,[])}async function X3(Z,$,Y){let X=OZ(),J=Z.traits?.useSeeder,G=$??(typeof J==="object"&&J?J.count:10);if(!Y)try{let U=await import("./chunk-d2b8tt64.js");Y=B1(U.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let U=0;U<G;U++){let H={};for(let[A,W]of Object.entries(Z.attributes))if(W.factory)H[DZ(A)]=W.factory(Y);if(G9(Z)){let A=J9();H.created_at=A,H.updated_at=A}if(Z.traits?.useUuid)H.uuid=crypto.randomUUID();let z=Object.keys(H);await X.run(`INSERT INTO ${Z.table} (${z.join(", ")}) VALUES (${z.map(()=>"?").join(", ")})`,Object.values(H))}}var C1,W7=null,N0,j7,lU=500,X9=null,k8=null,a9=null,D0=null,I0=null,n8="deleted_at",M0="__btm_rel__",D1,I1,M1,M9,tU=1000,Q7,aU;var P0=A8(()=>{H0();qZ();g8();l$();E0();A7();m8();Z7();C1=/^[A-Z_][A-Z0-9_]*$/i;N0=new Map;j7=new Map;D1=new WeakMap;I1=new Map,M1=new Map,M9=new Map;Q7=["hasMany","hasOne","belongsTo","belongsToMany"],aU=[...Q7,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"]});var v1={};$2(v1,{registerModel:()=>T0,registerBrowserModels:()=>X2,hasModel:()=>p1,getModelRegistry:()=>g1,getModel:()=>b1,getAllModels:()=>f1,defineModel:()=>m1,clearModelRegistry:()=>d1});function b1(Z){return C9.get(Z)}function f1(){return[...C9.values()]}function g1(){return Object.fromEntries(C9)}function p1(Z){return C9.has(Z)}function d1(){C9.clear(),N1()}function T0(Z,$){return C9.set(Z,$),$}function Y2(){return typeof window<"u"&&typeof document<"u"}function m1(Z){let $;if(Y2())$=y1(Z);else{let Y=x1(Z);$=Object.assign(Y,{definition:Z,getDefinition:()=>Z,getTable:()=>Z.table,getName:()=>Z.name})}return T0(Z.name,$),$}function X2(Z){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...Z}}var C9;var e9=A8(()=>{h1();P0();C9=new Map});qZ();g8();import{existsSync as y8,mkdirSync as OJ,mkdtempSync as T2,readdirSync as EJ,readFileSync as Y$,rmSync as DJ,unlinkSync as g0,writeFileSync as IJ}from"fs";import{tmpdir as q2}from"os";import{join as $8}from"path";import p0 from"process";qZ();function j6(Z){let $=2166136261;for(let Y=0;Y<Z.length;Y++)$^=Z.charCodeAt(Y),$=Math.imul($,16777619)>>>0;return $.toString(36).padStart(7,"0").slice(-7)}function Q6(Z,$=63){if(Z.length<=$)return Z;let Y=`_${j6(Z)}`;return Z.slice(0,$-Y.length)+Y}function j8(Z,$){let Y=`${Z}_`,X=$.startsWith(Y)?$:`${Y}${$}`;return Q6(X)}class hZ{quoteIdentifier(Z){return`\`${Z.replace(/`/g,"``")}\``}getColumnType(Z){switch(Z.type){case"string":return`varchar(${Z.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(Z.enumValues&&Z.enumValues.length>0)return`ENUM(${Z.enumValues.map((Y)=>`'${Y.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(Z){return this.getColumnType(Z)}getAutoIncrementClause(Z){if(Z.isPrimaryKey&&(Z.type==="integer"||Z.type==="bigint"))return"auto_increment";return""}getDefaultValue(Z){if(!Z.hasDefault||Z.defaultValue===void 0)return"";let $=Z.defaultValue;if(typeof $==="string"){let Y=$.toUpperCase();if(Y==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(Y))return`default ${Y}`;let J=`'${$.replace(/'/g,"''")}'`;if(Z.type==="text"||Z.type==="json"||Z.type==="enum"&&!Z.enumValues?.length)return`default (${J})`;return`default ${J}`}else if(typeof $==="number"||typeof $==="bigint")return`default ${$}`;else if(typeof $==="boolean")return`default ${$?1:0}`;else if($ instanceof Date)return`default '${$.toISOString()}'`;return""}createEnumType(Z,$){return""}foreignKeyClauses(Z){return Z.columns.filter(($)=>$.references).map(($)=>{let Y=$.references,X=`${Z.table}_${$.name}_fk`,J=`CONSTRAINT ${this.quoteIdentifier(X)} FOREIGN KEY (${this.quoteIdentifier($.name)}) REFERENCES ${this.quoteIdentifier(Y.table)}(${this.quoteIdentifier(Y.column)})`;if(Y.onDelete)J+=` ON DELETE ${Y.onDelete.toUpperCase()}`;if(Y.onUpdate)J+=` ON UPDATE ${Y.onUpdate.toUpperCase()}`;return J})}createTable(Z){let $=[...Z.columns.map((Y)=>this.renderColumn(Y)),...this.foreignKeyClauses(Z)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(Z.table)} (
|
|
65
|
-
${$.join(`,
|
|
66
|
-
`)}
|
|
67
|
-
) DEFAULT CHARSET=utf8mb4;`}static KEY_PREFIX_CHARACTERS=255;static MAX_KEY_BYTES=3072;static BYTES_PER_CHARACTER=4;keyPartWidth(Z){let $=this.getColumnType(Z).toLowerCase();if($.includes("text")||$.includes("blob")||$==="json")return{bytes:Number.POSITIVE_INFINITY,indexableWhole:!1};let Y=$.match(/^(?:var)?char\((\d+)\)$/)?.[1];if(Y!==void 0)return{bytes:Number(Y)*hZ.BYTES_PER_CHARACTER,indexableWhole:!0};return{bytes:8,indexableWhole:!0}}keyParts(Z,$,Y){let X=$.columns.map((G)=>{let U=Y?.find((A)=>A.name===G),H=U?this.keyPartWidth(U):{bytes:0,indexableWhole:!0},z=!H.indexableWhole;return{name:G,prefixed:z,bytes:z?hZ.KEY_PREFIX_CHARACTERS*hZ.BYTES_PER_CHARACTER:H.bytes,narrowable:!H.indexableWhole||H.bytes>hZ.KEY_PREFIX_CHARACTERS*hZ.BYTES_PER_CHARACTER}}),J=()=>X.reduce((G,U)=>G+U.bytes,0);while(J()>hZ.MAX_KEY_BYTES){let G=X.filter((U)=>U.narrowable&&!U.prefixed).sort((U,H)=>H.bytes-U.bytes)[0];if(!G)throw Error(`[migrations] Index '${$.name}' on table '${Z}' needs ${J()} bytes of key, over MySQL's ${hZ.MAX_KEY_BYTES}. Every column in it is already at its ${hZ.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);G.prefixed=!0,G.bytes=hZ.KEY_PREFIX_CHARACTERS*hZ.BYTES_PER_CHARACTER}return X.map((G)=>G.prefixed?`${this.quoteIdentifier(G.name)}(${hZ.KEY_PREFIX_CHARACTERS})`:this.quoteIdentifier(G.name))}createIndex(Z,$,Y){if($.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${$.name}' on table '${Z}' uses WHERE clause: ${$.where}`);let X=$.type==="unique"?"UNIQUE ":"",J=j8(Z,$.name),G=this.keyParts(Z,$,Y).join(", ");return`CREATE ${X}INDEX ${this.quoteIdentifier(J)} ON ${this.quoteIdentifier(Z)} (${G});`}addForeignKey(Z,$,Y,X,J,G,U=[]){let H=`${Z}_${$}_fk`,z=`ALTER TABLE ${this.quoteIdentifier(Z)} ADD CONSTRAINT ${this.quoteIdentifier(H)} FOREIGN KEY (${this.quoteIdentifier($)}) REFERENCES ${this.quoteIdentifier(Y)}(${this.quoteIdentifier(X)})`;if(J)z+=` ON DELETE ${J.toUpperCase()}`;if(G)z+=` ON UPDATE ${G.toUpperCase()}`;let A=[...new Set(U)].map((W)=>`ALTER TABLE ${this.quoteIdentifier(Z)} DROP FOREIGN KEY ${this.quoteIdentifier(W)};`).join(`
|
|
68
|
-
`);return A?`${A}
|
|
69
|
-
${z};`:`${z};`}addColumn(Z,$){let Y=this.getColumnType($),X=[this.quoteIdentifier($.name),Y];if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let J=this.getDefaultValue($);if(J)X.push(J);return`ALTER TABLE ${this.quoteIdentifier(Z)} ADD COLUMN ${X.join(" ")};`}modifyColumn(Z,$){let Y=this.getColumnType($),X=[this.quoteIdentifier($.name),Y];if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let J=this.getDefaultValue($);if(J)X.push(J);return`ALTER TABLE ${this.quoteIdentifier(Z)} MODIFY COLUMN ${X.join(" ")};`}renameColumn(Z,$,Y){return`ALTER TABLE ${this.quoteIdentifier(Z)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Y)};`}renameTable(Z,$){return`RENAME TABLE ${this.quoteIdentifier(Z)} TO ${this.quoteIdentifier($)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; MySQL uses in-place ALTER.")}dropTable(Z){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(Z)}`}dropColumn(Z,$){return`ALTER TABLE ${this.quoteIdentifier(Z)} DROP COLUMN ${this.quoteIdentifier($)};`}dropIndex(Z,$){let Y=j8(Z,$);return`DROP INDEX ${this.quoteIdentifier(Y)} ON ${this.quoteIdentifier(Z)};`}dropEnumType(Z){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
70
|
-
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
71
|
-
migration VARCHAR(255) NOT NULL UNIQUE,
|
|
72
|
-
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
73
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(Z,$){return`JSON_UNQUOTE(JSON_EXTRACT(${Z}, CONCAT('$.', ${$})))`}dateBucket(Z,$,Y=0){let X=Y===0?Z:`DATE_ADD(${Z}, INTERVAL ${Y} HOUR)`;switch($){case"hour":return`DATE_FORMAT(${X}, '%Y-%m-%dT%H:00:00.000Z')`;case"week":return`DATE_FORMAT(DATE_SUB(${X}, INTERVAL WEEKDAY(${X}) DAY), '%Y-%m-%dT00:00:00.000Z')`;case"month":return`DATE_FORMAT(${X}, '%Y-%m-01T00:00:00.000Z')`;case"year":return`DATE_FORMAT(${X}, '%Y-01-01T00:00:00.000Z')`;case"day":default:return`DATE_FORMAT(${X}, '%Y-%m-%dT00:00:00.000Z')`}}booleanLiteral(Z){return Z?"TRUE":"FALSE"}renderColumn(Z){let $=this.getColumnType(Z),Y=[this.quoteIdentifier(Z.name),$];if(Z.isPrimaryKey){Y.push("PRIMARY KEY");let J=this.getAutoIncrementClause(Z);if(J)Y.push(J)}if(!Z.isNullable&&!Z.isPrimaryKey)Y.push("not null");let X=this.getDefaultValue(Z);if(X)Y.push(X);return Y.join(" ")}}class o${quoteIdentifier(Z){return`"${Z.replace(/"/g,'""')}"`}getColumnType(Z){switch(Z.type){case"string":return`varchar(${Z.maxLength??255})`;case"text":return"text";case"boolean":return"boolean";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"timestamp";case"timestamptz":return"timestamptz";case"json":return"jsonb";case"enum":if(Z.enumValues&&Z.enumValues.length>0)return Z.enumTypeName?this.quoteIdentifier(Z.enumTypeName):"text";return"text";default:return"text"}}getPrimaryKeyType(Z){switch(Z.type){case"integer":return"SERIAL";case"bigint":return"BIGSERIAL";default:return this.getColumnType(Z)}}getAutoIncrementClause(Z){return""}getDefaultValue(Z){if(!Z.hasDefault||Z.defaultValue===void 0)return"";let $=Z.defaultValue;if(typeof $==="string"){let Y=$.toUpperCase();if(Y==="UTC_TIMESTAMP")return"default (now() AT TIME ZONE 'utc')";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(Y))return`default ${Y}`;return`default '${$.replace(/'/g,"''")}'`}else if(typeof $==="number"||typeof $==="bigint")return`default ${$}`;else if(typeof $==="boolean")return`default ${$?"true":"false"}`;else if($ instanceof Date)return`default '${$.toISOString()}'`;return""}createEnumType(Z,$){let Y=$.map((X)=>`'${X.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier(Z)} AS ENUM (${Y});`}createTable(Z){let $=Z.columns.map((Y)=>this.renderColumn(Y)).join(`,
|
|
74
|
-
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(Z.table)} (
|
|
75
|
-
${$}
|
|
76
|
-
);`}createIndex(Z,$){let Y=$.type==="unique"?"UNIQUE ":"",X=j8(Z,$.name),J=$.columns.map((U)=>this.quoteIdentifier(U)).join(", "),G=$.where?` WHERE ${$.where}`:"";return`CREATE ${Y}INDEX IF NOT EXISTS ${this.quoteIdentifier(X)} ON ${this.quoteIdentifier(Z)} (${J})${G};`}addForeignKey(Z,$,Y,X,J,G,U=[]){let H=`${Z}_${$}_fk`,z=`ALTER TABLE ${this.quoteIdentifier(Z)} ADD CONSTRAINT ${this.quoteIdentifier(H)} FOREIGN KEY (${this.quoteIdentifier($)}) REFERENCES ${this.quoteIdentifier(Y)}(${this.quoteIdentifier(X)})`;if(J)z+=` ON DELETE ${J.toUpperCase()}`;if(G)z+=` ON UPDATE ${G.toUpperCase()}`;let A=[...new Set(U)].map((W)=>`ALTER TABLE ${this.quoteIdentifier(Z)} DROP CONSTRAINT ${this.quoteIdentifier(W)};`).join(`
|
|
77
|
-
`);return A?`${A}
|
|
78
|
-
${z};`:`${z};`}addColumn(Z,$){let Y=this.getColumnType($),X=[this.quoteIdentifier($.name),Y];if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let J=this.getDefaultValue($);if(J)X.push(J);return`ALTER TABLE ${this.quoteIdentifier(Z)} ADD COLUMN ${X.join(" ")};`}modifyColumn(Z,$){let Y=this.getColumnType($),X=this.quoteIdentifier(Z),J=this.quoteIdentifier($.name),G=[`ALTER TABLE ${X} ALTER COLUMN ${J} DROP DEFAULT;`,`ALTER TABLE ${X} ALTER COLUMN ${J} TYPE ${Y} USING ${J}::${Y};`];if(!$.isPrimaryKey)G.push(`ALTER TABLE ${X} ALTER COLUMN ${J} ${$.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let U=this.getDefaultValue($);if(U)G.push(`ALTER TABLE ${X} ALTER COLUMN ${J} SET ${U};`);return G.join(`
|
|
79
|
-
`)}renameColumn(Z,$,Y){return`ALTER TABLE ${this.quoteIdentifier(Z)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Y)};`}renameTable(Z,$){return`ALTER TABLE ${this.quoteIdentifier(Z)} RENAME TO ${this.quoteIdentifier($)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; Postgres uses in-place ALTER.")}dropTable(Z){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(Z)} CASCADE`}dropColumn(Z,$){return`ALTER TABLE ${this.quoteIdentifier(Z)} DROP COLUMN ${this.quoteIdentifier($)};`}dropIndex(Z,$){let Y=j8(Z,$);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(Y)};`}dropEnumType(Z){return`DROP TYPE IF EXISTS ${this.quoteIdentifier(Z)} CASCADE`}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
80
|
-
id SERIAL PRIMARY KEY,
|
|
81
|
-
migration VARCHAR(255) NOT NULL UNIQUE,
|
|
82
|
-
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
83
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}jsonExtract(Z,$){return`(${Z}::jsonb ->> ${$})`}dateBucket(Z,$,Y=0){let X=Y===0?`${Z}::timestamp`:`(${Z}::timestamp ${Y>=0?"+":"-"} interval '${Math.abs(Y)} hours')`,J=$==="week"?`date_trunc('week', ${X})`:X;switch($){case"hour":return`to_char(${J}, 'YYYY-MM-DD"T"HH24:00:00.000"Z"')`;case"month":return`to_char(${J}, 'YYYY-MM-01"T"00:00:00.000"Z"')`;case"year":return`to_char(${J}, 'YYYY-01-01"T"00:00:00.000"Z"')`;case"week":case"day":default:return`to_char(${J}, 'YYYY-MM-DD"T"00:00:00.000"Z"')`}}booleanLiteral(Z){return Z?"TRUE":"FALSE"}renderColumn(Z){let $=Z.isPrimaryKey?this.getPrimaryKeyType(Z):this.getColumnType(Z),Y=[this.quoteIdentifier(Z.name),$];if(Z.isPrimaryKey)Y.push("PRIMARY KEY");if(!Z.isNullable&&!Z.isPrimaryKey)Y.push("not null");let X=this.getDefaultValue(Z);if(X)Y.push(X);if(Z.references){let J=`REFERENCES ${this.quoteIdentifier(Z.references.table)}(${this.quoteIdentifier(Z.references.column)})`;if(Z.references.onDelete)J+=` ON DELETE ${Z.references.onDelete.toUpperCase()}`;if(Z.references.onUpdate)J+=` ON UPDATE ${Z.references.onUpdate.toUpperCase()}`;Y.push(J)}return Y.join(" ")}}class r$ extends hZ{createTable(Z){let $=Z.columns.map((G)=>this.renderColumn(G)).join(`,
|
|
84
|
-
`),Y=[];if(Z.tableKind!=="reference"){let G=Z.shardKey?.length?Z.shardKey:Z.columns.filter((U)=>U.isPrimaryKey).map((U)=>U.name);if(G&&G.length>0)Y.push(`SHARD KEY (${G.map((U)=>this.quoteIdentifier(U)).join(", ")})`)}if(Z.tableKind!=="rowstore"&&Z.tableKind!=="reference"){let G=Z.sortKey?.length?Z.sortKey:void 0;Y.push(`SORT KEY (${(G??[]).map((U)=>this.quoteIdentifier(U)).join(", ")})`)}let X=[$,...Y].join(`,
|
|
85
|
-
`);return`CREATE${this.tableKindSuffix(Z.tableKind)} TABLE IF NOT EXISTS ${this.quoteIdentifier(Z.table)} (
|
|
86
|
-
${X}
|
|
87
|
-
);`}tableKindSuffix(Z){switch(Z){case"rowstore":return" ROWSTORE";case"reference":return" REFERENCE";default:return""}}addForeignKey(){return""}createIndex(Z,$,Y){if($.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on SingleStore. Index '${$.name}' on table '${Z}' uses WHERE clause: ${$.where}`);return super.createIndex(Z,$,Y)}}class t$ extends hZ{sharded;constructor(Z=!0){super();this.sharded=Z}getAutoIncrementClause(Z){return this.sharded?"":super.getAutoIncrementClause(Z)}renderColumn(Z){if(!this.sharded||!Z.references)return super.renderColumn(Z);let{references:$,...Y}=Z;return super.renderColumn(Y)}foreignKeyClauses(Z){return this.sharded?[]:super.foreignKeyClauses(Z)}createTable(Z){return super.createTable(Z)}addForeignKey(...Z){return this.sharded?"":super.addForeignKey(...Z)}createMigrationsTable(){if(!this.sharded)return super.createMigrationsTable();return`CREATE TABLE IF NOT EXISTS migrations (
|
|
88
|
-
migration VARCHAR(255) NOT NULL PRIMARY KEY,
|
|
89
|
-
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
90
|
-
)`}}H0();class e${quoteIdentifier(Z){return`"${Z.replace(/"/g,'""')}"`}getColumnType(Z){if(Z.name.endsWith("_id")&&O9(Z.type))return"INTEGER";if(Z.type==="enum"){if(Z.enumValues&&Z.enumValues.length>0){let $=Z.enumValues.map((Y)=>`'${Y.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier(Z.name)} IN (${$}))`}return"TEXT"}return a$(Z.type)}getPrimaryKeyType(Z){return this.getColumnType(Z)}getAutoIncrementClause(Z){if(Z.isPrimaryKey&&(Z.type==="integer"||Z.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue(Z){if(!Z.hasDefault||Z.defaultValue===void 0)return"";let $=Z.defaultValue;if(typeof $==="string"){if($.toUpperCase()==="UTC_TIMESTAMP")return"default CURRENT_TIMESTAMP";if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes($.toUpperCase()))return`default ${$.toUpperCase()}`;return`default '${$.replace(/'/g,"''")}'`}else if(typeof $==="number"||typeof $==="bigint")return`default ${$}`;else if(typeof $==="boolean")return`default ${$?1:0}`;else if($ instanceof Date)return`default '${$.toISOString()}'`;return""}createEnumType(Z,$){return""}createTable(Z){let $=Z.columns.map((Y)=>this.renderColumn(Y)).join(`,
|
|
91
|
-
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(Z.table)} (
|
|
92
|
-
${$}
|
|
93
|
-
);`}createIndex(Z,$){let Y=$.type==="unique"?"UNIQUE ":"",X=j8(Z,$.name),J=$.columns.map((U)=>this.quoteIdentifier(U)).join(", "),G=$.where?` WHERE ${$.where}`:"";return`CREATE ${Y}INDEX IF NOT EXISTS ${this.quoteIdentifier(X)} ON ${this.quoteIdentifier(Z)} (${J})${G};`}addForeignKey(Z,$,Y,X,J,G){return""}addColumn(Z,$){let Y=this.getColumnType($),X=[this.quoteIdentifier($.name),Y];if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let J=this.getDefaultValue($);if(J)X.push(J);return`ALTER TABLE ${this.quoteIdentifier(Z)} ADD COLUMN ${X.join(" ")};`}modifyColumn(Z,$){return`-- SQLite does not support ALTER COLUMN; a table rebuild is required to change ${this.quoteIdentifier(Z)}.${this.quoteIdentifier($.name)}`}renameColumn(Z,$,Y){return`ALTER TABLE ${this.quoteIdentifier(Z)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Y)};`}renameTable(Z,$){return`ALTER TABLE ${this.quoteIdentifier(Z)} RENAME TO ${this.quoteIdentifier($)};`}rebuildTable(Z){let{target:$,tempName:Y,columnSource:X}=Z,J=(A)=>this.quoteIdentifier(A),G=$.columns.map((A)=>this.renderColumn(A)).join(`,
|
|
94
|
-
`),U=`CREATE TABLE ${J(Y)} (
|
|
95
|
-
${G}
|
|
96
|
-
);`,H=$.columns.map((A)=>A.name).filter((A)=>X[A]!==void 0),z=["PRAGMA foreign_keys=OFF;","BEGIN;",U];if(H.length>0){let A=H.map(J).join(", "),W=H.map((Q)=>J(X[Q])).join(", ");z.push(`INSERT INTO ${J(Y)} (${A}) SELECT ${W} FROM ${J($.table)};`)}z.push(`DROP TABLE ${J($.table)};`),z.push(`ALTER TABLE ${J(Y)} RENAME TO ${J($.table)};`);for(let A of $.indexes)z.push(this.createIndex($.table,A));return z.push("PRAGMA foreign_key_check;"),z.push("COMMIT;"),z.push("PRAGMA foreign_keys=ON;"),z.join(`
|
|
97
|
-
`)}dropTable(Z){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(Z)}`}dropColumn(Z,$){return`ALTER TABLE ${this.quoteIdentifier(Z)} DROP COLUMN ${this.quoteIdentifier($)};`}dropIndex(Z,$){let Y=j8(Z,$);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(Y)};`}dropEnumType(Z){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
98
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
99
|
-
migration TEXT NOT NULL UNIQUE,
|
|
100
|
-
executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
101
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(Z,$){return`json_extract(${Z}, '$.' || ${$})`}dateBucket(Z,$,Y=0){let X=Y===0?Z:`datetime(${Z}, '${Y>=0?"+":"-"}${Math.abs(Y)} hours')`;switch($){case"hour":return`strftime('%Y-%m-%dT%H:00:00.000Z', ${X})`;case"week":return`strftime('%Y-%m-%dT00:00:00.000Z', ${X}, '-6 days', 'weekday 1')`;case"month":return`strftime('%Y-%m-01T00:00:00.000Z', ${X})`;case"year":return`strftime('%Y-01-01T00:00:00.000Z', ${X})`;case"day":default:return`strftime('%Y-%m-%dT00:00:00.000Z', ${X})`}}booleanLiteral(Z){return Z?"TRUE":"FALSE"}renderColumn(Z){let $=this.getColumnType(Z),Y=[this.quoteIdentifier(Z.name),$];if(Z.isPrimaryKey){Y.push("PRIMARY KEY");let J=this.getAutoIncrementClause(Z);if(J)Y.push(J)}if(!Z.isNullable&&!Z.isPrimaryKey)Y.push("not null");let X=this.getDefaultValue(Z);if(X)Y.push(X);if(Z.references){if(Y.push(`REFERENCES ${this.quoteIdentifier(Z.references.table)}(${this.quoteIdentifier(Z.references.column)})`),Z.references.onDelete)Y.push(`ON DELETE ${Z.references.onDelete.toUpperCase()}`);if(Z.references.onUpdate)Y.push(`ON UPDATE ${Z.references.onUpdate.toUpperCase()}`)}return Y.join(" ")}}function B8(Z,$={}){switch(Z){case"postgres":return new o$;case"mysql":return new hZ;case"singlestore":return new r$;case"vitess":return new t$($.vitessSharded??y.vitess?.sharded??!0);case"sqlite":return new e$;default:throw Error(`Unsupported dialect: ${Z}`)}}g8();async function _6(Z={}){let $=Z.iterations||1000,Y=Z.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${$}`),console.log(`-- Operations: ${Y.join(", ")}`),console.log();let X=JZ();console.log("-- Setting up test table...");try{await $Z.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await $Z.unsafe(`
|
|
102
|
-
CREATE TABLE bench_users (
|
|
103
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
104
|
-
name TEXT NOT NULL,
|
|
105
|
-
email TEXT NOT NULL,
|
|
106
|
-
active INTEGER DEFAULT 1,
|
|
107
|
-
created_at TEXT
|
|
108
|
-
)
|
|
109
|
-
`).execute();for(let U=0;U<100;U++)await $Z.unsafe(`
|
|
110
|
-
INSERT INTO bench_users (name, email, created_at)
|
|
111
|
-
VALUES (?, ?, ?)
|
|
112
|
-
`,[`User ${U}`,`user${U}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(U){throw console.error("-- Failed to setup test table:",U),U}let J=[];if(Y.includes("select")){let U=[];for(let H=0;H<$;H++){let z=performance.now();await X.selectFrom("bench_users").where({active:1}).limit(10).execute(),U.push(performance.now()-z)}J.push({operation:"SELECT with WHERE + LIMIT",avgTime:U.reduce((H,z)=>H+z,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}if(Y.includes("select")){let U=[];for(let H=0;H<$;H++){let z=performance.now();await X.selectFrom("bench_users").where({id:1}).first(),U.push(performance.now()-z)}J.push({operation:"SELECT by ID (first)",avgTime:U.reduce((H,z)=>H+z,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}if(Y.includes("count")){let U=[];for(let H=0;H<$;H++){let z=performance.now();await X.selectFrom("bench_users").count(),U.push(performance.now()-z)}J.push({operation:"COUNT",avgTime:U.reduce((H,z)=>H+z,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}if(Y.includes("insert")){let U=[];for(let H=0;H<$;H++){let z=performance.now();await X.insertInto("bench_users").values({name:`Bench User ${H}`,email:`bench${H}@example.com`,created_at:new Date().toISOString()}).execute(),U.push(performance.now()-z)}J.push({operation:"INSERT",avgTime:U.reduce((H,z)=>H+z,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}if(Y.includes("update")){let U=[];for(let H=0;H<$;H++){let z=performance.now();await X.updateTable("bench_users").set({active:0}).where({id:1}).execute(),U.push(performance.now()-z)}J.push({operation:"UPDATE by ID",avgTime:U.reduce((H,z)=>H+z,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}if(Y.includes("delete")){let U=[],H=[];for(let z=0;z<$;z++){let A=await X.insertInto("bench_users").values({name:"To Delete",email:`delete${z}@example.com`,created_at:new Date().toISOString()}).execute();H.push(A)}for(let z=0;z<$;z++){let A=performance.now();await X.deleteFrom("bench_users").where({id:H[z]}).execute(),U.push(performance.now()-A)}J.push({operation:"DELETE by ID",avgTime:U.reduce((z,A)=>z+A,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}console.log("-- Benchmark Results"),console.log();let G=Math.max(...J.map((U)=>U.operation.length));console.log("Operation".padEnd(G+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(G+2+12+12+12+12));for(let U of J){let H=U.operation.padEnd(G+2),z=U.avgTime.toFixed(3).padStart(12),A=U.minTime.toFixed(3).padStart(12),W=U.maxTime.toFixed(3).padStart(12),Q=(1000/U.avgTime).toFixed(0).padStart(12);console.log(`${H}${z}${A}${W}${Q}`)}console.log();try{await $Z.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(U){console.error("-- Warning: Failed to cleanup test table:",U)}}qZ();g8();qZ();m8();function L6(Z){return d8(y.relations?.singularizeStrategy)(Z)}function e8(Z,$,Y,X={}){let J=X.singularize??L6,U=Z.relations?.[$]?.belongsToMany?.[Y];if(U==null)return null;let H=typeof U==="object",z=H?U:null,A=H?z.model:U,W=Z.modelToTable[A]||A,Q,L;if(z?.table)Q=z.table;else if(z?.through){if(L=z.through,Q=Z.modelToTable[z.through],!Q)throw Error(`[query-builder] belongsToMany relation '${Y}' on '${$}' references unknown through model '${z.through}'. Make sure '${z.through}' is registered via defineModels({...}).`)}else{let V=J($),F=J(W);Q=[V,F].sort().join("_")}let O=z?.foreignKey??`${J($)}_id`,T=z?.relatedKey??`${J(W)}_id`,w={};if(z?.pivot?.columns)Object.assign(w,z.pivot.columns);if(L&&X.models){let V=X.models[L],F=V?.definition??V?.getDefinition?.()??V,I=F?.attributes??{};for(let[E,n]of Object.entries(I)){if(E===O||E===T||E===(F?.primaryKey??"id"))continue;w[E]={default:n?.default,nullable:n?.nullable,validation:n?.validation}}}let K=Boolean(z?.pivot?.timestamps),B=Object.keys(w);return{pivotTable:Q,fkParent:O,fkRelated:T,pivotColumns:B,pivotColumnDefs:w,pivotModelName:L,timestamps:K,relatedModelName:A,relatedTable:W,hasConfig:H}}function*CH(Z,$={}){let Y=Z.relations;if(!Y)return;for(let[X,J]of Object.entries(Y)){let G=J?.belongsToMany;if(!G)continue;for(let U of Object.keys(G)){let H=e8(Z,X,U,$);if(H)yield{parentTable:X,relationKey:U,resolved:H}}}}m8();Z7();function R8(Z){return typeof Z==="object"&&Z!==null&&"raw"in Z&&typeof Z.raw==="string"}function W0(Z,$,Y){if(Array.isArray($)){let J=NZ($.length,Y.length+1),G=rZ(Z,$,!1,J);return Y.push(...$),G}let X=`${Z} = ${e(Y.length+1)}`;return Y.push($),X}function u9(Z){return typeof Z==="object"&&Z!==null&&"sql"in Z&&typeof Z.sql==="string"&&(!("parameters"in Z)||Array.isArray(Z.parameters))}function n9(Z,$){let Y=Z.parameters??[];if(y.dialect!=="postgres"||Y.length===0)return{text:Z.sql,parameters:Y};let X=0,J=Z.sql.replace(/\?/g,(G)=>{if(X>=Y.length)return G;return e($+X++)});if(X!==Y.length)throw TypeError(`[query-builder] SQL expression declares ${Y.length} parameters but contains only ${X} placeholders`);return{text:J,parameters:Y}}function vH(Z,...$){if(typeof Z==="string")return{raw:Z};let Y=Z[0];for(let X=0;X<$.length;X++)Y+=P8($[X])+Z[X+1];return{raw:Y}}function tZ(Z){return YZ(y.dialect)?`\`${Z.replace(/`/g,"``")}\``:`"${Z.replace(/"/g,'""')}"`}function $7(Z,$=1){let Y=Object.keys(Z[0]??{}),X=[],J=$,G=Z.map((U)=>{return`(${Y.map((z)=>{return X.push(U[z]),e(J++)}).join(", ")})`});return{colsSql:Y.map(tZ).join(", "),valuesSql:G.join(", "),params:X,nextIndex:J}}function i9(Z){return Boolean(Z&&(Z.onSlowQuery||Z.slowQueryThresholdMs!=null&&Z.slowQueryThresholdMs>=0))}function U8(Z,$=y.dialect){if(!YZ($))return Z;let Y=/^([A-Z_][\w$]*)(?:\.([A-Z_][\w$]*))?(?:\s+as\s+([A-Z_][\w$]*))?$/i.exec(Z.trim());if(!Y)return Z;let[,X,J,G]=Y,U=J?`\`${X}\`.\`${J}\``:`\`${X}\``;return G?`${U} AS \`${G}\``:U}function B6(Z,$=y.dialect){if(!YZ($)||Z===null||Z===void 0)return Z;if(typeof Z==="string"){let Y=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(Z);if(!Y)return Z;let[,X,J]=Y;return`${X} ${J.length===5?`${J}:00`:J}`}if(!(Z instanceof Date)||Number.isNaN(Z.getTime()))return Z;return Z.toISOString().replace("T"," ").replace(/\.\d+Z$/,"")}function vX(Z){if(typeof Z==="string")return U8(Z);if(R8(Z))return Z.raw;if(Z&&typeof Z==="object"){let $=Z;if(typeof $.raw==="function")return String($.raw());if(typeof $.sql==="string")return $.sql;let Y=String(Z);if(Y!=="[object Object]")return Y}throw TypeError(`[query-builder] select(): unsupported column ${String(Z)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function R6(Z){let $=/\(|\)|\bORDER\s+BY\b/gi,Y=0,X;while(X=$.exec(Z))if(X[0]==="(")Y++;else if(X[0]===")")Y=Math.max(0,Y-1);else if(Y===0)return!0;return!1}var VZ={SELECT_STAR:/^SELECT\s+\*/i,SELECT:/^SELECT\s+/i,SELECT_FROM:/^SELECT\s+(.+?)\s+FROM/i,WHERE:/\bWHERE\b/i,ORDER_BY:/\bORDER\s+BY\b/i,GROUP_BY:/\bGROUP\s+BY\b/i,LIMIT:/\sLIMIT\s+\d+/i,OFFSET:/\sOFFSET\s+\d+/i,IDENTIFIER:/^[A-Z_][\w.]*$/i,DELETED_AT:/\bdeleted_at\b/i},yX=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function o(Z,$){if(!VZ.IDENTIFIER.test(Z)){let Y=$?` in ${$}`:"";throw Error(`[query-builder] Invalid identifier${Y}: '${Z}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function kZ(Z,$){if(typeof Z!=="string")throw TypeError(`[query-builder] ${$}: operator must be a string, got ${typeof Z}`);let Y=Z.toLowerCase();if(!yX.has(Y))throw TypeError(`[query-builder] ${$}: refusing to use '${Z}' as a SQL operator \u2014 not in the allowed set (${[...yX].join(", ")})`);return Z}function G8(Z,$){if(typeof Z!=="string"||Z.length===0)throw TypeError(`[query-builder] ${$}: identifier must be a non-empty string, got ${typeof Z}`);if(Z.length>129)throw TypeError(`[query-builder] ${$}: identifier '${Z}' too long`);let Y=Z.split(".");if(Y.length>2)throw TypeError(`[query-builder] ${$}: identifier '${Z}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let X of Y)if(!/^[A-Z_][A-Z0-9_]*$/i.test(X))throw TypeError(`[query-builder] ${$}: identifier segment '${X}' contains characters outside [A-Za-z0-9_]`)}function $9(Z,$){if(typeof Z==="string")return O6($),Z;if(Z===null||Z===void 0)throw TypeError(`[query-builder] ${$}: fragment must be a SqlFragment, got ${Z}`);if(R8(Z))return Z.raw;if(typeof Z==="object"){let Y=Z;if(typeof Y.raw==="string")return Y.raw;if(typeof Y.raw==="function"){let J=Y.raw();if(typeof J==="string")return J}if(typeof Y.sql==="string")return Y.sql;let X=String(Z);if(X!=="[object Object]"&&X!=="[object Promise]")return X}throw TypeError(`[query-builder] ${$}: cannot render this value as a SQL fragment. `+"A Bun `sql`...`` query object cannot be converted to SQL text \u2014 pass a "+"string, or use the exported `raw` helper: raw`count(*) as c` / raw('age > 18').")}var hX=new Set;function O6(Z){if(hX.has(Z))return;hX.add(Z),console.warn(`[query-builder] ${Z}: bare string passed to a *Raw method. Prefer the \`raw\`...\`\` tagged template, which escapes interpolated `+"values for the configured dialect \u2014 concatenating request input into SQL "+"is an injection vector. This will become a hard error in a future release.")}function E6(Z,$=y.dialect){return YZ($)?Z.replace(/\\/g,"\\\\").replace(/'/g,"''"):Z.replace(/'/g,"''")}function P8(Z){if(Z===null)return"NULL";if(typeof Z==="number"&&Number.isFinite(Z))return String(Z);if(typeof Z==="boolean")return Z?"1":"0";if(typeof Z==="string")return`'${E6(Z)}'`;if(Z instanceof Date)return`'${Z.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof Z}`)}function D6(Z,$){let Y=Array.isArray(Z)?Z:Z?[Z]:[],X=[];if(Y.length)X.push(`PARTITION BY ${Y.join(", ")}`);if($&&$.length)X.push(`ORDER BY ${$.map(([J,G])=>`${J} ${G==="desc"?"DESC":"ASC"}`).join(", ")}`);return X.length?`OVER (${X.join(" ")})`:"OVER ()"}class bX{cache=new Map;maxSize=100;get(Z){let $=this.cache.get(Z);if(!$)return null;if(Date.now()>$.expiresAt)return this.cache.delete(Z),null;return this.cache.delete(Z),this.cache.set(Z,$),$.data}set(Z,$,Y){if(this.cache.has(Z))this.cache.delete(Z);if(this.cache.size>=this.maxSize){let X=Date.now(),J=!1;for(let[G,U]of this.cache)if(X>U.expiresAt){if(this.cache.delete(G),J=!0,this.cache.size<this.maxSize)break}if(!J){let G=this.cache.keys().next().value;if(G!==void 0)this.cache.delete(G)}}this.cache.set(Z,{data:$,expiresAt:Date.now()+Y})}clear(){this.cache.clear()}setMaxSize(Z){this.maxSize=Math.max(0,Math.floor(Z));while(this.cache.size>this.maxSize){let $=this.cache.keys().next().value;if($===void 0)break;this.cache.delete($)}}}var X7=new bX;function I6(Z){let $=String(Z?.message||"").toLowerCase();return $.includes("deadlock")||$.includes("serialization failure")||$.includes("could not serialize access")||$.includes("deadlock found when trying to get lock")||$.includes("lock wait timeout exceeded")||$.includes("database is locked")||$.includes("busy")}function M6(Z,$){if(!$||$.length===0)return!1;let Y=Z&&(Z.code||Z.sqlState||Z.sqlstate);if(!Y)return!1;return $.includes(Y)}function w6(Z){return new Promise(($)=>setTimeout($,Z))}var Y7=new Map,C6=500;function l9(Z){let $=Y7.get(Z);if($!==void 0)return $;let Y=S6(Z);if(Y7.size>=C6)Y7.clear();return Y7.set(Z,Y),Y}function S6(Z){let $=[{key:"GROUP_BY",tokens:/^GROUP\s+BY\b/i},{key:"ORDER_BY",tokens:/^ORDER\s+BY\b/i},{key:"HAVING",tokens:/^HAVING\b/i},{key:"OFFSET",tokens:/^OFFSET\b/i},{key:"LIMIT",tokens:/^LIMIT\b/i},{key:"WHERE",tokens:/^WHERE\b/i}],Y=[],X=0,J=!1,G="";for(let W=0;W<Z.length;W++){let Q=Z[W];if(J){if(Q===G){if(Z[W+1]===G){W++;continue}J=!1}continue}if(Q==="'"||Q==='"'||Q==="`"){J=!0,G=Q;continue}if(Q==="("){X++;continue}if(Q===")"){X--;continue}if(X!==0)continue;if(W===0||!/\s/.test(Z[W-1]))continue;let L=Z.charCodeAt(W)&-33;if(L!==71&&L!==79&&L!==72&&L!==76&&L!==87)continue;let O=Z.slice(W);for(let{key:T,tokens:w}of $){let K=O.match(w);if(!K)continue;Y.push({key:T,start:W}),W+=K[0].length-1;break}}if(Y.length<=1)return Z;let U=Z.slice(0,Y[0].start).trimEnd(),H={};for(let W=0;W<Y.length;W++){let Q=Y[W].start,L=W+1<Y.length?Y[W+1].start:Z.length,O=Z.slice(Q,L).trim();if(!H[Y[W].key])H[Y[W].key]=[];H[Y[W].key].push(O)}let A=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((W)=>H[W]).map((W)=>H[W].join(" ")).join(" ");return A?`${U} ${A}`:U}function N6(Z,$){let Y=Math.max(1,$?.baseMs??50),X=Math.max(1,$?.factor??2),J=Math.max(Y,$?.maxMs??2000),G=Math.min(J,Y*X**Math.max(0,Z-1));if($?.jitter)G=Math.min(J,G*(0.9+Math.random()*0.2));return Math.floor(G)}function JZ(Z){let $=Z?.sql??f8(),Y=Z?.meta,X=Z?.schema,J=(K,B)=>{let V=Y?.temporalColumns?.[K];if(!V||V.length===0||!YZ(y.dialect))return B;return B.map((F)=>{let I=null;for(let E of V){if(!(E in F))continue;let n=B6(F[E]);if(n!==F[E])I=I??{...F},I[E]=n}return I??F})};function G(K){if(typeof K==="number")return K;let B=String(K),V=7;for(let F=0;F<B.length;F++)V=V*31+B.charCodeAt(F)|0;return Math.abs(V)}function U(){if(!Z?.hooks)return y.hooks;return{...y.hooks,...Z.hooks}}let H=new Map;function z(K){if(Array.isArray(K)){let[E,n,x]=K;o(E,"where(column)");let d=String(E);switch(n){case"in":if(Array.isArray(x)){let P=NZ(x.length);return $.unsafe(`${d} IN (${P})`,x)}return $.unsafe(`${d} IN (${e(1)})`,[x]);case"not in":if(Array.isArray(x)){let P=NZ(x.length);return $.unsafe(`${d} NOT IN (${P})`,x)}return $.unsafe(`${d} NOT IN (${e(1)})`,[x]);case"like":return $.unsafe(`${d} LIKE ${e(1)}`,[x]);case"is":case"is not":{if(x!==null&&x!==void 0)throw TypeError(`[query-builder] where(..., '${n}', ?): operator '${n}' only accepts NULL/undefined as value, got ${typeof x} (${String(x)})`);return $.unsafe(`${d} IS ${n==="is not"?"NOT ":""}NULL`)}case"!=":return $.unsafe(`${d} <> ${e(1)}`,[x]);case"<":case">":case"<=":case">=":case"=":return $.unsafe(`${d} ${n} ${e(1)}`,[x]);default:throw TypeError(`[query-builder] where(..., '${String(n)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in K)return K.raw;let B=Object.keys(K);if(B.length===0)return $.unsafe("");let V=[],F=[],I=1;for(let E of B){o(E,"where(object key)");let n=K[E];if(Array.isArray(n)){let x=NZ(n.length,I);V.push(`${E} IN (${x})`),F.push(...n),I+=n.length}else V.push(`${E} = ${e(I++)}`),F.push(n)}return $.unsafe(V.join(" AND "),F)}function A(K,B,V){if(!V)return B;let F=z(V);return $`${B} WHERE ${F}`}function W(K){let B=y.debug?.captureText;if(y.debug)y.debug.captureText=!0;let V=String(K);if(y.debug)y.debug.captureText=B;return V}function Q(K){if(!K||typeof K!=="object")return;if(Array.isArray(K.values))return K.values;if(Array.isArray(K.parameters))return K.parameters;if(Array.isArray(K.params))return K.params;return}function L(K,B,V){let F=U(),I=F?.slowQueryThresholdMs,E=I!=null&&I>=0,n=Boolean(F?.onSlowQuery||E),x=F&&(F.onQueryStart||F.onQueryEnd||F.onQueryError||F.startSpan||n),d=V?.timeoutMs&&V.timeoutMs>0||V?.signal;if(!x&&!d)return K.execute();let P=W(K),M=Q(K),S=Date.now(),C;try{if(F?.onQueryStart?.({sql:P,params:M,kind:B}),F?.startSpan)C=F.startSpan({sql:P,params:M,kind:B})}catch{}let v=!1,i=(u,r)=>{if(v)return;v=!0;let b=Date.now()-S;try{if(u)F?.onQueryError?.({sql:P,params:M,error:u,durationMs:b,kind:B});else if(F?.onQueryEnd?.({sql:P,params:M,durationMs:b,rowCount:r,kind:B}),E&&b>=I)if(F?.onSlowQuery)F.onSlowQuery({sql:P,params:M,durationMs:b,kind:B});else console.warn(`[query-builder] slow query (${b}ms >= ${I}ms): ${P}`)}catch{}try{C?.end(u)}catch{}},m=K.execute(),q=[m],l;if(V?.timeoutMs&&V.timeoutMs>0){let u=new Promise((r,b)=>{l=setTimeout(()=>{try{K.cancel?.()}catch{}let c=Error(`Query timed out after ${V.timeoutMs}ms`);c.code="EBQBTIMEOUT",b(c)},V.timeoutMs)});q.push(u)}if(V?.signal){if(V.signal.aborted){try{K.cancel?.()}catch{}let r=Error("Query aborted");return r.code="EBQBABORT",i(r),Promise.reject(r)}let u=()=>{try{K.cancel?.()}catch{}};V.signal.addEventListener("abort",u,{once:!0}),m.finally(()=>{V.signal?.removeEventListener("abort",u)})}return Promise.race(q).then((u)=>{clearTimeout(l);let r=Array.isArray(u)?u.length:typeof u==="number"?u:void 0;return i(void 0,r),u}).catch((u)=>{throw clearTimeout(l),i(u),u})}function O(K){if(typeof K==="number")return Number.isFinite(K)?K:0;if(typeof K==="bigint")return Number(K);if(!K||typeof K!=="object")return 0;let B=K;for(let V of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(B[V]!==void 0&&B[V]!==null)return O(B[V]);if(Array.isArray(K))return K.reduce((V,F)=>V+O(F),0);return 0}function T(K,B){let V=B??W(K);return{sql:V,toString:()=>V,execute:()=>K.execute(),values:()=>K.values(),raw:()=>K.raw()}}function w(K,B){let V=$,F=B&&B.length>0?`SELECT ${B.join(", ")} FROM ${String(K)}`:`SELECT * FROM ${String(K)}`,I=[],E=[],n=!1,x=!1,d=!1,P=null,M=()=>{if(P===null){let j=l9(m());P=E.length>0?$.unsafe(j,E):$.unsafe(j)}return P},S=(j,_)=>{I.push({conn:j,sql:_}),P=null},C=(j,_)=>{S(j==="OR"?"OR":"AND",_)},v=/\(|\)|\b(?:GROUP\s+BY|HAVING|ORDER\s+BY|LIMIT|OFFSET|WINDOW|UNION|INTERSECT|EXCEPT|FOR\s+UPDATE|FOR\s+SHARE|LOCK\s+IN\s+SHARE\s+MODE)\b/gi,i=(j)=>{v.lastIndex=0;let _=0,R;while(R=v.exec(j))if(R[0]==="(")_++;else if(R[0]===")")_=Math.max(0,_-1);else if(_===0)return R.index;return-1},m=(j)=>{let _=Z9(j?[...I,j]:I);if(!_)return F;if(n)return`${F} ${x?"AND":"WHERE"} ${_}`;let R=i(F);return R>=0?`${F.slice(0,R)}WHERE ${_} ${F.slice(R)}`:`${F} WHERE ${_}`},q=(j,_)=>{let R=w(K);_(R);let D=R.__whereState?.();if(!D||!D.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let N=E.length,k=N>0&&y.dialect==="postgres"?D.body.replace(/\$(\d+)/g,(f,g)=>`$${Number(g)+N}`):D.body;E.push(...D.params),S(j,`(${k})`)},l=(j,_,R,D,N,k)=>{if(typeof D==="string"&&N!==void 0){o(String(D),`${R}(column)`),kZ(N,`${R}(operator)`);let f=E.length+1;return E.push(k),S(_,`${String(D)} ${String(N)} ${e(f)}`),j}if(Array.isArray(D)){let[f,g,s]=D,h=String(f);o(h,`${R}(column)`);let p=kZ(g,`${R}(operator)`);if(p==="in"||p==="not in"){let a=Array.isArray(s)?s:[s],UZ=NZ(a.length,E.length+1),PZ=rZ(U8(h),a,p==="not in",UZ);E.push(...a),S(_,PZ)}else{let a=E.length+1;E.push(s),S(_,`${h} ${p} ${e(a)}`)}return j}if(typeof D==="function")return q(_,D),j;if(D&&typeof D==="object"&&!("raw"in D)){let f=[];for(let g of Object.keys(D)){o(g,`${R}(column)`);let s=D[g];if(Array.isArray(s)){let h=NZ(s.length,E.length+1);f.push(rZ(U8(g),s,!1,h)),E.push(...s)}else{let h=E.length+1;f.push(`${g} = ${e(h)}`),E.push(s)}}if(f.length>0)S(_,f.length>1?`(${f.join(" AND ")})`:f[0]);return j}if(D&&typeof D.raw<"u")return S(_,D.raw),j;return j},u=(j,_)=>{if(I.length>0)F=m(),I.length=0;n=!0;let R=_.__rawState?.();if(R){let D=E.length,N=y.dialect==="postgres"?R.sql.replace(/\$(\d+)/g,(k,f)=>`$${Number(f)+D}`):R.sql;F+=` ${j} ${N}`,E.push(...R.params),x=_.__hasPredicate?.()??VZ.WHERE.test(N)}else{let D=String(_.toSQL());F+=` ${j} ${D}`,x=_.__hasPredicate?.()??VZ.WHERE.test(D)}P=null},r=(j)=>{let _=/\(|\)|\b(?:WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET|UNION)\b/gi,R=0,D=-1,N;while(N=_.exec(F))if(N[0]==="(")R++;else if(N[0]===")")R=Math.max(0,R-1);else if(R===0){D=N.index;break}F=D>=0?`${F.slice(0,D)}${j} ${F.slice(D)}`:`${F} ${j}`,P=null},b=new Set,c,t,GZ=!1,FZ=!1,mZ=!1,E8=new Map,Y8=new Set,X$=60000,EZ=(j)=>d8(y.relations.singularizeStrategy)(j),V8=(j)=>{if(!Y)return null;return e8(Y,String(K),j,{singularize:EZ,models:Y.models})},D8=(j)=>{if(!j||typeof j!=="object"||Y8.size===0)return j;let _;for(let R of Object.keys(j))if(R.startsWith("pivot_")){if(!_)_={};_[R.slice(6)]=j[R],delete j[R]}if(_)j.pivot=_;return j},P9=(j)=>{if(Y8.size===0||!j)return j;if(Array.isArray(j))for(let _=0;_<j.length;_++)D8(j[_]);else D8(j);return j},T9=(j)=>{if(!Y)return;if(b.has(j.pivotTable))return;let _=String(K),R=Y.primaryKeys[_]??"id";o(j.pivotTable,"wherePivot auto-join (pivot table)"),o(j.fkParent,"wherePivot auto-join (parent FK)"),o(_,"wherePivot auto-join (parent table)"),o(R,"wherePivot auto-join (parent PK)"),P=V`${M()} LEFT JOIN ${V(j.pivotTable)} ON ${V(`${j.pivotTable}.${j.fkParent}`)} = ${V(`${_}.${R}`)}`,F=`${F} LEFT JOIN ${j.pivotTable} ON ${j.pivotTable}.${j.fkParent} = ${_}.${R}`,b.add(j.pivotTable)},q9=(j)=>{if(VZ.SELECT_STAR.test(F))F=F.replace(VZ.SELECT_STAR,`SELECT *, ${j}`);else if(VZ.SELECT.test(F))F=F.replace(VZ.SELECT_FROM,`SELECT $1, ${j} FROM`);let _=String(M());if(VZ.SELECT_STAR.test(_)){let R=_.replace(VZ.SELECT_STAR,`SELECT *, ${j}`);P=$.unsafe(R)}else if(VZ.SELECT.test(_)){if(VZ.SELECT_FROM.exec(_)){let D=_.replace(VZ.SELECT_FROM,`SELECT $1, ${j} FROM`);P=$.unsafe(D)}}},K8=(j,_,R,D)=>{q9(`${j} ${D6(R,D)} AS ${_}`)},J$=(j,_,R,D)=>{o(j,"relationship subquery (parent table)"),o(_,"relationship subquery (target table)"),o(R,"relationship subquery (primary key)");let N=`${j.endsWith("s")?j.slice(0,-1):j}_id`;o(N,"relationship subquery (foreign key)");let k=`SELECT 1 FROM ${_} WHERE ${_}.${N} = ${j}.${R}`;if(D){let g=D({where:(s,h,p)=>{return o(s,"relationship subquery condition"),`${_}.${s} ${kZ(h,"whereHas callback")} ${P8(p)}`}});if(g)k+=` AND ${g}`}return k},G$=(j,_,R,D)=>{o(j,"relationship subquery (parent table)"),o(_,"relationship subquery (target table)"),o(R,"relationship subquery (primary key)");let N=`${_.endsWith("s")?_.slice(0,-1):_}_id`;o(N,"relationship subquery (foreign key)");let k=`SELECT 1 FROM ${_} WHERE ${_}.${R} = ${j}.${N}`;if(D){let g=D({where:(s,h,p)=>{return o(s,"relationship subquery condition"),`${_}.${s} ${kZ(h,"whereHas callback")} ${P8(p)}`}});if(g)k+=` AND ${g}`}return k},U$=(j,_,R,D,N,k)=>{o(j,"relationship subquery (parent table)"),o(_,"relationship subquery (target table)"),o(R,"relationship subquery (primary key)"),o(D,"relationship subquery (target primary key)");let f=k&&Y?e8(Y,j,k,{singularize:EZ,models:Y.models}):null,g=EZ(j),s=EZ(_),h=f?.pivotTable??[g,s].sort().join("_"),p=f?.fkParent??`${g}_id`,a=f?.fkRelated??`${s}_id`;o(h,"relationship subquery (pivot table)"),o(p,"relationship subquery (foreign key A)"),o(a,"relationship subquery (foreign key B)");let UZ=`SELECT 1 FROM ${h} JOIN ${_} ON ${_}.${D} = ${h}.${a} WHERE ${h}.${p} = ${j}.${R}`;if(N){let ZZ=N({where:(TZ,uZ,lZ)=>{return o(TZ,"relationship subquery condition"),`${_}.${TZ} ${kZ(uZ,"whereHas callback")} ${P8(lZ)}`}});if(ZZ)UZ+=` AND ${ZZ}`}return UZ},PJ=(j,_,R)=>{o(j,"withCount (parent table)"),o(_,"withCount (target table)"),o(R,"withCount (primary key)");let D=`${j.endsWith("s")?j.slice(0,-1):j}_id`;return o(D,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${_} WHERE ${_}.${D} = ${j}.${R})`},TJ=(j,_,R,D)=>{o(j,"withCount (parent table)"),o(_,"withCount (target table)"),o(R,"withCount (primary key)");let N=D&&Y?e8(Y,j,D,{singularize:EZ,models:Y.models}):null,k=EZ(j),f=EZ(_),g=N?.pivotTable??[k,f].sort().join("_"),s=N?.fkParent??`${k}_id`;return o(g,"withCount (pivot table)"),o(s,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${g} WHERE ${g}.${s} = ${j}.${R})`},z$=(j,_,R)=>{if(!Y)return;o(R,`with${j[0]}${j.slice(1).toLowerCase()} (column)`);let D=String(K),N=Y.relations?.[D];if(!N)return;let k=Object.entries(N).find(([ZZ,TZ])=>TZ&&typeof TZ==="object"&&(_ in TZ));if(!k)return;let[f,g]=k,s=g[_],h=typeof s==="string"?s:s?.model||s?.target||s,p=Y.modelToTable[h]||h,a=Y.primaryKeys[D]??"id";o(p,`with${j} (target table)`);let UZ=`${j}(${p}.${R})`,PZ;if(f==="hasMany"||f==="hasOne"){let ZZ=`${D.endsWith("s")?D.slice(0,-1):D}_id`;o(ZZ,`with${j} (foreign key)`),PZ=`(SELECT ${UZ} FROM ${p} WHERE ${p}.${ZZ} = ${D}.${a})`}else if(f==="belongsToMany"){let ZZ=Y?e8(Y,D,_,{singularize:EZ,models:Y.models}):null,TZ=EZ(D),uZ=EZ(p),lZ=ZZ?.pivotTable??[TZ,uZ].sort().join("_"),cZ=ZZ?.fkParent??`${TZ}_id`,zZ=ZZ?.fkRelated??`${uZ}_id`,k9=Y.primaryKeys[p]??"id";o(lZ,`with${j} (pivot table)`),o(cZ,`with${j} (foreign key)`),o(zZ,`with${j} (related key)`),PZ=`(SELECT ${UZ} FROM ${lZ} JOIN ${p} ON ${p}.${k9} = ${lZ}.${zZ} WHERE ${lZ}.${cZ} = ${D}.${a})`}else return;q9(`${PZ} AS ${_}_${j.toLowerCase()}_${R}`)},m0=()=>{if(E8.size===0)return;let j=[];for(let[_,R]of E8.entries()){let D=V8(_);if(!D)continue;for(let k of R)o(k,"withPivot");let N=R.map((k)=>`${D.pivotTable}.${k} AS pivot_${k}`);j.push(...N)}if(j.length>0){let _=j.join(", ");q9(_)}};return new Proxy({distinct(){return F=F.replace(/^SELECT\s+/i,"SELECT DISTINCT "),P=null,this},distinctOn(...j){let _=j.map(String).join(", ");return F=F.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${_}) `),P=null,this},selectRaw(j){let _=$9(j,"selectRaw(fragment)"),R=F.indexOf(" FROM ");if(R!==-1)F=`${F.substring(0,R)}, ${_}${F.substring(R)}`;else F+=`, ${_}`;return P=null,this},rowNumber(j="row_number",_,R){let D=[];if(_){let g=Array.isArray(_)?_:[_];D.push(`PARTITION BY ${g.join(", ")}`)}if(R&&R.length)D.push(`ORDER BY ${R.map(([g,s])=>`${g} ${s==="desc"?"DESC":"ASC"}`).join(", ")}`);let k=`ROW_NUMBER() ${D.length?`OVER (${D.join(" ")})`:"OVER ()"} AS ${j}`,f=F.indexOf(" FROM ");if(f!==-1)F=`${F.substring(0,f)}, ${k}${F.substring(f)}`;else F+=`, ${k}`;return P=null,this},denseRank(j="dense_rank",_,R){let D=Array.isArray(_)?_:_?[_]:[],N=[];if(D.length)N.push(`PARTITION BY ${D.join(", ")}`);if(R&&R.length)N.push(`ORDER BY ${R.map(([s,h])=>`${s} ${h==="desc"?"DESC":"ASC"}`).join(", ")}`);let f=`DENSE_RANK() ${N.length?`OVER (${N.join(" ")})`:"OVER ()"} AS ${j}`,g=F.indexOf(" FROM ");if(g!==-1)F=`${F.substring(0,g)}, ${f}${F.substring(g)}`;else F+=`, ${f}`;return P=null,this},rank(j="rank",_,R){let D=Array.isArray(_)?_:_?[_]:[],N=[];if(D.length)N.push(`PARTITION BY ${D.join(", ")}`);if(R&&R.length)N.push(`ORDER BY ${R.map(([s,h])=>`${s} ${h==="desc"?"DESC":"ASC"}`).join(", ")}`);let f=`RANK() ${N.length?`OVER (${N.join(" ")})`:"OVER ()"} AS ${j}`,g=F.indexOf(" FROM ");if(g!==-1)F=`${F.substring(0,g)}, ${f}${F.substring(g)}`;else F+=`, ${f}`;return P=null,this},over(j,_,R={}){return K8(j,_,R.partitionBy,R.orderBy),this},lag(j,_={}){let R=[j,String(_.offset??1)];if(_.defaultValue!==void 0)R.push(String(_.defaultValue));return K8(`LAG(${R.join(", ")})`,_.alias??`${j}_lag`,_.partitionBy,_.orderBy),this},lead(j,_={}){let R=[j,String(_.offset??1)];if(_.defaultValue!==void 0)R.push(String(_.defaultValue));return K8(`LEAD(${R.join(", ")})`,_.alias??`${j}_lead`,_.partitionBy,_.orderBy),this},sumOver(j,_={}){return K8(`SUM(${j})`,_.alias??`${j}_sum`,_.partitionBy,_.orderBy),this},avgOver(j,_={}){return K8(`AVG(${j})`,_.alias??`${j}_avg`,_.partitionBy,_.orderBy),this},countOver(j="*",_={}){return K8(`COUNT(${j})`,_.alias??"count_over",_.partitionBy,_.orderBy),this},minOver(j,_={}){return K8(`MIN(${j})`,_.alias??`${j}_min`,_.partitionBy,_.orderBy),this},maxOver(j,_={}){return K8(`MAX(${j})`,_.alias??`${j}_max`,_.partitionBy,_.orderBy),this},firstValue(j,_={}){return K8(`FIRST_VALUE(${j})`,_.alias??`${j}_first`,_.partitionBy,_.orderBy),this},lastValue(j,_={}){return K8(`LAST_VALUE(${j})`,_.alias??`${j}_last`,_.partitionBy,_.orderBy),this},selectAll(){return this},select(j){if(!j)return this;let _=Array.isArray(j)?j:[j];if(_.length===0)return this;let R=_.map(vX),D=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(F),N=D?D[1]:"",k=F.indexOf(" FROM ");if(k!==-1)F=`SELECT ${N}${R.join(", ")}${F.substring(k)}`;else F=`SELECT ${N}${R.join(", ")} FROM ${K}`;return P=null,this},addSelect(...j){if(!j.length)return this;let _=j.map(vX),R=F.indexOf(" FROM ");if(R!==-1)F=`${F.substring(0,R)}, ${_.join(", ")}${F.substring(R)}`;else F+=`, ${_.join(", ")}`;return P=null,this},with(...j){if(!Y||!j||j.length===0)return this;let _=[];for(let h of j){if(!h)continue;if(typeof h==="string")_.push({name:h});else if(typeof h==="object"&&!Array.isArray(h))for(let[p,a]of Object.entries(h))if(typeof a==="function")_.push({name:p,callback:a});else _.push({name:p})}if(_.length===0)return this;let R=y.relations.maxEagerLoad??50;if(_.length>R)throw Error(`[query-builder] Too many relationships to eager load (${_.length}). Maximum allowed: ${R}`);let D=String(K),N=new Set,k=new Set,f=new Map,g=(h)=>{let p=Y.relations?.[h];if(!p)return[];return[...Object.keys(p.hasOne||{}),...Object.keys(p.hasMany||{}),...Object.keys(p.belongsTo||{}),...Object.keys(p.belongsToMany||{}),...Object.keys(p.hasOneThrough||{}),...Object.keys(p.hasManyThrough||{}),...Object.keys(p.morphOne||{}),...Object.keys(p.morphMany||{}),...Object.keys(p.morphToMany||{}),...Object.keys(p.morphedByMany||{})]},s=(h,p,a=0,UZ)=>{let PZ=y.relations.maxDepth??10;if(a>=PZ)throw Error(`[query-builder] Maximum relationship depth (${PZ}) exceeded at '${p}'. Consider using separate queries or increasing maxDepth.`);let ZZ=Y.relations?.[h];if(!ZZ)return h;let TZ=(HZ)=>{if(y.softDeletes?.enabled&&y.softDeletes?.defaultFilter){let AZ=y.softDeletes.column||"deleted_at";return` AND ${HZ}.${AZ} IS NULL`}return""},uZ=(HZ)=>{if(!UZ)return"";let AZ=[],MZ=(jZ,sZ,L8)=>{o(String(jZ),"with() constraint column");let z9=kZ(sZ,"with() constraint operator");AZ.push(`${HZ}.${String(jZ)} ${z9} ${P8(L8)}`)},RZ=(jZ)=>()=>{throw Error(`[query-builder] with('${p}', ...): ${jZ} is not supported inside a constraint callback on the JOIN-based builder \u2014 apply it to the outer query, or use the model layer's eager loading. (Silently ignoring it would return wrong data.)`)},CZ={where:(jZ,sZ,L8)=>{if(Array.isArray(jZ))MZ(jZ[0],jZ[1],jZ[2]);else if(jZ&&typeof jZ==="object")for(let z9 of Object.keys(jZ))MZ(z9,"=",jZ[z9]);else if(sZ!==void 0&&L8!==void 0)MZ(jZ,sZ,L8);else if(sZ!==void 0)MZ(jZ,"=",sZ);return CZ},whereIn:(jZ,sZ)=>{return o(String(jZ),"with() constraint column"),AZ.push(`${HZ}.${String(jZ)} IN (${sZ.map(P8).join(", ")})`),CZ},whereNull:(jZ)=>{return o(String(jZ),"with() constraint column"),AZ.push(`${HZ}.${String(jZ)} IS NULL`),CZ},whereNotNull:(jZ)=>{return o(String(jZ),"with() constraint column"),AZ.push(`${HZ}.${String(jZ)} IS NOT NULL`),CZ},orderBy:RZ("orderBy()"),limit:RZ("limit()"),offset:RZ("offset()"),take:RZ("take()")};return UZ(CZ),AZ.length?` AND ${AZ.join(" AND ")}`:""},lZ=()=>{let HZ=(RZ)=>{let CZ=RZ?.[p];return CZ?Y.modelToTable[CZ]:void 0},AZ=(RZ)=>{let CZ=RZ?.[p],jZ=typeof CZ==="string"?CZ:CZ?.model;return jZ?Y.modelToTable[jZ]:void 0},MZ=(RZ)=>{let CZ=RZ?.[p];return CZ?.target?Y.modelToTable[CZ.target]:void 0};return HZ(ZZ?.hasOne)||HZ(ZZ?.hasMany)||HZ(ZZ?.belongsTo)||AZ(ZZ?.belongsToMany)||MZ(ZZ?.hasOneThrough)||MZ(ZZ?.hasManyThrough)||HZ(ZZ?.morphOne)||HZ(ZZ?.morphMany)||HZ(ZZ?.morphToMany)||HZ(ZZ?.morphedByMany)},cZ=lZ()??(Y.modelToTable[p]||Y.tableToModel[p]?Y.modelToTable[p]??p:p),zZ=String(cZ);if(!cZ||!lZ()&&!Y.modelToTable[p]&&!Y.tableToModel[p]){let HZ=g(h);if(HZ.length>0&&!HZ.includes(p)){let AZ=` Available relationships: ${HZ.join(", ")}`;throw Error(`[query-builder] Relationship '${p}' not found on table '${h}'.${AZ}`)}}if(y.relations.detectCycles!==!1){let HZ=`${h}->${zZ}`;if(N.has(HZ))throw Error(`[query-builder] Circular relationship detected: ${HZ}. This would cause an infinite loop.`);N.add(HZ)}if(!zZ||zZ===h)return h;let k9=ZZ?.hasOneThrough?.[p]||ZZ?.hasManyThrough?.[p];if(k9){let{through:HZ,target:AZ}=k9,MZ=Y.modelToTable[HZ]||HZ,RZ=Y.modelToTable[AZ]||AZ,CZ=Y.primaryKeys[h]??"id",jZ=Y.primaryKeys[MZ]??"id",sZ=`${EZ(h)}_id`,L8=`${EZ(MZ)}_id`;return r(`LEFT JOIN ${MZ} ON ${MZ}.${sZ} = ${h}.${CZ} LEFT JOIN ${RZ} ON ${RZ}.${L8} = ${MZ}.${jZ}`),b.add(MZ),b.add(RZ),RZ}if(Boolean(ZZ?.belongsToMany?.[p])){let HZ=e8(Y,h,p,{singularize:EZ,models:Y.models}),AZ=HZ?.pivotTable??[EZ(h),EZ(zZ)].sort().join("_"),MZ=Y.primaryKeys[h]??"id",RZ=Y.primaryKeys[zZ]??"id",CZ=HZ?.fkParent??`${EZ(h)}_id`,jZ=HZ?.fkRelated??`${EZ(zZ)}_id`;return r(`LEFT JOIN ${AZ} ON ${AZ}.${CZ} = ${h}.${MZ} LEFT JOIN ${zZ} ON ${zZ}.${RZ} = ${AZ}.${jZ}${uZ(zZ)}`),b.add(AZ),b.add(zZ),zZ}if(Boolean(ZZ?.morphToMany?.[p])){let HZ=p,AZ=`${EZ(zZ)}_${HZ}`,MZ=Y.primaryKeys[h]??"id",RZ=Y.primaryKeys[zZ]??"id",CZ=`${HZ}_type`,jZ=`${HZ}_id`,sZ=`${EZ(zZ)}_id`,L8=P8(Y.tableToModel[h]||h);return r(`LEFT JOIN ${AZ} ON ${AZ}.${jZ} = ${h}.${MZ} AND ${AZ}.${CZ} = ${L8} LEFT JOIN ${zZ} ON ${zZ}.${RZ} = ${AZ}.${sZ}`),b.add(AZ),b.add(zZ),zZ}if(Boolean(ZZ?.morphedByMany?.[p])){let HZ=ZZ.morphedByMany?.[p]||p,AZ=Y.modelToTable[HZ]||HZ,MZ=EZ(h),RZ=`${EZ(AZ)}_${MZ}`,CZ=Y.primaryKeys[h]??"id",jZ=Y.primaryKeys[AZ]??"id",sZ=`${MZ}_type`,L8=`${MZ}_id`,z9=`${EZ(AZ)}_id`,hJ=P8(Y.tableToModel[AZ]||AZ);return r(`LEFT JOIN ${RZ} ON ${RZ}.${z9} = ${h}.${CZ} LEFT JOIN ${AZ} ON ${AZ}.${jZ} = ${RZ}.${L8} AND ${RZ}.${sZ} = ${hJ}`),b.add(RZ),b.add(AZ),AZ}if(Boolean(ZZ?.belongsTo?.[p])){let HZ=`${EZ(zZ)}_id`,AZ=Y.primaryKeys[zZ]??"id";return r(`LEFT JOIN ${zZ} ON ${h}.${HZ} = ${zZ}.${AZ}${uZ(zZ)}`),b.add(zZ),zZ}let qJ=Boolean(ZZ?.morphOne?.[p]),kJ=Boolean(ZZ?.morphMany?.[p]);if(qJ||kJ){let HZ=`${p}_type`,AZ=`${p}_id`,MZ=Y.primaryKeys[h]??"id",RZ=P8(Y.tableToModel[h]||h);return r(`LEFT JOIN ${zZ} ON ${zZ}.${AZ} = ${h}.${MZ} AND ${zZ}.${HZ} = ${RZ}`),b.add(zZ),zZ}let xJ=`${EZ(h)}_id`,vJ=Y.primaryKeys[h]??"id",yJ=`${TZ(zZ)}${uZ(zZ)}`;return r(`LEFT JOIN ${zZ} ON ${zZ}.${xJ} = ${h}.${vJ}${yJ}`),b.add(zZ),zZ};for(let h of _){let p=h.name.trim();if(h.callback)f.set(p,h.callback);let a=p.split("."),UZ=D,PZ=0;for(let ZZ of a){if(!ZZ||ZZ.trim().length===0)continue;let TZ=ZZ.trim(),uZ=f.get(TZ);UZ=s(UZ,TZ,PZ,uZ)||UZ,PZ++}k.add(p)}if(E8.size>0){let h=[];for(let[p,a]of E8.entries()){let UZ=V8(p);if(!UZ)continue;let PZ=a.map((ZZ)=>`${UZ.pivotTable}.${ZZ} AS pivot_${ZZ}`);h.push(...PZ)}if(h.length>0){let p=h.join(", ");q9(p)}}return P=null,this},whereHas(j,_){if(!Y)return this;let R=String(K),D=Y.relations?.[R];if(!D)throw Error(`[query-builder] No relationships defined for table '${R}'`);let N=Object.entries(D).find(([a,UZ])=>UZ&&typeof UZ==="object"&&(j in UZ));if(!N)throw Error(`[query-builder] Relationship '${j}' not found on table '${R}'`);let[k,f]=N,g=f[j],s=typeof g==="string"?g:g?.model||g?.target||g,h=Y.modelToTable[s]||s,p;if(k==="hasMany"||k==="hasOne"){let a=Y.primaryKeys[R]??"id";p=J$(R,h,a,_)}else if(k==="belongsTo"){let a=Y.primaryKeys[h]??"id";p=G$(R,h,a,_)}else if(k==="belongsToMany"){let a=Y.primaryKeys[R]??"id",UZ=Y.primaryKeys[h]??"id";p=U$(R,h,a,UZ,_,j)}else throw Error(`[query-builder] Unsupported relationship type '${k}' for whereHas`);return C("WHERE",`EXISTS (${p})`),this},whereDoesntHave(j,_){if(!Y)return this;let R=String(K),D=Y.relations?.[R];if(!D)throw Error(`[query-builder] No relationships defined for table '${R}'`);let N=Object.entries(D).find(([a,UZ])=>UZ&&typeof UZ==="object"&&(j in UZ));if(!N)throw Error(`[query-builder] Relationship '${j}' not found on table '${R}'`);let[k,f]=N,g=f[j],s=typeof g==="string"?g:g?.model||g?.target||g,h=Y.modelToTable[s]||s,p;if(k==="hasMany"||k==="hasOne"){let a=Y.primaryKeys[R]??"id";p=J$(R,h,a,_)}else if(k==="belongsTo"){let a=Y.primaryKeys[h]??"id";p=G$(R,h,a,_)}else if(k==="belongsToMany"){let a=Y.primaryKeys[R]??"id",UZ=Y.primaryKeys[h]??"id";p=U$(R,h,a,UZ,_,j)}else throw Error(`[query-builder] Unsupported relationship type '${k}' for whereDoesntHave`);return C("WHERE",`NOT EXISTS (${p})`),this},has(j){if(!Y)return this;let _=String(K),R=Y.relations?.[_];if(!R)throw Error(`[query-builder] No relationships defined for table '${_}'`);let D=Object.entries(R).find(([p,a])=>a&&typeof a==="object"&&(j in a));if(!D)throw Error(`[query-builder] Relationship '${j}' not found on table '${_}'`);let[N,k]=D,f=k[j],g=typeof f==="string"?f:f?.model||f?.target||f,s=Y.modelToTable[g]||g,h;if(N==="hasMany"||N==="hasOne"){let p=Y.primaryKeys[_]??"id";h=J$(_,s,p)}else if(N==="belongsTo"){let p=Y.primaryKeys[s]??"id";h=G$(_,s,p)}else if(N==="belongsToMany"){let p=Y.primaryKeys[_]??"id",a=Y.primaryKeys[s]??"id";h=U$(_,s,p,a,void 0,j)}else throw Error(`[query-builder] Unsupported relationship type '${N}' for has`);return C("WHERE",`EXISTS (${h})`),this},doesntHave(j){if(!Y)return this;let _=String(K),R=Y.relations?.[_];if(!R)throw Error(`[query-builder] No relationships defined for table '${_}'`);let D=Object.entries(R).find(([p,a])=>a&&typeof a==="object"&&(j in a));if(!D)throw Error(`[query-builder] Relationship '${j}' not found on table '${_}'`);let[N,k]=D,f=k[j],g=typeof f==="string"?f:f?.model||f?.target||f,s=Y.modelToTable[g]||g,h;if(N==="hasMany"||N==="hasOne"){let p=Y.primaryKeys[_]??"id";h=J$(_,s,p)}else if(N==="belongsTo"){let p=Y.primaryKeys[s]??"id";h=G$(_,s,p)}else if(N==="belongsToMany"){let p=Y.primaryKeys[_]??"id",a=Y.primaryKeys[s]??"id";h=U$(_,s,p,a,void 0,j)}else throw Error(`[query-builder] Unsupported relationship type '${N}' for doesntHave`);return C("WHERE",`NOT EXISTS (${h})`),this},withCount(...j){if(!Y||!j||j.length===0)return this;let _=String(K);for(let R of j){let D=Y.relations?.[_];if(!D)continue;let N=Object.entries(D).find(([PZ,ZZ])=>ZZ&&typeof ZZ==="object"&&(R in ZZ));if(!N)continue;let[k,f]=N,g=f[R],s=typeof g==="string"?g:g?.model||g?.target||g,h=Y.modelToTable[s]||s,p=Y.primaryKeys[_]??"id",a;if(k==="hasMany"||k==="hasOne")a=PJ(_,h,p);else if(k==="belongsToMany")a=TJ(_,h,p,R);else continue;let UZ=`${R}_count`;q9(`${a} AS ${UZ}`)}return this},withSum(j,_){return z$("SUM",j,_),this},withAvg(j,_){return z$("AVG",j,_),this},withMax(j,_){return z$("MAX",j,_),this},withMin(j,_){return z$("MIN",j,_),this},applyPivotColumns(){return m0(),this},withPivot(j,..._){if(!Y)return this;let R=String(K),D=V8(j);if(!D)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${R}'`);let N=_&&_.length>0?_:D.hasConfig?D.pivotColumns:[];if(N.length===0)return this;if(E8.set(j,N),D.hasConfig)Y8.add(j);return m0(),this},wherePivot(j,_,R,D){if(!Y)return this;let N=V8(j);if(!N)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(K)}'`);o(N.pivotTable,"wherePivot (pivot table)"),o(_,"wherePivot (column)"),T9(N);let k=D===void 0?"=":String(R),f=D===void 0?R:D,g=E.length+1,s=`${N.pivotTable}.${_} ${k} ${e(g)}`;if(E.push(f),S("AND",s),N.hasConfig)Y8.add(j);return this},wherePivotIn(j,_,R){if(!Y||!Array.isArray(R))return this;let D=V8(j);if(!D)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(K)}'`);o(D.pivotTable,"wherePivotIn (pivot table)"),o(_,"wherePivotIn (column)"),T9(D);let N=NZ(R.length,E.length+1),k=rZ(`${D.pivotTable}.${_}`,R,!1,N);if(E.push(...R),S("AND",k),D.hasConfig)Y8.add(j);return this},wherePivotNotIn(j,_,R){if(!Y||!Array.isArray(R)||R.length===0)return this;let D=V8(j);if(!D)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(K)}'`);o(D.pivotTable,"wherePivotNotIn (pivot table)"),o(_,"wherePivotNotIn (column)"),T9(D);let N=NZ(R.length,E.length+1),k=`${D.pivotTable}.${_} NOT IN (${N})`;if(E.push(...R),S("AND",k),D.hasConfig)Y8.add(j);return this},wherePivotNull(j,_){if(!Y)return this;let R=V8(j);if(!R)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(K)}'`);if(o(R.pivotTable,"wherePivotNull (pivot table)"),o(_,"wherePivotNull (column)"),T9(R),S("AND",`${R.pivotTable}.${_} IS NULL`),R.hasConfig)Y8.add(j);return this},wherePivotNotNull(j,_){if(!Y)return this;let R=V8(j);if(!R)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(K)}'`);if(o(R.pivotTable,"wherePivotNotNull (pivot table)"),o(_,"wherePivotNotNull (column)"),T9(R),S("AND",`${R.pivotTable}.${_} IS NOT NULL`),R.hasConfig)Y8.add(j);return this},where(j,_,R){if(typeof j==="string"&&_!==void 0){o(String(j),"where(column)"),kZ(_,"where(operator)");let D=String(_).toLowerCase();if(D==="in"||D==="not in"){let k=Array.isArray(R)?R:[R],f=NZ(k.length,E.length+1),g=rZ(U8(String(j)),k,D==="not in",f);return E.push(...k),S("AND",g),this}let N=E.length+1;return E.push(R),S("AND",`${U8(String(j))} ${String(_)} ${e(N)}`),this}if(Array.isArray(j)){let[D,N,k]=j,f=String(D);o(f,"where(column)");let g=kZ(N,"where(operator)");if(g==="in"||g==="not in"){let s=Array.isArray(k)?k:[k],h=NZ(s.length,E.length+1),p=rZ(U8(f),s,g==="not in",h);E.push(...s),S("AND",p)}else{let s=E.length+1;E.push(k),S("AND",`${U8(f)} ${g} ${e(s)}`)}return this}if(j&&typeof j==="object"&&!R8(j)){let D=j,N=Object.keys(D),k=[];for(let f of N){o(f,"where(column)");let g=D[f];if(Array.isArray(g)){let s=NZ(g.length,E.length+1);k.push(rZ(U8(f),g,!1,s)),E.push(...g)}else{let s=E.length+1;k.push(`${U8(f)} = ${e(s)}`),E.push(g)}}if(k.length>0)S("AND",k.length>1?`(${k.join(" AND ")})`:k[0]);return this}if(R8(j))return S("AND",j.raw),this;if(typeof j==="function")return q("AND",j),this;if(j===void 0||j===null)throw TypeError("where() was called with no condition.");if(typeof j==="string")throw TypeError(`where(${JSON.stringify(j)}) is missing an operator and a value. Pass where(column, operator, value), or whereRaw() for a raw fragment.`);throw TypeError(`where() does not understand a condition of type ${typeof j}.`)},whereNull(j){return o(String(j),"whereNull(column)"),S("AND",`${String(j)} IS NULL`),this},whereNotNull(j){return o(String(j),"whereNotNull(column)"),S("AND",`${String(j)} IS NOT NULL`),this},orWhereNull(j){return o(String(j),"orWhereNull(column)"),S("OR",`${String(j)} IS NULL`),this},orWhereNotNull(j){return o(String(j),"orWhereNotNull(column)"),S("OR",`${String(j)} IS NOT NULL`),this},whereBetween(j,_,R){o(String(j),"whereBetween(column)");let D=E.length+1;return E.push(_,R),S("AND",`${String(j)} BETWEEN ${e(D)} AND ${e(D+1)}`),this},orWhereBetween(j,_,R){o(String(j),"orWhereBetween(column)");let D=E.length+1;return E.push(_,R),S("OR",`${String(j)} BETWEEN ${e(D)} AND ${e(D+1)}`),this},whereExists(j){return S("AND",`EXISTS (${j.toSQL()})`),this},orWhereExists(j){return S("OR",`EXISTS (${j.toSQL()})`),this},whereGroup(j){return q("AND",j),this},orWhereGroup(j){return q("OR",j),this},__whereState(){return{body:Z9(I),params:[...E]}},whereJsonContains(j,_){o(String(j),"whereJsonContains(column)");let R=y.dialect,D=E.length+1;if(R==="postgres"){let k=typeof _==="number"||typeof _==="boolean"?`to_jsonb(${e(D)})`:e(D);if(y.sql?.jsonContainsMode==="function")S("AND",`jsonb_contains(${j}, ${k})`);else S("AND",`${j} @> ${k}`);E.push(_)}else if(YZ(R))S("AND",`JSON_CONTAINS(${j}, ${e(D)})`),E.push(JSON.stringify(_));else if(Array.isArray(_)){let N=_.map((k,f)=>`EXISTS (SELECT 1 FROM json_each(${j}) WHERE json_each.value = ${e(D+f)})`);S("AND",`(${N.join(" AND ")})`);for(let k of _)E.push(k)}else if(_!==null&&typeof _==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else S("AND",`EXISTS (SELECT 1 FROM json_each(${j}) WHERE json_each.value = ${e(D)})`),E.push(_);return this},whereJsonPath(j,_,R){if(kZ(_,"whereJsonPath(op)"),typeof j!=="string"||j.length===0||j.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof j==="string"?`'${j.slice(0,32)}...'`:typeof j}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(j))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${j}' \u2014 contains characters outside the allowed JSON-path set`);let D=y.dialect,N=E.length+1;if(D==="postgres")S("AND",`${j} ${_} ${e(N)}`);else if(YZ(D))S("AND",`JSON_EXTRACT(${j}) ${_} ${e(N)}`);else S("AND",`json_extract(${j}) ${_} ${e(N)}`);return E.push(R),this},whereLike(j,_,R=!1){let D=e(E.length+1);return C("WHERE",`${R?String(j):`LOWER(${String(j)})`} LIKE ${R?D:`LOWER(${D})`}`),E.push(_),P=null,this},whereILike(j,_){let R=e(E.length+1);if(y.dialect==="postgres")C("WHERE",`${String(j)} ILIKE ${R}`);else C("WHERE",`LOWER(${String(j)}) LIKE LOWER(${R})`);return E.push(_),P=null,this},orWhereLike(j,_,R=!1){let D=e(E.length+1);return C("OR",`${R?String(j):`LOWER(${String(j)})`} LIKE ${R?D:`LOWER(${D})`}`),E.push(_),P=null,this},orWhereILike(j,_){let R=e(E.length+1);if(y.dialect==="postgres")C("OR",`${String(j)} ILIKE ${R}`);else C("OR",`LOWER(${String(j)}) LIKE LOWER(${R})`);return E.push(_),P=null,this},whereNotLike(j,_,R=!1){let D=e(E.length+1);return C("WHERE",`${R?String(j):`LOWER(${String(j)})`} NOT LIKE ${R?D:`LOWER(${D})`}`),E.push(_),P=null,this},whereNotILike(j,_){let R=e(E.length+1);if(y.dialect==="postgres")C("WHERE",`${String(j)} NOT ILIKE ${R}`);else C("WHERE",`LOWER(${String(j)}) NOT LIKE LOWER(${R})`);return E.push(_),P=null,this},orWhereNotLike(j,_,R=!1){let D=e(E.length+1);return C("OR",`${R?String(j):`LOWER(${String(j)})`} NOT LIKE ${R?D:`LOWER(${D})`}`),E.push(_),P=null,this},orWhereNotILike(j,_){let R=e(E.length+1);if(y.dialect==="postgres")C("OR",`${String(j)} NOT ILIKE ${R}`);else C("OR",`LOWER(${String(j)}) NOT LIKE LOWER(${R})`);return E.push(_),P=null,this},whereAny(j,_,R){if(j.length===0)return S("AND",`(${xX})`),this;let D=E.length+1,N=j.map((k,f)=>`${k} ${_} ${e(D+f)}`);for(let k=0;k<j.length;k++)E.push(R);return S("AND",`(${N.join(" OR ")})`),this},whereAll(j,_,R){if(j.length===0)return this;let D=E.length+1,N=j.map((k,f)=>`${k} ${_} ${e(D+f)}`);for(let k=0;k<j.length;k++)E.push(R);return S("AND",`(${N.join(" AND ")})`),this},whereNone(j,_,R){if(j.length===0)return this;let D=E.length+1,N=j.map((k,f)=>`${k} ${_} ${e(D+f)}`);for(let k=0;k<j.length;k++)E.push(R);return S("AND",`NOT (${N.join(" OR ")})`),this},whereNotBetween(j,_,R){o(String(j),"whereNotBetween(column)");let D=E.length+1;return E.push(_,R),S("AND",`${j} NOT BETWEEN ${e(D)} AND ${e(D+1)}`),this},whereDate(j,_,R){o(j,"whereDate(column)");let D=R instanceof Date?R.toISOString():typeof R==="string"?R:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof R}`)})(),N=E.length+1;return E.push(D),S("AND",`${j} ${_} ${e(N)}`),this},whereRaw(j){return S("AND",$9(j,"whereRaw(fragment)")),this},orWhereRaw(j){return S("OR",$9(j,"orWhereRaw(fragment)")),this},whereColumn(j,_,R){return o(j,"whereColumn(left)"),o(R,"whereColumn(right)"),S("AND",`${j} ${_} ${R}`),this},orWhereColumn(j,_,R){return o(j,"orWhereColumn(left)"),o(R,"orWhereColumn(right)"),S("OR",`${j} ${_} ${R}`),this},whereIn(j,_){if(o(String(j),"whereIn(column)"),Array.isArray(_)){let R=NZ(_.length,E.length+1),D=rZ(j,_,!1,R);E.push(..._),S("AND",D)}else S("AND",`${j} IN (${String(_.toSQL())})`);return this},orWhereIn(j,_){if(o(String(j),"orWhereIn(column)"),Array.isArray(_)){let R=NZ(_.length,E.length+1),D=rZ(j,_,!1,R);E.push(..._),S("OR",D)}else S("OR",`${j} IN (${String(_.toSQL())})`);return this},whereNotIn(j,_){if(o(String(j),"whereNotIn(column)"),Array.isArray(_)){let R=NZ(_.length,E.length+1),D=rZ(j,_,!0,R);E.push(..._),S("AND",D)}else S("AND",`${j} NOT IN (${String(_.toSQL())})`);return this},orWhereNotIn(j,_){if(o(String(j),"orWhereNotIn(column)"),Array.isArray(_)){let R=NZ(_.length,E.length+1),D=rZ(j,_,!0,R);E.push(..._),S("OR",D)}else S("OR",`${j} NOT IN (${String(_.toSQL())})`);return this},whereNested(j){let _=j.toSQL?String(j.toSQL()):String(j);return S("AND",`(${_})`),this},orWhereNested(j){let _=j.toSQL?String(j.toSQL()):String(j);return S("OR",`(${_})`),this},andWhere(j,_,R){return l(this,"AND","andWhere",j,_,R)},orWhere(j,_,R){return l(this,"OR","orWhere",j,_,R)},orderBy(j,_="asc"){let R=_==="asc"?"ASC":"DESC",D=U8(String(j));return F=VZ.ORDER_BY.test(F)?`${F}, ${D} ${R}`:`${F} ORDER BY ${D} ${R}`,P=null,this},orderByDesc(j){return F=VZ.ORDER_BY.test(F)?`${F}, ${j} DESC`:`${F} ORDER BY ${j} DESC`,P=null,this},inRandomOrder(){let j=y.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return F=VZ.ORDER_BY.test(F)?`${F}, ${j}`:`${F} ORDER BY ${j}`,P=null,this},reorder(j,_="asc"){return F=F.replace(/ORDER BY[\s\S]*$/i,""),F+=` ORDER BY ${j} ${_==="asc"?"ASC":"DESC"}`,P=null,this},latest(j){let _=j??y.timestamps.defaultOrderColumn;return F=VZ.ORDER_BY.test(F)?`${F}, ${_} DESC`:`${F} ORDER BY ${_} DESC`,P=null,this},oldest(j){let _=j??y.timestamps.defaultOrderColumn;return F=VZ.ORDER_BY.test(F)?`${F}, ${_} ASC`:`${F} ORDER BY ${_} ASC`,P=null,this},limit(j){if(!Number.isFinite(j)||j<0||!Number.isInteger(j))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${j}`);return F=VZ.LIMIT.test(F)?F.replace(VZ.LIMIT,` LIMIT ${j}`):`${F} LIMIT ${j}`,P=null,this},offset(j){if(!Number.isFinite(j)||j<0||!Number.isInteger(j))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${j}`);return F=VZ.OFFSET.test(F)?F.replace(VZ.OFFSET,` OFFSET ${j}`):`${F} OFFSET ${j}`,P=null,this},join(j,_,R,D){return o(j,"join(table)"),G8(_,"join(onLeft)"),G8(D,"join(onRight)"),kZ(R,"join(operator)"),r(`JOIN ${j} ON ${_} ${R} ${D}`),b.add(j),this},joinSub(j,_,R,D,N){return o(_,"joinSub(alias)"),G8(R,"joinSub(onLeft)"),G8(N,"joinSub(onRight)"),kZ(D,"joinSub(operator)"),r(`JOIN (${String(j.toSQL())}) AS ${_} ON ${R} ${D} ${N}`),b.add(_),this},innerJoin(j,_,R,D){return o(j,"innerJoin(table)"),G8(_,"innerJoin(onLeft)"),G8(D,"innerJoin(onRight)"),kZ(R,"innerJoin(operator)"),r(`INNER JOIN ${j} ON ${_} ${R} ${D}`),b.add(j),this},leftJoin(j,_,R,D){return o(j,"leftJoin(table)"),G8(_,"leftJoin(onLeft)"),G8(D,"leftJoin(onRight)"),kZ(R,"leftJoin(operator)"),r(`LEFT JOIN ${j} ON ${_} ${R} ${D}`),b.add(j),this},leftJoinSub(j,_,R,D,N){return o(_,"leftJoinSub(alias)"),G8(R,"leftJoinSub(onLeft)"),G8(N,"leftJoinSub(onRight)"),kZ(D,"leftJoinSub(operator)"),r(`LEFT JOIN (${String(j.toSQL())}) AS ${_} ON ${R} ${D} ${N}`),b.add(_),this},rightJoin(j,_,R,D){return o(j,"rightJoin(table)"),G8(_,"rightJoin(onLeft)"),G8(D,"rightJoin(onRight)"),kZ(R,"rightJoin(operator)"),r(`RIGHT JOIN ${j} ON ${_} ${R} ${D}`),b.add(j),this},crossJoin(j){return o(j,"crossJoin(table)"),r(`CROSS JOIN ${j}`),b.add(j),this},crossJoinSub(j,_){return o(_,"crossJoinSub(alias)"),r(`CROSS JOIN (${String(j.toSQL())}) AS ${_}`),b.add(_),this},selectAllRelations(){if(!X)return this;let j=String(K),_=Object.keys(X[j]?.columns??{}),R=[];if(_.length>0)R.push(V`${V(j)}.*`);for(let D of b){let N=Object.keys(X[D]?.columns??{});for(let k of N){let f=y.aliasing.relationColumnAliasFormat==="camelCase"?`${D}_${k}`.replace(/_([a-z])/g,(g,s)=>s.toUpperCase()):y.aliasing.relationColumnAliasFormat==="table.dot.column"?`${D}.${k}`:`${D}_${k}`;R.push(V`${V(`${D}.${k}`)} AS ${V(f)}`)}}if(R.length>0){let D=_.length>0?`${j}.*`:"",N=[];for(let g of b){let s=Object.keys(X[g]?.columns??{});for(let h of s){let p=y.aliasing.relationColumnAliasFormat==="camelCase"?`${g}_${h}`.replace(/_([a-z])/g,(a,UZ)=>UZ.toUpperCase()):y.aliasing.relationColumnAliasFormat==="table.dot.column"?`${g}.${h}`:`${g}_${h}`;N.push(`${g}.${h} AS ${p}`)}}let k=[D,...N].filter(Boolean).join(", "),f=F.indexOf(" FROM ");if(f!==-1)F=`SELECT ${k}${F.substring(f)}`;else F=`SELECT ${k} FROM ${j}`;P=null}return this},groupBy(...j){if(j.length)F=VZ.GROUP_BY.test(F)?`${F}, ${j.map((_)=>U8(String(_))).join(", ")}`:`${F} GROUP BY ${j.map((_)=>U8(String(_))).join(", ")}`,P=null;return this},groupByRaw(j){let _=$9(j,"groupByRaw(fragment)");return F=VZ.GROUP_BY.test(F)?`${F}, ${_}`:`${F} GROUP BY ${_}`,P=null,this},having(j){let _=d?"AND":"HAVING";if(Array.isArray(j)){let R=E.length+1;F=`${F} ${_} ${j[0]} ${j[1]} ${e(R)}`,E.push(j[2]),d=!0,P=null}else if(j&&typeof j==="object"&&!("raw"in j)){let R=Object.keys(j),D=R.length;if(D){let N=E.length,k=Array.from({length:D});for(let f=0;f<D;f++){let g=R[f];k[f]=`${g} = ${e(N+f+1)}`,E.push(j[g])}F=`${F} ${_} ${k.join(" AND ")}`,d=!0,P=null}}else if(j&&typeof j.raw<"u")F+=` ${_} ${j.raw}`,d=!0,P=null;return this},havingRaw(j){let _=$9(j,"havingRaw(fragment)");return F+=` ${d?"AND":"HAVING"} ${_}`,d=!0,P=null,this},orderByRaw(j){let _=$9(j,"orderByRaw(fragment)");return F=VZ.ORDER_BY.test(F)?`${F}, ${_}`:`${F} ORDER BY ${_}`,P=null,this},$call(j){return j(this),this},union(j){return u("UNION",j),this},unionAll(j){return u("UNION ALL",j),this},intersect(j){return u("INTERSECT",j),this},intersectAll(j){return u("INTERSECT ALL",j),this},except(j){return u("EXCEPT",j),this},exceptAll(j){return u("EXCEPT ALL",j),this},forPage(j,_){let R=Math.max(1,Math.floor(j)),D=Math.max(1,Math.floor(_));return F+=` LIMIT ${D} OFFSET ${(R-1)*D}`,P=null,this},toSQL(){let j=l9(m());return{sql:j,toString:()=>j,execute:()=>M().execute(),values:()=>M().values(),raw:()=>M().raw()}},async value(j){let _=V`${M()} LIMIT 1`,R=await L(_,"select",{signal:t,timeoutMs:c}),[D]=R;return D?.[j]},async pluck(j,_){let R=await L(M(),"select",{signal:t,timeoutMs:c});if(_){let D={};for(let N of R){let k=String(N?.[_]);if(Object.prototype.hasOwnProperty.call(D,k))throw Error(`[query-builder] pluck(${j}, ${_}): duplicate key '${k}' \u2014 multiple rows share this value, so the resulting map would silently drop data. Use a unique key column or pluck without a key to get an array.`);D[k]=N?.[j]}return D}return R.map((D)=>D?.[j])},async exists(){let j=V`SELECT EXISTS (${M()}) as e`,_=await L(j,"select",{signal:t,timeoutMs:c}),[R]=_;return Boolean(R?.e)},async doesntExist(){return!await this.exists()},async paginate(j,_=1,R={}){if(!Number.isFinite(j)||j<=0||!Number.isInteger(j))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${j}`);if(!Number.isFinite(_)||_<1||!Number.isInteger(_))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${_}`);if(R.tx){let a=l9(m()),UZ=[...E],PZ=await R.tx.unsafe(`SELECT COUNT(*) as c FROM (${a}) as sub`,UZ),ZZ=Number(PZ?.[0]?.c??0),TZ=Math.max(1,Math.ceil(ZZ/j)),uZ=Math.max(1,Math.min(_,TZ)),lZ=(uZ-1)*j;return{data:await R.tx.unsafe(`${a} LIMIT ${j} OFFSET ${lZ}`,UZ),meta:{perPage:j,page:uZ,total:ZZ,lastPage:TZ}}}let D=V`SELECT COUNT(*) as c FROM (${M()}) as sub`,N=await L(D,"select",{signal:t,timeoutMs:c}),[k]=N,f=Number(k?.c??0),g=Math.max(1,Math.ceil(f/j)),s=Math.max(1,Math.min(_,g)),h=(s-1)*j;return{data:await L(V`${M()} LIMIT ${j} OFFSET ${h}`,"select",{signal:t,timeoutMs:c}),meta:{perPage:j,page:s,total:f,lastPage:g}}},async simplePaginate(j,_=1){let R=Math.max(1,_),D=(R-1)*j,N=await L(V`${M()} LIMIT ${j+1} OFFSET ${D}`,"select",{signal:t,timeoutMs:c}),k=N.length>j;return{data:k?N.slice(0,j):N,meta:{perPage:j,page:R,hasMore:k}}},async cursorPaginate(j,_,R="id",D="asc"){if(!Number.isInteger(j)||j<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${j}`);let N=(Array.isArray(R)?R:[R]).map(String);for(let cZ of N)o(cZ,"cursorPaginate(column)");let k=D==="asc"?">":"<",f=D==="asc"?"ASC":"DESC",g=[...E],s="";if(_!==void 0&&_!==null)if(Array.isArray(R)){let cZ=_.map((zZ)=>{return g.push(zZ),e(g.length)});s=`(${N.join(", ")}) ${k} (${cZ.join(", ")})`}else g.push(_),s=`${N[0]} ${k} ${e(g.length)}`;let h=l9(s?m({conn:"AND",sql:s}):m()),p=N.map((cZ)=>`${cZ} ${f}`).join(", ");if(R6(h))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${p} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let a=g.length>0?$.unsafe(`${h} ORDER BY ${p} LIMIT ${j+1}`,g):$.unsafe(`${h} ORDER BY ${p} LIMIT ${j+1}`),UZ=await L(a,"select",{signal:t,timeoutMs:c}),PZ=UZ.length>j,ZZ=UZ.slice(0,j),TZ=ZZ[ZZ.length-1],uZ=PZ&&TZ?Array.isArray(R)?R.map((cZ)=>TZ[cZ]):TZ[R]:null,lZ=ZZ.length?Array.isArray(R)?R.map((cZ)=>ZZ[0]?.[cZ]):ZZ[0]?.[R]:null;return{data:ZZ,meta:{perPage:j,nextCursor:uZ??null,prevCursor:lZ}}},async chunk(j,_){let R=1;while(!0){let{data:D,meta:N}=await this.paginate(j,R);if(D.length===0)break;if(await _(D),R>=N.lastPage)break;R+=1}},async chunkById(j,_="id",R){let D;while(!0){let{data:N,meta:k}=await this.cursorPaginate(j,D,_,"asc");if(N.length===0)break;if(R)await R(N);if(D=k.nextCursor,!D)break}},async eachById(j,_="id",R){await this.chunkById(j,_,async(D)=>{for(let N of D)await R?.(N)})},withTimeout(j){return c=Math.max(1,Math.floor(j)),this},abort(j){return t=j,this},withTrashed(){return GZ=!0,FZ=!1,this},onlyTrashed(){GZ=!0,FZ=!0;let j=y.softDeletes?.column||"deleted_at",_=(N,k)=>{let f=N.toUpperCase(),g=0;for(let s=0;s<N.length;s++){let h=N[s];if(h==="(")g++;else if(h===")")g--;else if(g===0&&f.substring(s,s+5)==="WHERE"&&(s===0||/\s/.test(N[s-1]??""))&&/\s/.test(N[s+5]??""))return`${N.substring(0,s)}WHERE ${k} AND ${N.substring(s+6)}`}return`${N} WHERE ${k}`},R=`${K}.${j} IS NOT NULL`;F=_(F,R);let D=String(M());return P=V([_(D,R)]),this},scope(j,_){let R=String(K),N=Y?.scopes?.[R]?.[j];if(N)return N(this,_);return this},when(j,_,R){if(j)return _(this);if(R)return R(this);return this},tap(j){return j(this),this},dump(){return console.log(String(M())),this},dd(){throw console.log(String(M())),Error("Dump and Die")},cache(j=60000){return X$=j,mZ=!0,this},async explain(){let j=V`EXPLAIN ${M()}`;return await L(j,"select",{signal:t,timeoutMs:c})},simple(){return M().simple()},toText(){return m()},async get(){let j=U(),_=j&&(j.onQueryStart||j.onQueryEnd||j.onQueryError||j.startSpan||i9(j));if(!y.softDeletes?.enabled&&!mZ&&!c&&!t&&!_){let f=$._prepareStatement;if(f){let g=f(m());return P9(E.length>0?g.all(...E):g.all())}}let R=m();if(P=E.length>0?$.unsafe(R,E):$.unsafe(R),!y.softDeletes?.enabled&&!mZ&&!c&&!t&&!_){let f=M()._stmt,g=M()._params;if(f)return P9(g&&g.length>0?f.all(...g):f.all());return P9(await M().execute())}if(!y.softDeletes?.enabled&&!mZ&&!c&&!t)return P9(await L(M(),"select"));let D=M();if(y.softDeletes?.enabled&&y.softDeletes.defaultFilter&&!GZ){let f=y.softDeletes.column,g=String(K);if((X?Boolean(X[g]?.columns?.[f]):!0)&&!VZ.DELETED_AT.test(m()))C("WHERE",`${String(f)} IS ${FZ?"NOT ":""}NULL`),D=M()}let N=mZ?`${String(D)}\x00${JSON.stringify(E)}`:"";if(mZ){let f=X7.get(N);if(f)return f}let k=await L(D,"select",{signal:t,timeoutMs:c});if(mZ)X7.set(N,k,X$);return P9(k)},async executeTakeFirst(){let j=await L(M(),"select",{signal:t,timeoutMs:c});return D8(Array.isArray(j)?j[0]:j)},async executeTakeFirstOrThrow(){let j=await this.executeTakeFirst();if(!j)throw Error("Record not found");return j},async first(){let j=U(),_=j&&(j.onQueryStart||j.onQueryEnd||j.onQueryError||j.startSpan||i9(j));if(!y.softDeletes?.enabled&&!mZ&&!c&&!t&&!_){let N=$._prepareStatement;if(N){let k=m(),f=k.includes(" LIMIT ")?k:`${k} LIMIT 1`,g=N(f),s=E.length>0?g.all(...E):g.all();return D8(s[0])}}let R=await L(V`${M()} LIMIT 1`,"select",{signal:t,timeoutMs:c}),[D]=R;return D8(D)},async firstOrFail(){let j=await this.first();if(!j)throw Error("Record not found");return j},async find(j){let _=Y?.primaryKeys[String(K)]??"id",R=await L(V`${M()} WHERE ${V(_)} = ${j} LIMIT 1`,"select",{signal:t,timeoutMs:c}),[D]=R;return D},async findOrFail(j){let _=await this.find(j);if(!_)throw Error("Record not found");return _},async findMany(j){let _=Y?.primaryKeys[String(K)]??"id";return await L(V`${M()} WHERE ${V(String(_))} IN ${V(j)}`,"select",{signal:t,timeoutMs:c})},async*lazy(){let j,_=Y?.primaryKeys[String(K)]??"id";while(!0){let D=await(j==null?V`${M()} ORDER BY ${V(String(_))} ASC LIMIT 100`:V`${M()} WHERE ${V(String(_))} > ${j} ORDER BY ${V(String(_))} ASC LIMIT 100`).execute();if(D.length===0)break;for(let N of D)yield N;if(j=D[D.length-1]?.[_],j==null)break}},async*lazyById(){let j=Y?.primaryKeys[String(K)]??"id",_;while(!0){let D=await(_==null?V`${M()} ORDER BY ${V(String(j))} ASC LIMIT 100`:V`${M()} WHERE ${V(String(j))} > ${_} ORDER BY ${V(String(j))} ASC LIMIT 100`).execute();if(D.length===0)break;for(let N of D)yield N;if(_=D[D.length-1]?.[j],_==null)break}},pipe(j){return j(this)},async count(){let j=m(),_=j.indexOf(" FROM "),R=/ GROUP BY /i.test(j),D;if(R)D=`SELECT COUNT(*) as c FROM (${j}) AS _bqb_count_sub`;else if(_!==-1)D=`SELECT COUNT(*) as c${j.substring(_)}`;else D=`SELECT COUNT(*) as c FROM ${K}`;let N=U(),k=N&&(N.onQueryStart||N.onQueryEnd||N.onQueryError||N.startSpan||i9(N));if(!y.softDeletes?.enabled&&!mZ&&!c&&!t&&!k){let h=$._prepareStatement;if(h){let p=h(D),a=E.length>0?p.all(...E):p.all();return Number(a[0]?.c??0)}}let f=E.length>0?$.unsafe(D,E):$.unsafe(D),g=await L(f,"select",{signal:t,timeoutMs:c}),[s]=g;return Number(s?.c??0)},async avg(j){let _=m(),R=_.indexOf(" FROM "),D=R!==-1?`SELECT AVG(${j}) as a${_.substring(R)}`:`SELECT AVG(${j}) as a FROM ${K}`,N=U(),k=N&&(N.onQueryStart||N.onQueryEnd||N.onQueryError||N.startSpan||i9(N));if(!y.softDeletes?.enabled&&!mZ&&!c&&!t&&!k){let h=$._prepareStatement;if(h){let p=h(D),a=E.length>0?p.all(...E):p.all();return Number(a[0]?.a??0)}}let f=E.length>0?$.unsafe(D,E):$.unsafe(D),g=await L(f,"select",{signal:t,timeoutMs:c}),[s]=g;return Number(s?.a??0)},async sum(j){let _=m(),R=_.indexOf(" FROM "),D=R!==-1?`SELECT SUM(${j}) as s${_.substring(R)}`:`SELECT SUM(${j}) as s FROM ${K}`,N=E.length>0?$.unsafe(D,E):$.unsafe(D),k=await L(N,"select",{signal:t,timeoutMs:c}),[f]=k;return Number(f?.s??0)},async max(j){let _=m(),R=_.indexOf(" FROM "),D=R!==-1?`SELECT MAX(${j}) as m${_.substring(R)}`:`SELECT MAX(${j}) as m FROM ${K}`,N=E.length>0?$.unsafe(D,E):$.unsafe(D),k=await L(N,"select",{signal:t,timeoutMs:c}),[f]=k;return f?.m},async min(j){let _=m(),R=_.indexOf(" FROM "),D=R!==-1?`SELECT MIN(${j}) as m${_.substring(R)}`:`SELECT MIN(${j}) as m FROM ${K}`,N=E.length>0?$.unsafe(D,E):$.unsafe(D),k=await L(N,"select",{signal:t,timeoutMs:c}),[f]=k;return f?.m},lockForUpdate(){return F+=" FOR UPDATE",P=null,this},sharedLock(){let j=y.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return F+=` ${j}`,P=null,this},withCTE(j,_){return o(j,"withCTE(name)"),F=`WITH ${j} AS (${String(_.toSQL())}) ${F}`,P=null,this},withRecursive(j,_){return o(j,"withRecursive(name)"),F=`WITH RECURSIVE ${j} AS (${String(_.toSQL())}) ${F}`,P=null,this},execute(){return L(M(),"select",{signal:t,timeoutMs:c})},values(){return M().values()},toParams(){return[...E]},__rawState(){return{sql:l9(m()),params:[...E]}},__hasPredicate(){return I.length>0||x},raw(){return M().raw()},get rows(){return},get row(){return},cancel(){try{M().cancel()}catch{}}},{get(j,_,R){let D=Reflect.get(j,_,R);if(D!==void 0)return D;if(typeof _==="string"&&(_.startsWith("where")||_.startsWith("orWhere")||_.startsWith("andWhere"))){let N=_.startsWith("orWhere"),k=_.startsWith("andWhere"),f=`${String(K)}|${_}`,g=H.get(f);if(g===void 0){let h=_.replace(/^(?:or|and)?where/i,"");if(!h)H.set(f,""),g="";else{let p=h.charAt(0).toLowerCase()+h.slice(1),a=h.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),UZ=X?Object.keys(X[String(K)]?.columns??{}):[];g=[a,p,p.toLowerCase()].find((PZ)=>UZ.includes(PZ))??a,H.set(f,g)}}if(g==="")return()=>R;let s=g;return(h)=>{if(Array.isArray(h)){let p=NZ(h.length,E.length+1);C(N?"OR":k?"AND":"WHERE",`${s} IN (${p})`),E.push(...h)}else{let p=e(E.length+1);C(N?"OR":k?"AND":"WHERE",`${s} = ${p}`),E.push(h)}return R}}return Reflect.get(j,_,R)}})}return{configure(K){return DX(K),this},id(K){if(!VZ.IDENTIFIER.test(K))throw Error(`[query-builder] Invalid identifier: '${K}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(String(K))},ids(...K){for(let B of K)if(!VZ.IDENTIFIER.test(B))throw Error(`[query-builder] Invalid identifier: '${B}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(K)},select(K,...B){return w(K,B)},selectFrom(K){return w(K)},selectFromSub(K,B){function V(M){return()=>{throw Error(`[query-builder] selectFromSub(...).${M}() is not supported. Apply ${M}() to the underlying subquery BEFORE passing it to selectFromSub, or use the regular selectFrom(...) builder. This previously silently returned without `+"affecting the SQL, producing wrong results \u2014 see stacksjs/stacks#1862 #11.")}}o(String(B),"selectFromSub(alias)");let F=typeof K.__rawState==="function"?K.__rawState():null,I=K.toSQL(),E=F?.sql??(typeof I==="string"?I:I?.sql??String(I)),n=F?.params??(Array.isArray(I?.values)?I.values:[]),x=`SELECT * FROM (${E}) AS ${String(B)}`,d=(M,S,C,v)=>{let i=[...M],m=(l,u,r)=>{o(l,"selectFromSub where(column)");let b=kZ(u,"selectFromSub where(operator)");if(b==="in"||b==="not in"){let t=Array.isArray(r)?r:[r],GZ=NZ(t.length,i.length+1);return i.push(...t),`${l} ${b.toUpperCase()} (${GZ})`}let c=e(i.length+1);return i.push(r),`${l} ${b} ${c}`},q;if(typeof S==="string"&&C!==void 0)q=m(S,C,v);else if(Array.isArray(S)&&S.length===3)q=m(S[0],S[1],S[2]);else if(S&&typeof S==="object"){let l=Object.entries(S).map(([u,r])=>m(u,"=",r));q=l.length>1?`(${l.join(" AND ")})`:l[0]}else return{clause:null,params:M};return{clause:q,params:i}};function P(M,S,C,v=""){let i=Z9(S),m=i?`${M} WHERE ${i}${v}`:`${M}${v}`,q=()=>C.length>0?$.unsafe(m,C):$.unsafe(m),l=(b,c,t,GZ)=>{let FZ=d(C,c,t,GZ);return FZ.clause===null?P(M,S,C,v):P(M,[...S,{conn:b,sql:FZ.clause}],FZ.params,v)},u=(b,c)=>{let t=[],GZ=[...C],FZ=(Y8)=>(X$,EZ,V8)=>{let D8=d(GZ,X$,EZ,V8);if(D8.clause!==null)t.push({conn:Y8,sql:D8.clause}),GZ=D8.params;return mZ},mZ={where:FZ("AND"),andWhere:FZ("AND"),orWhere:FZ("OR")};c(mZ);let E8=Z9(t);if(!E8)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return P(M,[...S,{conn:b,sql:`(${E8})`}],GZ,v)},r={distinct(){return P(M.replace(/^SELECT\s+/i,"SELECT DISTINCT "),S,C,v)},distinctOn(...b){let c=b.map(String).join(", ");return P(M.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${c}) `),S,C,v)},selectRaw(b){let c=$9(b,"selectFromSub.selectRaw(fragment)"),t=M.indexOf(" FROM "),GZ=t!==-1?`${M.slice(0,t)}, ${c}${M.slice(t)}`:`${M}, ${c}`;return P(GZ,S,C,v)},$call(b){return b(this)??this},where(b,c,t){return l("AND",b,c,t)},andWhere(b,c,t){return l("AND",b,c,t)},orWhere(b,c,t){return l("OR",b,c,t)},whereGroup(b){return u("AND",b)},orWhereGroup(b){return u("OR",b)},orderBy(b,c="asc"){o(String(b),"selectFromSub.orderBy(column)");let t=c==="asc"?"ASC":"DESC",GZ=VZ.ORDER_BY.test(v)?`${v}, ${b} ${t}`:`${v} ORDER BY ${b} ${t}`;return P(M,S,C,GZ)},limit(b){if(!Number.isInteger(b)||b<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${b}`);let c=VZ.LIMIT.test(v)?v.replace(VZ.LIMIT,` LIMIT ${b}`):`${v} LIMIT ${b}`;return P(M,S,C,c)},offset(b){if(!Number.isInteger(b)||b<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${b}`);let c=VZ.OFFSET.test(v)?v.replace(VZ.OFFSET,` OFFSET ${b}`):`${v} OFFSET ${b}`;return P(M,S,C,c)},toSQL(){return T(q(),m)},async execute(){return L(q(),"select")},async executeTakeFirst(){let b=await L(q(),"select");return Array.isArray(b)?b[0]:b},async executeTakeFirstOrThrow(){let b=await L(q(),"select"),c=Array.isArray(b)?b[0]:b;if(!c)throw Error("Record not found");return c},async get(){return L(q(),"select")},async first(){let b=await L(q(),"select");return Array.isArray(b)?b[0]:b},async firstOrFail(){let b=await L(q(),"select"),c=Array.isArray(b)?b[0]:b;if(!c)throw Error("No rows found");return c},async count(){let b=C.length>0?$.unsafe(`SELECT COUNT(*) as c FROM (${m}) as sub`,C):$.unsafe(`SELECT COUNT(*) as c FROM (${m}) as sub`),c=await L(b,"select");return Number(c?.[0]?.c??0)},async exists(){let b=C.length>0?$.unsafe(`SELECT EXISTS(${m}) as e`,C):$.unsafe(`SELECT EXISTS(${m}) as e`),c=await L(b,"select");return Boolean(c?.[0]?.e)},async doesntExist(){return!await r.exists()},values(){return q().values()},raw(){return q().raw()},cancel(){try{q().cancel()}catch{}},whereRaw:V("whereRaw"),whereColumn:V("whereColumn"),orWhereColumn:V("orWhereColumn"),whereIn:V("whereIn"),orWhereIn:V("orWhereIn"),whereNotIn:V("whereNotIn"),orWhereNotIn:V("orWhereNotIn"),whereLike:V("whereLike"),whereILike:V("whereILike"),orWhereLike:V("orWhereLike"),orWhereILike:V("orWhereILike"),whereNotLike:V("whereNotLike"),whereNotILike:V("whereNotILike"),orWhereNotLike:V("orWhereNotLike"),orWhereNotILike:V("orWhereNotILike"),whereAny:V("whereAny"),whereAll:V("whereAll"),whereNone:V("whereNone"),whereNested:V("whereNested"),orWhereNested:V("orWhereNested"),whereDate:V("whereDate"),whereBetween:V("whereBetween"),whereNotBetween:V("whereNotBetween"),whereJsonContains:V("whereJsonContains"),whereJsonPath:V("whereJsonPath"),whereNull:V("whereNull"),orWhereNull:V("orWhereNull"),whereNotNull:V("whereNotNull"),orWhereNotNull:V("orWhereNotNull"),whereExists:V("whereExists"),orWhereExists:V("orWhereExists"),orWhereBetween:V("orWhereBetween"),orWhereRaw:V("orWhereRaw"),whereJsonDoesntContain:V("whereJsonDoesntContain"),whereJsonContainsKey:V("whereJsonContainsKey"),whereJsonDoesntContainKey:V("whereJsonDoesntContainKey"),whereJsonLength:V("whereJsonLength"),join:V("join"),joinSub:V("joinSub"),innerJoin:V("innerJoin"),leftJoin:V("leftJoin"),leftJoinSub:V("leftJoinSub"),rightJoin:V("rightJoin"),crossJoin:V("crossJoin"),crossJoinSub:V("crossJoinSub"),groupBy:V("groupBy"),groupByRaw:V("groupByRaw"),having:V("having"),havingRaw:V("havingRaw"),addSelect:V("addSelect"),select:V("select"),selectAll:V("selectAll"),orderByDesc:V("orderByDesc"),inRandomOrder:V("inRandomOrder"),reorder:V("reorder"),orderByRaw:V("orderByRaw"),union:V("union"),unionAll:V("unionAll"),forPage:V("forPage"),selectAllRelations:V("selectAllRelations"),with:V("with"),value:V("value"),pluck:V("pluck"),cursorPaginate:V("cursorPaginate"),paginate:V("paginate"),simplePaginate:V("simplePaginate"),chunk:V("chunk"),chunkById:V("chunkById"),eachById:V("eachById"),avg:V("avg"),sum:V("sum"),max:V("max"),min:V("min"),find:V("find"),findOrFail:V("findOrFail"),findMany:V("findMany"),latest:V("latest"),oldest:V("oldest"),lazy:V("lazy"),lazyById:V("lazyById"),pipe:(b)=>b(r),when:V("when"),tap:()=>r,dump:()=>r,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>q().simple(),toText:()=>m,toParams:()=>[...C],withTimeout:()=>r,abort:()=>r,lockForUpdate:()=>r,sharedLock:()=>r,withCTE:()=>r,withRecursive:()=>r,cache:()=>r,clone:()=>r,withTrashed:()=>r,onlyTrashed:()=>r,scope:()=>r,get rows(){return[]},get row(){return}};return r}return P(x,[],n)},insertInto(K){let B,V="",F=[],I=[],E=!1,n=()=>d?[]:{changes:0,lastInsertRowid:0},x=()=>{let C=async()=>{return},v=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>x(),andWhere:()=>x(),orWhere:()=>x(),orderBy:()=>x(),limit:()=>x(),offset:()=>x(),toSQL:()=>T(null,""),execute:async()=>[],get:async()=>[],first:C,executeTakeFirst:C,firstOrFail:v,executeTakeFirstOrThrow:v}},d=y.dialect==="postgres",P=(C)=>{let i=C.flat(2).map(String).filter(Boolean),m=i.length>0&&!i.includes("*")?i.map((u)=>M(u)).join(", "):"*",q=async()=>{let u=await L($.unsafe(V,F),"insert"),r=Number(u?.lastInsertRowid??0),b=Math.max(1,Number(u?.affectedRows??1)),c=I.filter((FZ)=>FZ!==void 0&&FZ!==null),t=r>0?$.unsafe(`SELECT ${m} FROM ${M(String(K))} WHERE ${M("id")} >= ? AND ${M("id")} < ? ORDER BY ${M("id")} ASC`,[r,r+b]):c.length>0?$.unsafe(`SELECT ${m} FROM ${M(String(K))} WHERE ${M("id")} IN (${c.map(()=>"?").join(", ")}) ORDER BY ${M("id")} ASC`,c):null;if(!t)return[];let GZ=await t.execute();return Array.isArray(GZ)?GZ:[]},l=async()=>(await q())[0];return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>T($.unsafe(V,F),V),execute:q,get:q,first:l,executeTakeFirst:l,async firstOrFail(){let u=await l();if(!u)throw Error("Insert with RETURNING returned no rows");return u},async executeTakeFirstOrThrow(){let u=await l();if(!u)throw Error("Insert with RETURNING returned no rows");return u}}},M=d?(C)=>`"${String(C).replace(/"/g,'""')}"`:YZ(y.dialect)?(C)=>`\`${String(C).replace(/`/g,"``")}\``:(C)=>`"${String(C).replace(/"/g,'""')}"`,S=d?(C)=>`$${C+1}`:(C)=>"?";return{values(C){let v=J(String(K),Array.isArray(C)?C:[C]),i=v.length;if(I=v.map((b)=>b?.id),i===0)return E=!0,B=null,V="",F.length=0,this;E=!1;let m=v[0],q=Object.keys(m),l=q.length,u=i*l;F.length=u;let r=d?q.map((b)=>M(b)).join(","):q.join(",");if(i===1)if(!d){let b=M(q[0]),c="?";F[0]=m[q[0]];for(let t=1;t<l;t++)b+=`,${M(q[t])}`,c+=",?",F[t]=m[q[t]];V=`INSERT INTO ${M(K)}(${b})VALUES(${c})`}else{V=`INSERT INTO ${M(K)}(${r})VALUES(`;for(let b=0;b<l;b++){if(b>0)V+=",";V+=S(b),F[b]=m[q[b]]}V+=")"}else{let b=q.map((t)=>M(t)).join(",");V=`INSERT INTO ${M(K)}(${b})VALUES`;let c=0;for(let t=0;t<i;t++){let GZ=v[t];if(t===0)V+="(";else V+="),(";for(let FZ=0;FZ<l;FZ++){if(FZ>0)V+=",";V+=S(c),F[c++]=GZ[q[FZ]]}}V+=")"}if(!$._prepareStatement)B=$.unsafe(V,F);return this},returning(...C){if(E)return x();if(YZ(y.dialect))return P(C);let v=`${V} RETURNING ${C.join(", ")}`,i=$.unsafe(v,F),m=async()=>{let q=await L(i,"insert");return Array.isArray(q)?q[0]:q};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>T(i,v),execute:()=>L(i,"insert"),get:()=>L(i,"insert"),first:m,executeTakeFirst:m,async firstOrFail(){let q=await m();if(!q)throw Error("Insert with RETURNING returned no rows");return q},async executeTakeFirstOrThrow(){let q=await m();if(!q)throw Error("Insert with RETURNING returned no rows");return q}}},toSQL(){if(E)return T(null,"");if(!B)B=$.unsafe(V,F);return T(B,V)},execute(){if(E)return Promise.resolve(n());let C=U();if(!(C&&(C.onQueryStart||C.onQueryEnd||C.onQueryError||C.startSpan||C.beforeCreate||C.afterCreate||i9(C)))){let i=$._prepareStatement;if(i){let m=i(V);return F.length>0?m.run(...F):m.run()}}if(!B)B=$.unsafe(V,F);return L(B,"insert")},async executeTakeFirst(){if(E)return n();if(!B)B=$.unsafe(V,F);return await L(B,"insert")},async executeTakeFirstOrThrow(){if(E)throw Error("Insert failed");if(!B)B=$.unsafe(V,F);let C=await L(B,"insert");if(!C)throw Error("Insert failed");return C},returningAll(){if(E)return x();let C=`${V} RETURNING *`,v=$.unsafe(C,F),i=async()=>{let m=await L(v,"insert");return Array.isArray(m)?m[0]:m};return{toSQL:()=>T(v,C),execute:()=>L(v,"insert"),get:()=>L(v,"insert"),first:i,executeTakeFirst:i,async firstOrFail(){let m=await i();if(!m)throw Error("Insert with RETURNING returned no rows");return m},async executeTakeFirstOrThrow(){let m=await i();if(!m)throw Error("Insert with RETURNING returned no rows");return m}}}}},updateTable(K){let B,V=[],F=(x)=>{let d=String(x);if(YZ(y.dialect))return`\`${d.replace(/`/g,"``")}\``;return`"${d.replace(/"/g,'""')}"`},I=`UPDATE ${F(String(K))}`,E=!1,n=(x)=>{I=`${I} ${E?"AND":"WHERE"} ${x}`,E=!0};return{set(x){let d=J(String(K),[x])[0],P=Object.keys(d),M=P.length,S=Array.from({length:M});for(let C=0;C<M;C++){let v=P[C],i=d[v];if(R8(i))S[C]=`${F(v)} = ${i.raw}`;else if(u9(i)){let m=n9(i,V.length+1);S[C]=`${F(v)} = ${m.text}`,V.push(...m.parameters)}else S[C]=`${F(v)} = ${e(V.length+1)}`,V.push(i)}return I=`${I} SET ${S.join(", ")}`,B=$.unsafe(I,V),this},where(x,d,P){if(d!==void 0&&(typeof x==="string"||R8(x)||u9(x))){let M=kZ(d,"updateTable.where"),S;if(typeof x==="string")S=F(x);else if(R8(x))S=x.raw;else{let v=n9(x,V.length+1);S=v.text,V.push(...v.parameters)}if(M.toLowerCase()==="in"||M.toLowerCase()==="not in"){let v=Array.isArray(P)?P:[P],i=NZ(v.length,V.length+1);return n(`${S} ${M.toUpperCase()} (${i})`),V.push(...v),B=$.unsafe(I,V),this}let C=V.length+1;return n(`${S} ${M} ${e(C)}`),V.push(P),B=$.unsafe(I,V),this}if(Array.isArray(x)){let[M,S,C]=x,v=kZ(S,"updateTable.where");if(v.toLowerCase()==="in"||v.toLowerCase()==="not in"){let m=Array.isArray(C)?C:[C],q=NZ(m.length,V.length+1);return n(`${F(String(M))} ${v.toUpperCase()} (${q})`),V.push(...m),B=$.unsafe(I,V),this}let i=V.length+1;return n(`${F(String(M))} ${v} ${e(i)}`),V.push(C),B=$.unsafe(I,V),this}if(R8(x))return n(x.raw),B=$.unsafe(I,V),this;if(u9(x)){let M=n9(x,V.length+1);return n(M.text),V.push(...M.parameters),B=$.unsafe(I,V),this}if(x&&typeof x==="object"){let M=Object.keys(x);if(M.length===0)throw TypeError("[query-builder] updateTable.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if updating every row is intended.");let S=M.map((C)=>W0(F(C),x[C],V));return n(S.join(" AND ")),B=$.unsafe(I,V),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${x===null?"null":typeof x}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(x){return n(`${F(String(x))} IS NULL`),B=$.unsafe(I,V),this},whereNotNull(x){return n(`${F(String(x))} IS NOT NULL`),B=$.unsafe(I,V),this},returning(...x){let d=this,P=()=>`${I} RETURNING ${x.join(", ")}`,M=()=>V.length>0?$.unsafe(P(),V):$.unsafe(P()),S=async()=>{let q=/\sWHERE\s/i.test(I),l=q?I.slice(I.search(/\sWHERE\s/i)+1):"",u=V.slice(V.length-(l.match(/\?|\$\d+/g)?.length??0)),r=F("id"),b=await(u.length>0?$.unsafe(`SELECT ${r} FROM ${F(String(K))}${q?` ${l}`:""}`,u):$.unsafe(`SELECT ${r} FROM ${F(String(K))}${q?` ${l}`:""}`)).execute().catch(()=>[]),c=(Array.isArray(b)?b:[]).map((FZ)=>FZ?.id).filter((FZ)=>FZ!==void 0&&FZ!==null);if(await L(V.length>0?$.unsafe(I,V):$.unsafe(I),"update"),c.length===0)return[];let t=`SELECT ${x.join(", ")} FROM ${F(String(K))} WHERE ${r} IN (${c.map(()=>"?").join(", ")})`,GZ=await $.unsafe(t,c).execute();return Array.isArray(GZ)?GZ:[]},C=()=>YZ(y.dialect)?S():L(M(),"update"),v=async()=>{let q=await C();return Array.isArray(q)?q[0]:q},i=(q)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${q}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},m={where:(...q)=>{return d.where(...q),m},andWhere:(...q)=>{return d.where(...q),m},whereNull:(...q)=>{return d.whereNull(...q),m},whereNotNull:(...q)=>{return d.whereNotNull(...q),m},orWhere:i("orWhere"),orderBy:i("orderBy"),limit:i("limit"),offset:i("offset"),toSQL:()=>T(M(),P()),execute:C,get:C,first:v,executeTakeFirst:v,async firstOrFail(){let q=await v();if(!q)throw Error("Update with RETURNING returned no rows");return q},async executeTakeFirstOrThrow(){let q=await v();if(!q)throw Error("Update with RETURNING returned no rows");return q}};return m},toSQL(){if(!B)B=V.length>0?$.unsafe(I,V):$.unsafe(I);return T(B,I)},async execute(){let x=await L(B,"update");return O(x)},async executeTakeFirst(){return{numUpdatedRows:O(await L(B,"update"))}},async executeTakeFirstOrThrow(){let x=O(await L(B,"update"));if(x===0)throw Error("No rows updated");return{numUpdatedRows:x}},returningAll(){let x=()=>`${I} RETURNING *`,d=()=>V.length>0?$.unsafe(x(),V):$.unsafe(x());return{toSQL:()=>T(d(),x()),execute:()=>L(d(),"update"),async executeTakeFirst(){let P=await L(d(),"update");return Array.isArray(P)?P[0]:P},async executeTakeFirstOrThrow(){let P=await L(d(),"update"),M=Array.isArray(P)?P[0]:P;if(!M)throw Error("Update with RETURNING failed");return M}}}}},deleteFrom(K){let B=(M)=>{let S=String(M);if(YZ(y.dialect))return`\`${S.replace(/`/g,"``")}\``;return`"${S.replace(/"/g,'""')}"`},F=`DELETE FROM ${B(String(K))}`,I=null,E=[],n=null,x=!1,d=(M)=>{F+=` ${x?"AND":"WHERE"} ${M}`,x=!0},P=()=>{if(I===null)I=E.length>0?$.unsafe(F,E):$.unsafe(F);return I};return{where(M,S,C){if(n=M,typeof M==="string"&&S!==void 0){let v=kZ(S,"deleteFrom.where");if(v.toLowerCase()==="in"||v.toLowerCase()==="not in"){let m=Array.isArray(C)?C:[C],q=NZ(m.length,E.length+1);return d(`${B(M)} ${v.toUpperCase()} (${q})`),E.push(...m),I=null,this}let i=E.length+1;return d(`${B(M)} ${v} ${e(i)}`),E.push(C),I=null,this}if(Array.isArray(M)){let[v,i,m]=M,q=kZ(i,"deleteFrom.where");if(q.toLowerCase()==="in"||q.toLowerCase()==="not in"){let u=Array.isArray(m)?m:[m],r=NZ(u.length,E.length+1);return d(`${B(String(v))} ${q.toUpperCase()} (${r})`),E.push(...u),I=null,this}let l=E.length+1;return d(`${B(String(v))} ${q} ${e(l)}`),E.push(m),I=null,this}if(R8(M))return d(M.raw),I=null,this;if(u9(M)){let v=n9(M,E.length+1);return d(v.text),E.push(...v.parameters),I=null,this}if(M&&typeof M==="object"){let v=Object.keys(M);if(v.length===0)throw TypeError("[query-builder] deleteFrom.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if deleting every row is intended.");let i=v.map((m)=>W0(B(m),M[m],E));return d(i.join(" AND ")),I=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${M===null?"null":typeof M}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(M){return d(`${B(String(M))} IS NULL`),I=null,this},whereNotNull(M){return d(`${B(String(M))} IS NOT NULL`),I=null,this},returning(...M){let S=this,C=()=>`${F} RETURNING ${M.join(", ")}`,v=()=>E.length>0?$.unsafe(C(),E):$.unsafe(C()),i=async()=>{await U()?.beforeDelete?.({table:String(K),where:n});let u=YZ(y.dialect)?await(async()=>{let r=F.slice(F.search(/\sFROM\s/i)+1),b=`SELECT ${M.join(", ")} ${r}`,c=await(E.length>0?$.unsafe(b,E):$.unsafe(b)).execute();return await L(E.length>0?$.unsafe(F,E):$.unsafe(F),"delete"),Array.isArray(c)?c:[]})():await L(v(),"delete");try{await U()?.afterDelete?.({table:String(K),where:n,result:u})}catch{}return u},m=async()=>{let u=await i();return Array.isArray(u)?u[0]:u},q=(u)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${u}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},l={where:(...u)=>{return S.where(...u),l},andWhere:(...u)=>{return S.where(...u),l},whereNull:(...u)=>{return S.whereNull(...u),l},whereNotNull:(...u)=>{return S.whereNotNull(...u),l},orWhere:q("orWhere"),orderBy:q("orderBy"),limit:q("limit"),offset:q("offset"),toSQL:()=>T(v(),C()),execute:()=>i(),get:()=>i(),first:m,executeTakeFirst:m,async firstOrFail(){let u=await m();if(!u)throw Error("Delete with RETURNING returned no rows");return u},async executeTakeFirstOrThrow(){let u=await m();if(!u)throw Error("Delete with RETURNING returned no rows");return u}};return l},toSQL(){return T(P(),F)},async execute(){try{await U()?.beforeDelete?.({table:String(K),where:n})}catch(S){throw S}let M=O(await L(P(),"delete"));try{await U()?.afterDelete?.({table:String(K),where:n,result:M})}catch{}return M},async executeTakeFirst(){return{numDeletedRows:O(await L(P(),"delete"))}},async executeTakeFirstOrThrow(){let M=O(await L(P(),"delete"));if(M===0)throw Error("No rows deleted");return{numDeletedRows:M}},returningAll(){let M=()=>`${F} RETURNING *`,S=()=>E.length>0?$.unsafe(M(),E):$.unsafe(M());return{toSQL:()=>T(S(),M()),execute:()=>L(S(),"delete"),async executeTakeFirst(){let C=await L(S(),"delete");return Array.isArray(C)?C[0]:C},async executeTakeFirstOrThrow(){let C=await L(S(),"delete"),v=Array.isArray(C)?C[0]:C;if(!v)throw Error("Delete with RETURNING failed");return v}}}}},table(K){let B=this;return{insert(V){return B.insertInto(K).values(V)},update(V){return B.updateTable(K).set(V)},delete(){return B.deleteFrom(K)},select(...V){if(V.length===0)return B.selectFrom(K);return B.select(K,...V)}}},sql:$,raw(K,...B){return $(K,...B)},simple(K,...B){return $(K,...B).simple()},async advisoryLock(K){if(y.dialect==="postgres"){let B=G(K),V=$`SELECT pg_advisory_lock(${B})`;await L(V,"raw");return}if(YZ(y.dialect)){let B=`bqb:${String(K)}`,V=$`SELECT GET_LOCK(${B}, -1) AS ok`;await L(V,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(K){if(y.dialect==="postgres"){let B=G(K),V=$`SELECT pg_try_advisory_lock(${B}) as ok`,F=await L(V,"raw");return Boolean(F?.[0]?.ok)}if(YZ(y.dialect)){let B=`bqb:${String(K)}`,V=$`SELECT GET_LOCK(${B}, 0) AS ok`,F=await L(V,"raw");return Number(F?.[0]?.ok)===1}return!1},async advisoryUnlock(K){if(y.dialect==="postgres"){let B=G(K),V=$`SELECT pg_advisory_unlock(${B}) as ok`,F=await L(V,"raw");return Boolean(F?.[0]?.ok)}if(YZ(y.dialect)){let B=`bqb:${String(K)}`,V=$`SELECT RELEASE_LOCK(${B}) AS ok`,F=await L(V,"raw");return Number(F?.[0]?.ok)===1}return!1},unsafe(K,B){return $.unsafe(K,B)},file(K,B){return $.file(K,B)},async reserve(){let K=await $Z.reserve(),B=JZ({sql:K,meta:Y,schema:X,hooks:Z?.hooks});return B.release=()=>K.release(),B},async close(K){await $Z.close(K)},async listen(K,B){},async unlisten(K){},async notify(K,B){},async copyTo(K,B){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(K,B,V){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let K=$`SELECT 1`;return await L(K,"select"),!0}catch{return!1}},async waitForReady(K){let B=Math.max(1,K?.attempts??10),V=Math.max(10,K?.delayMs??100);for(let F=0;F<B;F++){if(await this.ping())return;await new Promise((I)=>setTimeout(I,V))}throw Error("Database not ready after waiting")},async transaction(K,B){let F={...Z?.txDefaults,...B},I=Z?.sql??$Z,E=Z?.inTransaction===!0,n=E&&typeof I?.savepoint==="function"?"savepoint":"begin",x=async(M)=>{F.logger?.({type:"start",attempt:M});let S=Date.now();return await I[n](async(C)=>{let v=JZ({sql:C,meta:Y,schema:X,hooks:Z?.hooks,inTransaction:!0});if(F?.isolation&&!E){let q=F.isolation,l=q==="read committed"?"READ COMMITTED":q==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(y.dialect==="postgres")await C.unsafe(`SET TRANSACTION ISOLATION LEVEL ${l}`);else if(YZ(y.dialect))await C.unsafe(`SET TRANSACTION ISOLATION LEVEL ${l}`);else if(q!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${q}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(F?.readOnly)if(y.dialect==="postgres")await C.unsafe("SET TRANSACTION READ ONLY");else if(YZ(y.dialect))await C.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let i=await K(v),m=Date.now()-S;return F.logger?.({type:"commit",attempt:M,durationMs:m}),i})},d=Math.max(0,F?.retries??0),P=0;for(;;)try{let M=await x(P+1);return F?.afterCommit?.(),M}catch(M){let S=I6(M)||M6(M,F.sqlStates);if(P<d&&S){P++,F?.onRetry?.(P,M);let C=N6(P,F.backoff);if(C>0)await w6(C);continue}try{F.onRollback?.(M)}catch{}try{F.afterRollback?.()}catch{}throw M}},async savepoint(K){if(Z?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let B=$;if(!B||typeof B.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await B.savepoint(async(V)=>{let F=JZ({sql:V,meta:Y,schema:X,hooks:Z?.hooks,inTransaction:!0});return await K(F)})},async beginDistributed(K,B){return await(Z?.sql??$Z).beginDistributed(K,async(I)=>{let E=JZ({sql:I,meta:Y,schema:X,hooks:Z?.hooks});return await B(E)})},async commitDistributed(K){await $Z.commitDistributed(K)},async rollbackDistributed(K){await $Z.rollbackDistributed(K)},setTransactionDefaults(K){Z={...Z,txDefaults:{...Z?.txDefaults,...K}}},transactional(K,B){return(...V)=>{return this.transaction((F)=>K(F,...V),B)}},async insertOrIgnore(K,B){let V=Array.isArray(B)?B:[B];if(!V.length)return;let{colsSql:F,valuesSql:I,params:E}=$7(V),n=tZ(String(K)),x=YZ(y.dialect)?`INSERT IGNORE INTO ${n} (${F}) VALUES ${I}`:`INSERT INTO ${n} (${F}) VALUES ${I} ON CONFLICT DO NOTHING`;return $.unsafe(x,E).execute()},async insertGetId(K,B,V="id"){let{colsSql:F,valuesSql:I,params:E}=$7([B]),n=tZ(String(K));if(YZ(y.dialect)){await $.unsafe(`INSERT INTO ${n} (${F}) VALUES ${I}`,E).execute();let[d]=await $.unsafe("SELECT LAST_INSERT_ID() as id").execute();return d?.id}if(y.dialect==="sqlite"){let d=await $.unsafe(`INSERT INTO ${n} (${F}) VALUES ${I}`,E).execute();if(d?.lastInsertRowid!=null)return d.lastInsertRowid;let[P]=await $.unsafe("SELECT last_insert_rowid() as id").execute();return P?.id}let[x]=await $.unsafe(`INSERT INTO ${n} (${F}) VALUES ${I} RETURNING ${tZ(String(V))} as id`,E).execute();return x?.id},async updateOrInsert(K,B,V){let F=tZ(String(K)),I=Object.keys(B),E=1,n=I.map((C)=>`${tZ(C)} = ${e(E++)}`).join(" AND "),x=I.map((C)=>B[C]);if((await $.unsafe(`SELECT 1 FROM ${F} WHERE ${n} LIMIT 1`,x).execute()).length){let C=Object.keys(V),v=1,i=C.map((l)=>`${tZ(l)} = ${e(v++)}`).join(", "),m=I.map((l)=>`${tZ(l)} = ${e(v++)}`).join(" AND "),q=[...C.map((l)=>V[l]),...I.map((l)=>B[l])];return await $.unsafe(`UPDATE ${F} SET ${i} WHERE ${m}`,q).execute(),!0}let{colsSql:P,valuesSql:M,params:S}=$7([{...B,...V}]);return await $.unsafe(`INSERT INTO ${F} (${P}) VALUES ${M}`,S).execute(),!0},async upsert(K,B,V,F){let I=V.map((i)=>String(i)),E=(F??[]).map((i)=>String(i)),n=B;if(!n.length)return;let{colsSql:x,valuesSql:d,params:P}=$7(n),M=tZ(String(K)),S=`INSERT INTO ${M} (${x}) VALUES ${d}`;if(YZ(y.dialect)){if(E.length===0)return $.unsafe(`INSERT IGNORE INTO ${M} (${x}) VALUES ${d}`,P).execute();let i=E.map((m)=>`${tZ(m)} = VALUES(${tZ(m)})`).join(", ");return $.unsafe(`${S} ON DUPLICATE KEY UPDATE ${i}`,P).execute()}let C=I.map(tZ).join(", ");if(E.length===0)return $.unsafe(`${S} ON CONFLICT (${C}) DO NOTHING`,P).execute();let v=E.map((i)=>`${tZ(i)} = EXCLUDED.${tZ(i)}`).join(", ");return $.unsafe(`${S} ON CONFLICT (${C}) DO UPDATE SET ${v}`,P).execute()},async save(K,B){let V=Y?.primaryKeys[String(K)]??"id",F=B[V];if(F!=null)if(await this.selectFrom(K).find(F)){await this.updateTable(K).set(B).where({[V]:F}).execute();let E=await this.selectFrom(K).find(F);if(!E)throw Error("save() failed to retrieve updated row");return E}else return await this.create(K,B);return await this.create(K,B)},async remove(K,B){return await this.deleteFrom(K).where({id:B}).execute()},async find(K,B){return await this.selectFrom(K).find(B)},async findOrFail(K,B){return await this.selectFrom(K).findOrFail(B)},async findMany(K,B){return await this.selectFrom(K).findMany(B)},async latest(K,B){return await this.selectFrom(K).latest(B).first()},async oldest(K,B){return await this.selectFrom(K).oldest(B).first()},skip(K,B){return this.selectFrom(K).offset(B)},async rawQuery(K){let B=Date.now();try{U()?.onQueryStart?.({sql:K,kind:"raw"});let V=await $.unsafe(K);return U()?.onQueryEnd?.({sql:K,durationMs:Date.now()-B,kind:"raw"}),V}catch(V){throw U()?.onQueryError?.({sql:K,error:V,durationMs:Date.now()-B,kind:"raw"}),V}},async create(K,B){let V=Y?.primaryKeys[String(K)]??"id";try{await U()?.beforeCreate?.({table:String(K),data:B})}catch(F){throw F}if(y.dialect==="postgres"){let F=$`INSERT INTO ${$(String(K))} ${$(B)} RETURNING ${$(String(V))} as id`,[I]=await F.execute();if(!I?.id)throw console.error(`create() failed to get insert ID for table ${String(K)}`),console.error("Inserted values:",B),Error(`create() failed to get insert ID for table ${String(K)}`);let E=await this.selectFrom(K).find(I.id);if(!E)throw console.error(`create() failed to retrieve inserted row for table ${String(K)} with id ${I.id}`),console.error("Inserted values:",B),Error(`create() failed to retrieve inserted row for table ${String(K)} with id ${I.id}`);try{await U()?.afterCreate?.({table:String(K),data:B,result:E})}catch{}return E}else{let F=await this.insertGetId(K,B,V);if(F==null)throw Error(`create() failed to get insert ID for table ${String(K)}`);let I=await this.selectFrom(K).find(F);if(!I)throw console.error(`create() failed to retrieve inserted row for table ${String(K)} with id ${F}`),console.error("Inserted values:",B),Error(`create() failed to retrieve inserted row for table ${String(K)} with id ${F}`);try{await U()?.afterCreate?.({table:String(K),data:B,result:I})}catch{}return I}},async createMany(K,B){if(!B?.length)return;let V=B[0],F=Object.keys(V),I=F.length,E=B.length,n=Array.from({length:E*I}),x=YZ(y.dialect)?(M)=>`\`${String(M).replace(/`/g,"``")}\``:(M)=>`"${String(M).replace(/"/g,'""')}"`,d=`INSERT INTO ${x(String(K))}(${F.map(x).join(",")})VALUES`,P=0;for(let M=0;M<E;M++){if(M>0)d+=",";d+="(";let S=B[M];for(let C=0;C<I;C++){if(C>0)d+=",";d+=e(P+1),n[P++]=S[F[C]]}d+=")"}return $.unsafe(d,n).execute()},async insertMany(K,B){if(!B?.length)return;let V=B[0],F=Object.keys(V),I=F.length,E=B.length,n=E*I,x=Array(n),d=y.dialect==="postgres",P;if(!d){let C=Array(I);for(let v=0;v<I;v++)C[v]="?";P=`(${C.join(",")})`}else P="";let M=Array(E+2);M[0]=`INSERT INTO ${K}(${F.join(",")})VALUES`;let S=0;if(!d){for(let C=0;C<E;C++){let v=B[C];M[C+1]=P;for(let i=0;i<I;i++)x[S++]=v[F[i]]}return $.unsafe(M[0]+M.slice(1,E+1).join(","),x).execute()}for(let C=0;C<E;C++){let v=B[C],i=Array(I);for(let m=0;m<I;m++)i[m]=`$${S+1}`,x[S++]=v[F[m]];M[C+1]=`(${i.join(",")})`}return $.unsafe(M[0]+M.slice(1,E+1).join(","),x).execute()},async updateMany(K,B,V){let F=Object.keys(V),I=F.length;if(I===0)return 0;let E=[],n=Array.from({length:I});for(let d=0;d<I;d++)n[d]=`${F[d]}=${e(d+1)}`,E.push(V[F[d]]);let x=`UPDATE ${K} SET ${n.join(",")}`;if(Array.isArray(B)){let d=kZ(String(B[1]),"updateMany");x+=` WHERE ${B[0]} ${d} ${e(E.length+1)}`,E.push(B[2])}else if(R8(B))x+=` WHERE ${B.raw}`;else if(u9(B)){let d=n9(B,E.length+1);x+=` WHERE ${d.text}`,E.push(...d.parameters)}else if(B&&typeof B==="object"&&Object.keys(B).length>0){let d=Object.keys(B).map((P)=>W0(P,B[P],E));x+=` WHERE ${d.join(" AND ")}`}else if(B&&typeof B==="object")throw TypeError("[query-builder] updateMany(): an empty object is not a filter. Pass a condition, or use updateTable(table).set(data).execute() if updating every row is intended.");else throw TypeError(`[query-builder] updateMany(): expected a condition, got ${B===null?"null":typeof B}. Refusing to run an UPDATE with no WHERE \u2014 use updateTable(table).set(data).execute() if updating every row is intended.`);return $.unsafe(x,E).execute()},async deleteMany(K,B){if(!Array.isArray(B)||B.length===0)return 0;let V=Y?.primaryKeys[String(K)]??"id",F=B.length;if(y.dialect==="postgres"){let E=Array(F);for(let n=0;n<F;n++)E[n]=`$${n+1}`;return $.unsafe(`DELETE FROM ${K} WHERE ${V} IN (${E.join(",")})`,B).execute()}let I=Array(F);for(let E=0;E<F;E++)I[E]="?";return $.unsafe(`DELETE FROM ${K} WHERE ${V} IN (${I.join(",")})`,B).execute()},async firstOrCreate(K,B,V){let F=await this.selectFrom(K).where(B).first();if(F)return F;return await this.create(K,{...B,...V})},async updateOrCreate(K,B,V){let F=await this.selectFrom(K).where(B).first();if(F){await this.updateTable(K).set(V).where(B).execute();let I=Y?.primaryKeys[String(K)]??"id",E=F[I],n=E!=null?await this.selectFrom(K).find(E):await this.selectFrom(K).where(B).first();if(!n)throw Error("updateOrCreate() failed to retrieve updated row");return n}return await this.create(K,{...B,...V})},async count(K,B){let V=B?$(String(B)):$`*`,F=$`SELECT COUNT(${V}) as c FROM ${$(String(K))}`,[I]=await F.execute();return Number(I?.c??0)},async sum(K,B){let V=$`SELECT SUM(${$(String(B))}) as s FROM ${$(String(K))}`,[F]=await V.execute();return Number(F?.s??0)},async avg(K,B){let V=$`SELECT AVG(${$(String(B))}) as a FROM ${$(String(K))}`,[F]=await V.execute();return Number(F?.a??0)},async min(K,B){let V=$`SELECT MIN(${$(String(B))}) as m FROM ${$(String(K))}`,[F]=await V.execute();return F?.m},async max(K,B){let V=$`SELECT MAX(${$(String(B))}) as m FROM ${$(String(K))}`,[F]=await V.execute();return F?.m},getRelationships(K){if(!Y?.relations)return{};let B=Y.relations[K];if(!B)return{};let V={};for(let[F,I]of Object.entries(B))if(I&&typeof I==="object"&&Object.keys(I).length>0)V[F]=I;return V},hasRelationship(K,B){if(!Y?.relations)return!1;let V=Y.relations[K];if(!V)return!1;return Object.values(V).some((F)=>F&&typeof F==="object"&&(B in F))},getRelationshipType(K,B){if(!Y?.relations)return null;let V=Y.relations[K];if(!V)return null;for(let[F,I]of Object.entries(V))if(I&&typeof I==="object"&&B in I)return F;return null},getRelationshipTarget(K,B){if(!Y?.relations)return null;let V=Y.relations[K];if(!V)return null;for(let[F,I]of Object.entries(V))if(I&&typeof I==="object"&&B in I){let E=I[B];if(typeof E==="string")return Y.modelToTable[E]||E;else if(E&&typeof E==="object"){if("model"in E)return Y.modelToTable[E.model]||E.model;if("target"in E)return Y.modelToTable[E.target]||E.target}}return null}}}function fX(){X7.clear()}function gX(Z){X7.setMaxSize(Z)}async function P6(){console.log("-- Clearing query cache..."),fX(),console.log("-- \u2713 Query cache cleared")}async function T6(){console.log("-- Query Cache Information"),console.log(),console.log("The query cache is an LRU (Least Recently Used) cache with TTL support."),console.log(),console.log("Configuration:"),console.log(" - Default max size: 100 entries"),console.log(" - Default TTL: 60 seconds (60000ms)"),console.log(" - Eviction: LRU when cache is full"),console.log(),console.log("Usage:"),console.log(' qb.selectFrom("users").cache().get() // Cache for 60s'),console.log(' qb.selectFrom("users").cache(5000).get() // Cache for 5s'),console.log(),console.log("Configuration:"),console.log(" clearQueryCache() // Clear all cached queries"),console.log(" setQueryCacheMaxSize(500) // Set max cache size"),console.log(),console.log("Commands:"),console.log(" qb cache:clear // Clear the cache"),console.log(" qb cache:config --size 500 // Configure cache size")}async function q6(Z={}){if(console.log("-- Configuring query cache..."),console.log(),Z.size!==void 0){let $=Number(Z.size);if(Number.isNaN($)||$<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");gX($),console.log(`-- \u2713 Cache max size set to: ${$}`)}else console.log("-- No configuration changes specified"),console.log("-- Available options:"),console.log("-- --size <n> Set maximum cache size (default: 100)"),console.log(),console.log("-- Example: qb cache:config --size 500")}import J7 from"process";import{createInterface as k6}from"readline";async function pX(){console.log("-- Query Builder Interactive Console"),console.log("-- Type .help for available commands"),console.log("-- Type .exit or press Ctrl+C to quit"),console.log();let Z=JZ(),$=k6({input:J7.stdin,output:J7.stdout,prompt:"qb> "}),Y="",X=!1,J=`
|
|
113
|
-
Available Commands:
|
|
114
|
-
.help Show this help message
|
|
115
|
-
.exit Exit the console
|
|
116
|
-
.tables List all tables
|
|
117
|
-
.clear Clear the screen
|
|
118
|
-
|
|
119
|
-
Query Examples:
|
|
120
|
-
qb.selectFrom('users').where({ active: true }).limit(10).execute()
|
|
121
|
-
qb.selectFrom('users').count()
|
|
122
|
-
qb.insertInto('users').values({ name: 'John' }).execute()
|
|
123
|
-
qb.selectFrom('users').where('id', '=', 1).first()
|
|
124
|
-
qb.unsafe("SELECT * FROM users WHERE id = $1", [1]).execute()
|
|
125
|
-
|
|
126
|
-
Tips:
|
|
127
|
-
- Use 'qb' to access the query builder
|
|
128
|
-
- Use 'await' for async operations
|
|
129
|
-
- Multi-line input: end with \\ to continue on next line
|
|
130
|
-
- Press Enter on an empty line to execute multi-line input
|
|
131
|
-
`,G=async(H)=>{try{let W=await new(Object.getPrototypeOf(async()=>{})).constructor("qb",`return (${H})`)(Z);if(W!==void 0)if(Array.isArray(W))console.log(`-- ${W.length} row(s) returned`),console.table(W);else if(typeof W==="object"&&W!==null)console.log(W);else console.log(W)}catch(z){console.error("Error:",z.message)}},U=async(H)=>{let z=H.trim();if(z.startsWith(".")){let A=z.toLowerCase();if(A===".exit"||A===".quit")console.log("Goodbye!"),$.close(),J7.exit(0);else if(A===".help")console.log(J);else if(A===".clear")console.clear();else if(A===".tables")try{let W=await Z.unsafe(`
|
|
132
|
-
SELECT name FROM sqlite_master
|
|
133
|
-
WHERE type = 'table'
|
|
134
|
-
AND name NOT LIKE 'sqlite_%'
|
|
135
|
-
ORDER BY name
|
|
136
|
-
`);if(W.length>0){console.log("Tables:");for(let Q of W)console.log(` - ${Q.name}`)}else console.log("No tables found")}catch(W){console.error("Error listing tables:",W.message)}else console.log(`Unknown command: ${z}`),console.log("Type .help for available commands");return}if(z.endsWith("\\")){X=!0,Y+=`${z.slice(0,-1)}
|
|
137
|
-
`;return}if(X){if(z==="")await G(Y),Y="",X=!1;else Y+=`${z}
|
|
138
|
-
`;return}if(z)await G(z)};$.on("line",async(H)=>{await U(H),$.prompt()}),$.on("SIGINT",()=>{if(X)console.log(`
|
|
139
|
-
-- Multi-line input cancelled`),Y="",X=!1,$.prompt();else console.log(`
|
|
140
|
-
-- Type .exit to quit`),$.prompt()}),$.on("close",()=>{console.log(`
|
|
141
|
-
Goodbye!`),J7.exit(0)}),$.prompt()}async function x6(){return pX()}qZ();import{existsSync as v6,readFileSync as y6,writeFileSync as s9}from"fs";async function h6(Z,$={}){let Y=$.format||"json",X=$.output||`${Z}.${Y}`,J=$.limit;if(console.log(`-- Exporting data from table: ${Z}`),console.log(`-- Format: ${Y}`),console.log(`-- Output: ${X}`),J)console.log(`-- Limit: ${J} rows`);console.log();try{let U=JZ().selectFrom(Z);if(J)U=U.limit(J);let H=await U.execute();if(console.log(`-- Retrieved ${H.length} rows`),Y==="json")s9(X,JSON.stringify(H,null,2)),console.log(`-- \u2713 Exported to JSON: ${X}`);else if(Y==="csv"){if(H.length===0){s9(X,""),console.log(`-- \u2713 Exported to CSV: ${X} (empty)`);return}let z=Object.keys(H[0]),A=[z.join(",")];for(let W of H){let Q=z.map((L)=>{let O=W[L];if(O===null||O===void 0)return"";let T=String(O);if(T.includes(",")||T.includes('"')||T.includes(`
|
|
142
|
-
`))return`"${T.replace(/"/g,'""')}"`;return T});A.push(Q.join(","))}s9(X,A.join(`
|
|
143
|
-
`)),console.log(`-- \u2713 Exported to CSV: ${X}`)}else if(Y==="sql"){let z=[];for(let A of H){let W=Object.keys(A),Q=W.map((L)=>{let O=A[L];if(O===null||O===void 0)return"NULL";if(typeof O==="number")return String(O);return`'${String(O).replace(/'/g,"''")}'`});z.push(`INSERT INTO ${Z} (${W.join(", ")}) VALUES (${Q.join(", ")});`)}s9(X,z.join(`
|
|
144
|
-
`)),console.log(`-- \u2713 Exported to SQL: ${X}`)}}catch(G){throw console.error(`-- Failed to export data from ${Z}:`,G),G}}async function b6(Z,$,Y={}){if(!v6($))throw console.error(`-- File not found: ${$}`),Error(`File not found: ${$}`);let X=Y.format||($.endsWith(".json")?"json":"csv"),J=Y.truncate??!1;console.log(`-- Importing data into table: ${Z}`),console.log(`-- Format: ${X}`),console.log(`-- File: ${$}`),console.log(`-- Truncate: ${J}`),console.log();try{let G=JZ();if(J)await G.deleteFrom(Z).execute(),console.log("-- Table truncated");let U=y6($,"utf8"),H=[];if(X==="json"){if(H=JSON.parse(U),!Array.isArray(H))throw TypeError("JSON file must contain an array of objects")}else if(X==="csv"){let W=U.split(`
|
|
145
|
-
`).filter((L)=>L.trim());if(W.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let Q=W[0].split(",").map((L)=>L.trim());for(let L=1;L<W.length;L++){let O=W[L].split(",").map((w)=>w.trim()),T={};for(let w=0;w<Q.length;w++){let K=O[w];if(K.startsWith('"')&&K.endsWith('"'))K=K.slice(1,-1).replace(/""/g,'"');if(K==="")K=null;else if(!Number.isNaN(Number(K)))K=Number(K);T[Q[w]]=K}H.push(T)}}if(H.length===0){console.log("-- No data to import");return}let z=100,A=0;for(let W=0;W<H.length;W+=z){let Q=H.slice(W,W+z);await G.insertInto(Z).values(Q).execute(),A+=Q.length,console.log(`-- Imported ${A}/${H.length} rows...`)}console.log(`-- \u2713 Successfully imported ${H.length} rows`)}catch(G){throw console.error(`-- Failed to import data into ${Z}:`,G),G}}async function f6(Z={}){let $=y.dialect||"postgres",Y=Z.output||`dump-${Date.now()}.sql`,X=Z.tables?.split(",").map((J)=>J.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${$}`),console.log(`-- Output: ${Y}`),X)console.log(`-- Tables: ${X.join(", ")}`);console.log();try{let J=JZ(),G=[];if($==="sqlite")G=(await J.unsafe(`
|
|
146
|
-
SELECT name FROM sqlite_master
|
|
147
|
-
WHERE type = 'table'
|
|
148
|
-
AND name NOT LIKE 'sqlite_%'
|
|
149
|
-
ORDER BY name
|
|
150
|
-
`)).map((z)=>z.name);else if($==="postgres")G=(await J.unsafe(`
|
|
151
|
-
SELECT table_name
|
|
152
|
-
FROM information_schema.tables
|
|
153
|
-
WHERE table_schema = 'public'
|
|
154
|
-
AND table_type = 'BASE TABLE'
|
|
155
|
-
ORDER BY table_name
|
|
156
|
-
`)).map((z)=>z.table_name);else if(YZ($))G=(await J.unsafe(`
|
|
157
|
-
SELECT table_name
|
|
158
|
-
FROM information_schema.tables
|
|
159
|
-
WHERE table_schema = DATABASE()
|
|
160
|
-
AND table_type = 'BASE TABLE'
|
|
161
|
-
ORDER BY table_name
|
|
162
|
-
`)).map((z)=>z.table_name);if(X)G=G.filter((H)=>X.includes(H));if(G.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${G.length} table(s)`);let U=[];U.push("-- Database dump"),U.push(`-- Generated at: ${new Date().toISOString()}`),U.push(`-- Dialect: ${$}`),U.push("");for(let H of G){console.log(`-- Dumping table: ${H}`);let z=await J.selectFrom(H).execute();U.push(`-- Table: ${H}`),U.push(`-- Rows: ${z.length}`),U.push("");for(let A of z){let W=Object.keys(A),Q=W.map((L)=>{let O=A[L];if(O===null||O===void 0)return"NULL";if(typeof O==="number")return String(O);return`'${String(O).replace(/'/g,"''")}'`});U.push(`INSERT INTO ${H} (${W.join(", ")}) VALUES (${Q.join(", ")});`)}U.push("")}s9(Y,U.join(`
|
|
163
|
-
`)),console.log(),console.log(`-- \u2713 Database dump saved to: ${Y}`)}catch(J){throw console.error("-- Failed to dump database:",J),J}}qZ();async function dX(){let Z=y.dialect||"postgres",$=y.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${Z}`),console.log(`-- Database: ${$}`),console.log();try{let Y=JZ(),X=[],J=[];if(Z==="postgres")J=(await Y.unsafe(`
|
|
164
|
-
SELECT table_name
|
|
165
|
-
FROM information_schema.tables
|
|
166
|
-
WHERE table_schema = 'public'
|
|
167
|
-
AND table_type = 'BASE TABLE'
|
|
168
|
-
ORDER BY table_name
|
|
169
|
-
`)).map((H)=>H.table_name);else if(YZ(Z))J=(await Y.unsafe(`
|
|
170
|
-
SELECT table_name
|
|
171
|
-
FROM information_schema.tables
|
|
172
|
-
WHERE table_schema = DATABASE()
|
|
173
|
-
AND table_type = 'BASE TABLE'
|
|
174
|
-
ORDER BY table_name
|
|
175
|
-
`)).map((H)=>H.table_name);else if(Z==="sqlite")J=(await Y.unsafe(`
|
|
176
|
-
SELECT name
|
|
177
|
-
FROM sqlite_master
|
|
178
|
-
WHERE type = 'table'
|
|
179
|
-
AND name NOT LIKE 'sqlite_%'
|
|
180
|
-
ORDER BY name
|
|
181
|
-
`)).map((H)=>H.name);for(let U of J)try{let H=await Y.unsafe(`SELECT COUNT(*) as count FROM ${U}`),z=Number(H[0]?.count||0),A=0,W=0;if(Z==="postgres"){let Q=await Y.unsafe(`
|
|
182
|
-
SELECT COUNT(*) as count
|
|
183
|
-
FROM information_schema.columns
|
|
184
|
-
WHERE table_name = $1
|
|
185
|
-
`,[U]);A=Number(Q[0]?.count||0);let L=await Y.unsafe(`
|
|
186
|
-
SELECT COUNT(*) as count
|
|
187
|
-
FROM pg_indexes
|
|
188
|
-
WHERE tablename = $1
|
|
189
|
-
`,[U]);W=Number(L[0]?.count||0)}else if(YZ(Z)){let Q=await Y.unsafe(`
|
|
190
|
-
SELECT COUNT(*) as count
|
|
191
|
-
FROM information_schema.columns
|
|
192
|
-
WHERE table_name = ?
|
|
193
|
-
AND table_schema = DATABASE()
|
|
194
|
-
`,[U]);A=Number(Q[0]?.count||0);let L=await Y.unsafe(`
|
|
195
|
-
SELECT COUNT(*) as count
|
|
196
|
-
FROM information_schema.statistics
|
|
197
|
-
WHERE table_name = ?
|
|
198
|
-
AND table_schema = DATABASE()
|
|
199
|
-
`,[U]);W=Number(L[0]?.count||0)}else if(Z==="sqlite")A=(await Y.unsafe(`PRAGMA table_info(${U})`)).length,W=(await Y.unsafe(`PRAGMA index_list(${U})`)).length;X.push({name:U,rowCount:z,columns:A,indexes:W})}catch(H){console.error(`-- Error getting info for table ${U}:`,H)}let G=X.reduce((U,H)=>U+H.rowCount,0);if(console.log(`-- Total Tables: ${X.length}`),console.log(`-- Total Rows: ${G.toLocaleString()}`),console.log(),X.length>0){console.log("Tables:"),console.log();let U=Math.max(...X.map((A)=>A.name.length)),H=U+2,z="Table".padEnd(H)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(z),console.log("-".repeat(z.length));for(let A of X){let W=A.name.padEnd(U+2),Q=A.rowCount.toLocaleString().padStart(12),L=(A.columns||0).toString().padStart(10),O=(A.indexes||0).toString().padStart(10);console.log(`${W}${Q}${L}${O}`)}}else console.log("-- No tables found");return{dialect:Z,database:$,tables:X,totalTables:X.length,totalRows:G}}catch(Y){throw console.error("-- Failed to get database info:",Y),Y}}async function g6(){return dX()}qZ();g8();async function mX(Z={}){let $=n$(Z.dialect),Y=Z.aggressive||!1;if(Z.verbose)console.log(`Optimizing ${$} database${Y?" (aggressive mode)":""}...`);try{if($==="postgres"){if(Z.tables&&Z.tables.length>0)for(let X of Z.tables){if(Z.verbose)console.log(`Analyzing table: ${X}`);if(Y)await $Z`VACUUM FULL ANALYZE ${$Z(X)}`;else await $Z`VACUUM ANALYZE ${$Z(X)}`}else{if(Z.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(Y)await $Z`VACUUM FULL`,await $Z`ANALYZE`;else await $Z`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(YZ($)){if(Z.tables&&Z.tables.length>0)for(let X of Z.tables){if(Z.verbose)console.log(`Optimizing table: ${X}`);await $Z`OPTIMIZE TABLE ${$Z(X)}`,await $Z`ANALYZE TABLE ${$Z(X)}`}else{let X=s$(),J=await $Z`
|
|
200
|
-
SELECT table_name
|
|
201
|
-
FROM information_schema.tables
|
|
202
|
-
WHERE table_schema = ${X}
|
|
203
|
-
`;for(let G of J){let U=G.table_name||G.TABLE_NAME;if(Z.verbose)console.log(`Optimizing table: ${U}`);await $Z`OPTIMIZE TABLE ${$Z(U)}`,await $Z`ANALYZE TABLE ${$Z(U)}`}}console.log("\u2713 MySQL optimization complete")}else if($==="sqlite"){if(Z.verbose)console.log("Running VACUUM on SQLite database...");if(await $Z`VACUUM`,Z.tables&&Z.tables.length>0)for(let X of Z.tables){if(Z.verbose)console.log(`Analyzing table: ${X}`);await $Z`ANALYZE ${$Z(X)}`}else await $Z`ANALYZE`;if(Y){if(Z.verbose)console.log("Running aggressive SQLite optimizations...");await $Z`PRAGMA optimize`,await $Z`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${$}`)}catch(X){throw console.error("Error optimizing database:",X.message),X}}qZ();g8();async function cX(Z={}){let $=n$(Z.dialect);if(Z.verbose)console.log(`Wiping all tables from ${$} database...`);try{let Y=[];if($==="postgres")Y=(await $Z`
|
|
204
|
-
SELECT tablename
|
|
205
|
-
FROM pg_tables
|
|
206
|
-
WHERE schemaname = 'public'
|
|
207
|
-
`).map((J)=>J.tablename);else if(YZ($)){let X=s$();Y=(await $Z`
|
|
208
|
-
SELECT table_name
|
|
209
|
-
FROM information_schema.tables
|
|
210
|
-
WHERE table_schema = ${X}
|
|
211
|
-
`).map((G)=>G.table_name||G.TABLE_NAME)}else if($==="sqlite")Y=(await $Z`
|
|
212
|
-
SELECT name
|
|
213
|
-
FROM sqlite_master
|
|
214
|
-
WHERE type = 'table'
|
|
215
|
-
AND name NOT LIKE 'sqlite_%'
|
|
216
|
-
`).map((J)=>J.name);if(Y.length===0){console.log("No tables found to drop.");return}if(Z.verbose)console.log(`Found ${Y.length} tables: ${Y.join(", ")}`);if($==="postgres")for(let X of Y){if(Z.verbose)console.log(`Dropping table: ${X}`);await $Z`DROP TABLE IF EXISTS ${$Z(X)} CASCADE`}else if(YZ($)){await $Z`SET FOREIGN_KEY_CHECKS = 0`;for(let X of Y){if(Z.verbose)console.log(`Dropping table: ${X}`);await $Z`DROP TABLE IF EXISTS ${$Z(X)}`}await $Z`SET FOREIGN_KEY_CHECKS = 1`}else if($==="sqlite"){await $Z`PRAGMA foreign_keys = OFF`;for(let X of Y){if(Z.verbose)console.log(`Dropping table: ${X}`);await $Z`DROP TABLE IF EXISTS ${$Z(X)}`}await $Z`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${Y.length} tables`)}catch(Y){throw console.error("Error wiping database:",Y.message),Y}}async function p6(Z){let X=await(JZ().raw([Z]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(X,null,2)),X}async function d6(Z,$={}){let Y=JZ(),X=$.params?JSON.parse($.params):void 0,J=await Y.file(Z,X);return console.log(JSON.stringify(J)),J}qZ();async function uX(Z,$={}){let Y=y.dialect||"postgres",X=$.verbose??!0;if(X)console.log(`-- Inspecting table: ${Z}`),console.log(`-- Dialect: ${Y}`),console.log();try{let J=JZ(),G=[],U=[],H=await J.unsafe(`SELECT COUNT(*) as count FROM ${Z}`),z=Number(H[0]?.count||0);if(Y==="postgres"){let A=await J.unsafe(`
|
|
217
|
-
SELECT
|
|
218
|
-
c.column_name,
|
|
219
|
-
c.data_type,
|
|
220
|
-
c.is_nullable,
|
|
221
|
-
c.column_default,
|
|
222
|
-
CASE
|
|
223
|
-
WHEN pk.column_name IS NOT NULL THEN true
|
|
224
|
-
ELSE false
|
|
225
|
-
END as is_primary_key,
|
|
226
|
-
CASE
|
|
227
|
-
WHEN fk.column_name IS NOT NULL THEN true
|
|
228
|
-
ELSE false
|
|
229
|
-
END as is_foreign_key
|
|
230
|
-
FROM information_schema.columns c
|
|
231
|
-
LEFT JOIN (
|
|
232
|
-
SELECT ku.column_name
|
|
233
|
-
FROM information_schema.table_constraints tc
|
|
234
|
-
JOIN information_schema.key_column_usage ku
|
|
235
|
-
ON tc.constraint_name = ku.constraint_name
|
|
236
|
-
WHERE tc.constraint_type = 'PRIMARY KEY'
|
|
237
|
-
AND tc.table_name = $1
|
|
238
|
-
) pk ON c.column_name = pk.column_name
|
|
239
|
-
LEFT JOIN (
|
|
240
|
-
SELECT ku.column_name
|
|
241
|
-
FROM information_schema.table_constraints tc
|
|
242
|
-
JOIN information_schema.key_column_usage ku
|
|
243
|
-
ON tc.constraint_name = ku.constraint_name
|
|
244
|
-
WHERE tc.constraint_type = 'FOREIGN KEY'
|
|
245
|
-
AND tc.table_name = $1
|
|
246
|
-
) fk ON c.column_name = fk.column_name
|
|
247
|
-
WHERE c.table_name = $1
|
|
248
|
-
ORDER BY c.ordinal_position
|
|
249
|
-
`,[Z]);for(let Q of A)G.push({name:Q.column_name,type:Q.data_type,nullable:Q.is_nullable==="YES",default:Q.column_default,isPrimaryKey:Q.is_primary_key,isForeignKey:Q.is_foreign_key});let W=await J.unsafe(`
|
|
250
|
-
SELECT
|
|
251
|
-
i.indexname as name,
|
|
252
|
-
i.indexdef,
|
|
253
|
-
ix.indisunique as is_unique
|
|
254
|
-
FROM pg_indexes i
|
|
255
|
-
JOIN pg_class c ON c.relname = i.indexname
|
|
256
|
-
JOIN pg_index ix ON ix.indexrelid = c.oid
|
|
257
|
-
WHERE i.tablename = $1
|
|
258
|
-
`,[Z]);for(let Q of W){let L=Q.indexdef?.match(/\(([^)]+)\)/),T=(L?L[1]:"").split(",").map((w)=>w.trim());U.push({name:Q.name,columns:T,unique:Q.is_unique})}}else if(YZ(Y)){let A=await J.unsafe(`
|
|
259
|
-
SELECT
|
|
260
|
-
COLUMN_NAME as column_name,
|
|
261
|
-
DATA_TYPE as data_type,
|
|
262
|
-
IS_NULLABLE as is_nullable,
|
|
263
|
-
COLUMN_DEFAULT as column_default,
|
|
264
|
-
COLUMN_KEY as column_key
|
|
265
|
-
FROM information_schema.COLUMNS
|
|
266
|
-
WHERE TABLE_NAME = ?
|
|
267
|
-
AND TABLE_SCHEMA = DATABASE()
|
|
268
|
-
ORDER BY ORDINAL_POSITION
|
|
269
|
-
`,[Z]);for(let L of A)G.push({name:L.column_name,type:L.data_type,nullable:L.is_nullable==="YES",default:L.column_default,isPrimaryKey:L.column_key==="PRI",isForeignKey:L.column_key==="MUL"});let W=await J.unsafe(`
|
|
270
|
-
SHOW INDEXES FROM ${Z}
|
|
271
|
-
`),Q=new Map;for(let L of W){let O=L.Key_name;if(!Q.has(O))Q.set(O,{columns:[],unique:L.Non_unique===0});Q.get(O).columns.push(L.Column_name)}for(let[L,O]of Q)U.push({name:L,columns:O.columns,unique:O.unique})}else if(Y==="sqlite"){let A=await J.unsafe(`PRAGMA table_info(${Z})`);for(let Q of A)G.push({name:Q.name,type:Q.type,nullable:Q.notnull===0,default:Q.dflt_value,isPrimaryKey:Q.pk===1});let W=await J.unsafe(`PRAGMA index_list(${Z})`);for(let Q of W){let L=await J.unsafe(`PRAGMA index_info(${Q.name})`);U.push({name:Q.name,columns:L.map((O)=>O.name),unique:Q.unique===1})}}if(X){console.log(`Table: ${Z}`),console.log(`Rows: ${z.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let A=Math.max(...G.map((T)=>T.name.length),10),W=Math.max(...G.map((T)=>T.type.length),10),Q=A+2,L=W+2,O=`${"Name".padEnd(Q)+"Type".padEnd(L)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(O),console.log("-".repeat(O.length));for(let T of G){let w=T.name.padEnd(Q),K=T.type.padEnd(L),B=(T.nullable?"YES":"NO").padEnd(10),V=String(T.default||"").padEnd(20),F=[T.isPrimaryKey?"PK":"",T.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${w}${K}${B}${V}${F}`)}if(console.log(),U.length>0){console.log("Indexes:"),console.log();for(let T of U){let w=T.unique?" (UNIQUE)":"";console.log(` - ${T.name}${w}: [${T.columns.join(", ")}]`)}console.log()}}return{tableName:Z,rowCount:z,columns:G,indexes:U}}catch(J){throw console.error(`-- Failed to inspect table ${Z}:`,J),J}}async function m6(Z,$={}){return uX(Z,$)}async function c6(Z,$={}){let Y=await Q8({modelsDir:Z}),X=G7(Y);return console.log(JSON.stringify(X,null,2)),{models:Y,schema:X}}qZ();function nX(Z){let $=Z.toLowerCase();if(/^bool|boolean|tinyint\(1\)/.test($))return"boolean";if(/int|serial|numeric|decimal|double|real|float|money/.test($))return"number";if(/timestamp|datetime|date|time/.test($))return"datetime";if(/json/.test($))return"json";return"string"}function u6(Z){if(/ies$/i.test(Z))return Z.replace(/ies$/i,"y");if(/ses$/i.test(Z))return Z.replace(/es$/i,"");if(/s$/i.test(Z)&&!/ss$/i.test(Z))return Z.replace(/s$/i,"");return Z}function n6(Z){return Z.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join("")}function j0(Z){return n6(u6(Z))}async function iX(Z,$){if($==="postgres")return(await Z.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name")).map((J)=>J.table_name);if(YZ($))return(await Z.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' ORDER BY table_name")).map((J)=>J.table_name??J.TABLE_NAME);return(await Z.unsafe("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")).map((X)=>X.name)}async function i6(Z,$,Y){if($==="sqlite")return(await Z.unsafe(`PRAGMA table_info(${Y})`)).map((G)=>({name:G.name,sqlType:String(G.type||""),nullable:Number(G.notnull)===0,isPrimaryKey:Number(G.pk)>0}));if($==="postgres")return(await Z.unsafe(`SELECT c.column_name, c.data_type, c.is_nullable,
|
|
272
|
-
(SELECT COUNT(*) FROM information_schema.table_constraints tc
|
|
273
|
-
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
|
|
274
|
-
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
|
|
275
|
-
FROM information_schema.columns c
|
|
276
|
-
WHERE c.table_name = $1 AND c.table_schema = 'public'
|
|
277
|
-
ORDER BY c.ordinal_position`,[Y])).map((G)=>({name:G.column_name,sqlType:String(G.data_type||""),nullable:String(G.is_nullable).toUpperCase()==="YES",isPrimaryKey:Number(G.is_pk)>0}));return(await Z.unsafe(`SELECT column_name, data_type, is_nullable, column_key
|
|
278
|
-
FROM information_schema.columns
|
|
279
|
-
WHERE table_name = ? AND table_schema = DATABASE()
|
|
280
|
-
ORDER BY ordinal_position`,[Y])).map((J)=>({name:J.column_name??J.COLUMN_NAME,sqlType:String(J.data_type??J.DATA_TYPE??""),nullable:String(J.is_nullable??J.IS_NULLABLE).toUpperCase()==="YES",isPrimaryKey:String(J.column_key??J.COLUMN_KEY).toUpperCase()==="PRI"}))}function lX(Z,$){let Y=j0(Z),X=$.find((G)=>G.isPrimaryKey)?.name??"id",J=$.map((G)=>{let U=[`type: '${nX(G.sqlType)}'`];if(!G.nullable&&!G.isPrimaryKey)U.push("required: true");return` ${G.name}: { ${U.join(", ")} },`}).join(`
|
|
281
|
-
`);return`export const ${Y} = defineModel({
|
|
282
|
-
name: '${Y}',
|
|
283
|
-
table: '${Z}',
|
|
284
|
-
primaryKey: '${X}',
|
|
285
|
-
attributes: {
|
|
286
|
-
${J}
|
|
287
|
-
},
|
|
288
|
-
})
|
|
289
|
-
`}async function Q0(Z={}){let $=y.dialect||"postgres",Y=JZ(),X=Z.tables?.length?Z.tables:await iX(Y,$),J=[];for(let G of X){let U=await i6(Y,$,G);if(!U.length)continue;J.push({table:G,modelName:j0(G),primaryKey:U.find((H)=>H.isPrimaryKey)?.name??"id",columns:U,source:lX(G,U)})}return J}function _0(Z,$,Y){if(Y?.enumValues&&Y.enumValues.length>0)return"enum";let X=String(Z||"").toLowerCase().trim(),J=X.replace(/\(.*$/,"").replace(/\s+/g," ").trim();if(YZ($)&&/^tinyint\(1\)/.test(X))return"boolean";if(/^bool/.test(J))return"boolean";if(J==="int8"||J==="bigint"||J==="bigserial")return"bigint";if(/^(?:int|integer|smallint|mediumint|serial|int2|int4|tinyint)/.test(J))return"integer";if(/^(?:varchar|character varying|nvarchar|nchar|char|character|bpchar)/.test(J)){let G=X.match(/\((\d+)\)/),U=G?Number(G[1]):void 0;if(YZ($))return"string";return U!==void 0&&U>255?"text":"string"}if(/text|clob/.test(J))return"text";if(J==="float8"||/^double/.test(J))return"double";if(/^(?:real|float4|float)/.test(J))return"float";if(/^(?:numeric|decimal|money)/.test(J))return"decimal";if(J==="date")return"date";if(J==="timestamptz"||/\bwith time zone\b/.test(X))return"timestamptz";if(/^(?:timestamp|datetime)/.test(J))return"datetime";if(/^time/.test(J))return"string";if(/json/.test(J))return"json";if(/^enum/.test(J))return"enum";return"string"}function l6(Z,$,Y){return _0(String($||Z||""),"mysql",{enumValues:Y})}function s6(Z){let $=String(Z||"").trim().match(/^varchar\((\d+)\)/i);if(!$)return;let Y=Number($[1]);return Number.isSafeInteger(Y)&&Y>0?Y:void 0}function E9(Z){let $=String(Z??"").toLowerCase().trim();if($==="cascade"||$==="restrict"||$==="set null")return $;return}async function o6(Z,$){let Y=await Z.unsafe(`PRAGMA table_info(${JSON.stringify($)})`),X=await Z.unsafe(`PRAGMA index_list(${JSON.stringify($)})`),J=await Z.unsafe(`PRAGMA foreign_key_list(${JSON.stringify($)})`),G=await Z.unsafe("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",[$]),U=String(G?.[0]?.sql??""),H=new Map;for(let Q of J)H.set(String(Q.from),{table:String(Q.table),column:String(Q.to??"id"),onDelete:E9(Q.on_delete),onUpdate:E9(Q.on_update)});let z=[],A=new Set;for(let Q of X){let L=String(Q.origin??""),O=String(Q.name??"");if(L==="pk"||O.startsWith("sqlite_autoindex_"))continue;let w=(await Z.unsafe(`PRAGMA index_info(${JSON.stringify(O)})`)).map((B)=>String(B.name)).filter(Boolean);if(w.length===0)continue;let K=Number(Q.unique)===1;if(K&&w.length===1)A.add(w[0]);z.push({name:O,columns:w,type:K?"unique":"index"})}let W=Y.map((Q)=>{let L=String(Q.name),O=r6(U,L),T=Number(Q.pk)>0,w=Q.dflt_value,K=w!==null&&w!==void 0;return{name:L,type:_0(String(Q.type??""),"sqlite",{enumValues:O}),isPrimaryKey:T,isUnique:A.has(L),isNullable:T?!1:Number(Q.notnull)===0,hasDefault:K,defaultValue:K?V0(w):void 0,enumValues:O,references:H.get(L)}});return{table:$,columns:W,indexes:z}}function r6(Z,$){if(!Z)return;let Y=new RegExp(`(?:"${$}"|\`${$}\`|\\b${$}\\b)\\s+IN\\s*\\(([^)]*)\\)`,"i"),X=Z.match(Y);if(!X)return;let J=X[1].split(",").map((G)=>G.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((G)=>G.length>0);return J.length>0?J:void 0}function V0(Z){if(typeof Z==="number"||typeof Z==="boolean")return Z;return String(Z)}async function sX(Z){let $=await Z.unsafe(`SELECT t.typname AS type_name, e.enumlabel AS label
|
|
290
|
-
FROM pg_type t
|
|
291
|
-
JOIN pg_enum e ON e.enumtypid = t.oid
|
|
292
|
-
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
293
|
-
WHERE n.nspname = 'public'
|
|
294
|
-
ORDER BY t.typname, e.enumsortorder`),Y=new Map;for(let X of $){let J=String(X.type_name),G=Y.get(J);if(G)G.push(String(X.label));else Y.set(J,[String(X.label)])}return Y}function t6(Z,$,Y){let X=Y.get($),J=_0(String(Z||$||""),"postgres",{enumValues:X});return X?{type:J,enumValues:X,enumTypeName:$}:{type:J}}async function a6(Z,$,Y){let X=Y??await sX(Z),J=await Z.unsafe(`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length,
|
|
295
|
-
(SELECT COUNT(*) FROM information_schema.table_constraints tc
|
|
296
|
-
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
|
|
297
|
-
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
|
|
298
|
-
FROM information_schema.columns c
|
|
299
|
-
WHERE c.table_name = $1 AND c.table_schema = 'public'
|
|
300
|
-
ORDER BY c.ordinal_position`,[$]),G=await Z.unsafe(`SELECT i.relname AS index_name, ix.indisunique AS is_unique, ix.indisprimary AS is_primary,
|
|
301
|
-
a.attname AS column_name, array_position(ix.indkey, a.attnum) AS ord,
|
|
302
|
-
pg_get_expr(ix.indpred, ix.indrelid) AS where_clause
|
|
303
|
-
FROM pg_class t
|
|
304
|
-
JOIN pg_index ix ON t.oid = ix.indrelid
|
|
305
|
-
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
306
|
-
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
|
|
307
|
-
WHERE t.relname = $1 AND t.relkind = 'r'
|
|
308
|
-
ORDER BY i.relname, ord`,[$]),U=await Z.unsafe(`SELECT kcu.column_name, ccu.table_name AS ref_table, ccu.column_name AS ref_column,
|
|
309
|
-
tc.constraint_name, rc.delete_rule, rc.update_rule
|
|
310
|
-
FROM information_schema.table_constraints tc
|
|
311
|
-
JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name
|
|
312
|
-
JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name
|
|
313
|
-
JOIN information_schema.referential_constraints rc ON rc.constraint_name = tc.constraint_name
|
|
314
|
-
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[$]),H=new Map,z=new Map;for(let L of U){let O=String(L.constraint_name);z.set(O,(z.get(O)??0)+1)}for(let L of U){let O=String(L.column_name),T=H.get(O),w=String(L.constraint_name),K=z.get(w)===1?[...new Set([...T?.constraintNames??[],w])]:T?.constraintNames;H.set(O,T?{...T,constraintNames:K}:{table:String(L.ref_table),column:String(L.ref_column??"id"),onDelete:E9(L.delete_rule),onUpdate:E9(L.update_rule),constraintNames:K})}let{indexes:A,uniqueColumns:W}=oX($,G.map((L)=>({indexName:String(L.index_name),isUnique:L.is_unique===!0||L.is_unique==="t",isPrimary:L.is_primary===!0||L.is_primary==="t",column:String(L.column_name),where:L.where_clause?String(L.where_clause):void 0}))),Q=J.map((L)=>{let O=String(L.column_name),T=Number(L.is_pk)>0,w=L.column_default==null?null:String(L.column_default),K=w!=null&&/nextval\(/i.test(w),B=w!=null&&!K;return{name:O,...t6(String(L.data_type??""),L.udt_name==null?"":String(L.udt_name),X),isPrimaryKey:T,isUnique:W.has(O),isNullable:T?!1:String(L.is_nullable).toUpperCase()==="YES",hasDefault:B,defaultValue:B?V0(w):void 0,references:H.get(O)}});return{table:$,columns:Q,indexes:A}}async function e6(Z,$){let Y=await Z.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
|
|
315
|
-
FROM information_schema.columns
|
|
316
|
-
WHERE table_name = ? AND table_schema = DATABASE()
|
|
317
|
-
ORDER BY ordinal_position`,[$]),X=await Z.unsafe(`SELECT index_name, non_unique, seq_in_index, column_name
|
|
318
|
-
FROM information_schema.statistics
|
|
319
|
-
WHERE table_name = ? AND table_schema = DATABASE()
|
|
320
|
-
ORDER BY index_name, seq_in_index`,[$]),J=await Z.unsafe(`SELECT kcu.column_name, kcu.referenced_table_name AS ref_table, kcu.referenced_column_name AS ref_column,
|
|
321
|
-
kcu.constraint_name, rc.delete_rule, rc.update_rule
|
|
322
|
-
FROM information_schema.key_column_usage kcu
|
|
323
|
-
JOIN information_schema.referential_constraints rc
|
|
324
|
-
ON rc.constraint_name = kcu.constraint_name AND rc.constraint_schema = kcu.table_schema
|
|
325
|
-
WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[$]),G=new Map,U=new Map;for(let W of J){let Q=String(W.constraint_name??W.CONSTRAINT_NAME);U.set(Q,(U.get(Q)??0)+1)}for(let W of J){let Q=String(W.column_name??W.COLUMN_NAME),L=G.get(Q),O=String(W.constraint_name??W.CONSTRAINT_NAME),T=U.get(O)===1?[...new Set([...L?.constraintNames??[],O])]:L?.constraintNames;G.set(Q,L?{...L,constraintNames:T}:{table:String(W.ref_table??W.REF_TABLE),column:String(W.ref_column??W.REF_COLUMN??"id"),onDelete:E9(W.delete_rule??W.DELETE_RULE),onUpdate:E9(W.update_rule??W.UPDATE_RULE),constraintNames:T})}let{indexes:H,uniqueColumns:z}=oX($,X.map((W)=>({indexName:String(W.index_name??W.INDEX_NAME),isUnique:Number(W.non_unique??W.NON_UNIQUE)===0,isPrimary:String(W.index_name??W.INDEX_NAME).toUpperCase()==="PRIMARY",column:String(W.column_name??W.COLUMN_NAME)}))),A=Y.map((W)=>{let Q=String(W.column_name??W.COLUMN_NAME),L=String(W.column_type??W.COLUMN_TYPE??""),O=ZU(L),w=String(W.column_key??W.COLUMN_KEY??"").toUpperCase()==="PRI",K=W.column_default??W.COLUMN_DEFAULT,B=K!=null;return{name:Q,type:l6(W.data_type??W.DATA_TYPE,L,O),isPrimaryKey:w,isUnique:z.has(Q),isNullable:w?!1:String(W.is_nullable??W.IS_NULLABLE).toUpperCase()==="YES",hasDefault:B,defaultValue:B?V0(K):void 0,enumValues:O,maxLength:s6(L),references:G.get(Q)}});return{table:$,columns:A,indexes:H}}function ZU(Z){let $=Z.match(/^enum\((.*)\)$/i);if(!$)return;return $[1].split(",").map((Y)=>Y.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((Y)=>Y.length>0)}function oX(Z,$){let Y=new Map;for(let G of $){if(G.isPrimary)continue;let U=Y.get(G.indexName)??{isUnique:G.isUnique,isPrimary:G.isPrimary,columns:[],where:G.where};U.columns.push(G.column),Y.set(G.indexName,U)}let X=[],J=new Set;for(let[G,U]of Y){if(U.columns.length===0)continue;if(U.isUnique&&U.columns.length===1)J.add(U.columns[0]);X.push({name:G,columns:U.columns,type:U.isUnique?"unique":"index",where:U.where})}return{indexes:X,uniqueColumns:J}}async function rX(Z,$={}){let Y=Z||y.dialect||"postgres",X=JZ(),G=(($.tables?.length)?$.tables:await iX(X,Y)).filter((z)=>z!=="migrations"),U=Y==="postgres"?await sX(X):void 0,H=[];for(let z of G){let A;if(Y==="sqlite")A=await o6(X,z);else if(Y==="postgres")A=await a6(X,z,U);else A=await e6(X,z);if(A.columns.length>0)H.push(A)}return{dialect:Y,tables:H}}import{existsSync as K0,mkdirSync as $U,writeFileSync as YU}from"fs";import{dirname as tX,join as L0}from"path";import aX from"process";function XU(Z){let $=Z;while($!==tX($)){if(K0(L0($,"package.json")))return $;$=tX($)}return aX.cwd()}async function JU(Z,$={}){let Y=XU(aX.cwd()),X=$.dir||L0(Y,"app/Models");if(!K0(X))$U(X,{recursive:!0}),console.log(`-- Created models directory: ${X}`);let J=Z.charAt(0).toUpperCase()+Z.slice(1),G=$.table||`${Z.toLowerCase()}s`,U=`${J}.ts`,H=L0(X,U);if(K0(H))throw console.error(`-- Model already exists: ${H}`),Error(`Model already exists: ${H}`);let A=$.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
|
|
326
|
-
updated_at: { validation: { rule: v.date() } },`:"",W=`import { v } from '@stacksjs/ts-validation'
|
|
327
|
-
import { defineModel } from 'bun-query-builder'
|
|
328
|
-
|
|
329
|
-
const model = defineModel({
|
|
330
|
-
name: '${J}',
|
|
331
|
-
table: '${G}',
|
|
332
|
-
primaryKey: 'id',
|
|
333
|
-
attributes: {
|
|
334
|
-
id: { validation: { rule: v.integer() } },
|
|
335
|
-
${A}
|
|
336
|
-
// Add your model attributes here
|
|
337
|
-
// Example:
|
|
338
|
-
// name: { validation: { rule: v.string() } },
|
|
339
|
-
// email: { unique: true, validation: { rule: v.string().email() } },
|
|
340
|
-
// age: { default: 0, validation: { rule: v.number().min(0) } },
|
|
341
|
-
},
|
|
342
|
-
})
|
|
343
|
-
|
|
344
|
-
export default model
|
|
345
|
-
`;YU(H,W),console.log(`-- \u2713 Created model: ${H}`),console.log(`-- Table: ${G}`)}async function GU(Z,$={}){return F0(Z,$)}qZ();import{existsSync as Y1,readFileSync as HU,unlinkSync as AU}from"fs";import{join as WU}from"path";import{existsSync as UU}from"fs";import{dirname as eX,isAbsolute as zU,join as $1}from"path";import Z1 from"process";function B0(Z=Z1.cwd()){let $=Z;while($!==eX($)){if(UU($1($,"package.json")))return $;$=eX($)}return Z1.cwd()}function T8(Z,$="database/migrations"){let Y=$||"database/migrations";return zU(Y)?Y:$1(Z??B0(),Y)}function jU(Z){let $=[],Y="",X=null;for(let J=0;J<Z.length;J++){let G=Z[J];if(X){if(Y+=G,G===X)if(Z[J+1]===X)Y+=Z[J+1],J++;else X=null;continue}if(G==="'"||G==='"'||G==="`"){X=G,Y+=G;continue}if(G==="-"&&Z[J+1]==="-"){let U=Z.indexOf(`
|
|
346
|
-
`,J);J=U===-1?Z.length:U;continue}if(G==="/"&&Z[J+1]==="*"){let U=Z.indexOf("*/",J+2);J=U===-1?Z.length:U+1;continue}if(G===";"){if(Y.trim())$.push(Y.trim());Y="";continue}Y+=G}if(Y.trim())$.push(Y.trim());return $}function QU(Z,$=y.dialect){let Y=(G)=>YZ($)?`\`${G}\``:`"${G}"`,X=[],J=[];for(let G of jU(Z)){let U;if(U=/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?/i.exec(G))X.push(`DROP TABLE IF EXISTS ${Y(U[1])}`);else if(U=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+CONSTRAINT\s+["`']?(\w+)["`']?([\s\S]*)$/i.exec(G))if($==="sqlite")J.push(G);else if(YZ($)&&/\bFOREIGN\s+KEY\b/i.test(U[3]??""))X.push(`ALTER TABLE ${Y(U[1])} DROP FOREIGN KEY ${Y(U[2])}`);else X.push(`ALTER TABLE ${Y(U[1])} DROP CONSTRAINT ${Y(U[2])}`);else if(U=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+(?:COLUMN\s+["`']?(\w+)["`']?|["`'](\w+)["`']|(\w+))/i.exec(G)){let H=U[2]??U[3]??U[4];if(U[4]&&/^(?:PRIMARY|UNIQUE|INDEX|KEY|FOREIGN|CHECK|FULLTEXT|SPATIAL)$/i.test(U[4]))J.push(G);else X.push(`ALTER TABLE ${Y(U[1])} DROP COLUMN ${Y(H)}`)}else if(U=/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?(?:\s+ON\s+["`']?(\w+)["`']?)?/i.exec(G))X.push(YZ($)&&U[2]?`DROP INDEX ${Y(U[1])} ON ${Y(U[2])}`:`DROP INDEX IF EXISTS ${Y(U[1])}`);else J.push(G)}return{down:X.reverse(),skipped:J}}async function _U(Z={}){let $=Z.steps||1,Y=Z.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${$}`),console.log();try{let X=JZ(),J=[];try{J=await X.unsafe(`
|
|
347
|
-
SELECT migration, executed_at
|
|
348
|
-
FROM migrations
|
|
349
|
-
ORDER BY executed_at DESC, migration DESC
|
|
350
|
-
`)}catch(z){console.log("-- Migrations table not found. Nothing to rollback.",z);return}if(J.length===0){console.log("-- No migrations to rollback");return}let G=J.slice(0,$);console.log(`-- Found ${J.length} executed migrations`),console.log(`-- Rolling back ${G.length} migration(s):`),console.log();for(let z of G)console.log(` - ${z.migration}`);console.log();let U=T8(void 0,y.migrationDir),H=!1;for(let z of G)try{let A=WU(U,z.migration);if(Y&&Y1(A)){let Q=HU(A,"utf8"),{down:L,skipped:O}=QU(Q);for(let T of L)await X.unsafe(T),console.log(`-- \u21A9 ${T}`),H=!0;if(O.length>0)console.log(`-- \u26A0\uFE0F ${O.length} statement(s) in ${z.migration} could not be auto-reversed (data/complex DDL) \u2014 reverse manually.`)}let W=`DELETE FROM migrations WHERE migration = ${e(1)}`;if(await X.unsafe(W,[z.migration]),console.log(`-- \u2713 Removed migration record: ${z.migration}`),Z.deleteFiles&&Y1(A))AU(A),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${z.migration}`)}catch(A){throw console.error(`-- \u2717 Failed to rollback migration ${z.migration}:`,A),A}if(console.log(),Y)console.log(H?"-- \u2713 Reverse DDL executed for the rolled-back migration(s).":"-- \u26A0\uFE0F No reversible DDL found; only migration records were removed.");else console.log("-- \u26A0\uFE0F reverseSchema disabled: only migration records were removed.")}catch(X){throw console.error("-- Rollback failed:",X),X}}qZ();import{existsSync as VU,readdirSync as KU}from"fs";async function X1(){let Z=y.dialect||"postgres",$=B8(Z),Y=T8(void 0,y.migrationDir);if(console.log("-- Migration Status"),console.log(`-- Dialect: ${Z}`),console.log(`-- SQL directory: ${Y}`),console.log(),!VU(Y))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let J=KU(Y).filter((G)=>G.endsWith(".sql")).sort();if(J.length===0)return console.log("-- No migration files found"),[];try{let G=JZ(),U=[];try{U=await G.unsafe($.getExecutedMigrationsQuery())}catch(Q){console.log("-- Migrations table not found. All migrations are pending.",Q),console.log()}let H=new Map(U.map((Q)=>[Q.migration,Q.executed_at])),z=J.map((Q)=>({file:Q,status:H.has(Q)?"executed":"pending",executedAt:H.get(Q)})),A=z.filter((Q)=>Q.status==="executed"),W=z.filter((Q)=>Q.status==="pending");if(console.log(`-- Total migrations: ${J.length}`),console.log(`-- Executed: ${A.length}`),console.log(`-- Pending: ${W.length}`),console.log(),A.length>0){console.log("\u2713 Executed Migrations:");for(let Q of A)console.log(` - ${Q.file} ${Q.executedAt?`(${new Date(Q.executedAt).toLocaleString()})`:""}`);console.log()}if(W.length>0){console.log("\u25CB Pending Migrations:");for(let Q of W)console.log(` - ${Q.file}`);console.log()}return z}catch(G){throw console.error("-- Failed to get migration status:",G),G}}async function LU(){return X1()}import{readdirSync as FU}from"fs";import{extname as R0,join as J1}from"path";import BU from"process";async function G1(Z,$={}){let Y=$.dir||J1(BU.cwd(),"app/Models");try{let X=FU(Y),J=X.find((W)=>{return W.replace(R0(W),"").toLowerCase()===Z.toLowerCase()});if(!J){console.error(`Model "${Z}" not found in ${Y}`),console.log(`Available models: ${X.filter((W)=>[".ts",".js"].includes(R0(W))).map((W)=>W.replace(R0(W),"")).join(", ")}`);return}let U=await import(J1(Y,J)),H=U.default||U[Object.keys(U)[0]];if(!H||!H.name){console.error(`Invalid model file: ${J}`);return}let z={name:H.name,table:H.table||`${H.name.toLowerCase()}s`,primaryKey:H.primaryKey||"id",attributes:H.attributes||{},relations:H.relations,scopes:H.scopes,indexes:H.indexes,timestamps:H.timestamps!==!1,softDeletes:H.softDeletes===!0},A=[];if(H.beforeCreate)A.push("beforeCreate");if(H.afterCreate)A.push("afterCreate");if(H.beforeUpdate)A.push("beforeUpdate");if(H.afterUpdate)A.push("afterUpdate");if(H.beforeDelete)A.push("beforeDelete");if(H.afterDelete)A.push("afterDelete");if(A.length>0)z.hooks=A;if($.json)return console.log(JSON.stringify(z,null,2)),z;console.log(`
|
|
351
|
-
\uD83D\uDCE6 Model: ${z.name}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Table: ${z.table}`),console.log(`Primary Key: ${z.primaryKey}`),console.log(`Timestamps: ${z.timestamps?"\u2713":"\u2717"}`),console.log(`Soft Deletes: ${z.softDeletes?"\u2713":"\u2717"}`),console.log(`
|
|
352
|
-
\uD83D\uDCCB Attributes (${Object.keys(z.attributes).length}):`);for(let[W,Q]of Object.entries(z.attributes)){let L=Q.type||"string",O=Q.required?"(required)":"",T=Q.unique?"(unique)":"",w=Q.default!==void 0?`= ${JSON.stringify(Q.default)}`:"";console.log(` \u2022 ${W}: ${L} ${O} ${T} ${w}`.trim())}if(z.relations&&Object.keys(z.relations).length>0){console.log(`
|
|
353
|
-
\uD83D\uDD17 Relations (${Object.keys(z.relations).length}):`);for(let[W,Q]of Object.entries(z.relations)){let L=Q.type||"unknown",O=Q.model||Q.table||"unknown";console.log(` \u2022 ${W}: ${L} \u2192 ${O}`)}}if(z.scopes&&Object.keys(z.scopes).length>0){console.log(`
|
|
354
|
-
\uD83D\uDD0D Scopes (${Object.keys(z.scopes).length}):`);for(let W of Object.keys(z.scopes))console.log(` \u2022 ${W}()`)}if(z.hooks&&z.hooks.length>0){console.log(`
|
|
355
|
-
\uD83E\uDE9D Hooks (${z.hooks.length}):`);for(let W of z.hooks)console.log(` \u2022 ${W}`)}if(z.indexes&&z.indexes.length>0){console.log(`
|
|
356
|
-
\uD83D\uDCC7 Indexes (${z.indexes.length}):`);for(let W of z.indexes){let Q=Array.isArray(W.columns)?W.columns.join(", "):W.columns,L=W.unique?"(unique)":"";console.log(` \u2022 ${W.name||"unnamed"}: [${Q}] ${L}`.trim())}}return console.log(),z}catch(X){throw console.error(`Error loading model "${Z}":`,X.message),X}}async function RU(){let $=await JZ().ping();return console.log($?"OK":"NOT READY"),$}g8();import{readdirSync as OU,readFileSync as U1,statSync as EU}from"fs";import{extname as z1,join as DU}from"path";async function H1(Z,$={}){let Y=[];try{let X=EU(Z),J=[];if(X.isDirectory())J=OU(Z).filter((z)=>z1(z)===".sql").map((z)=>DU(Z,z));else if(X.isFile()&&z1(Z)===".sql")J=[Z];else return console.error("Path must be a .sql file or directory containing .sql files"),Y;if(J.length===0)return console.log("No .sql files found"),Y;if($.verbose)console.log(`Analyzing ${J.length} SQL file(s)...
|
|
357
|
-
`);for(let H of J)try{let z=U1(H,"utf8").trim();if(!z){if($.verbose)console.log(`\u2298 ${H}: empty file`);continue}if($.verbose)console.log(`\uD83D\uDCC4 ${H}`),console.log(` Query: ${z.substring(0,60)}${z.length>60?"...":""}`);let A=await $Z`EXPLAIN ${$Z.unsafe(z)}`;if(Y.push({file:H,query:z,plan:Array.isArray(A)?A:[A]}),$.verbose&&!$.json){if(console.log(" Plan:"),Array.isArray(A))for(let W of A)if(typeof W==="string")console.log(` ${W}`);else if(W["QUERY PLAN"])console.log(` ${W["QUERY PLAN"]}`);else if(W.plan)console.log(` ${JSON.stringify(W.plan)}`);else console.log(` ${JSON.stringify(W)}`);console.log()}}catch(z){if(Y.push({file:H,query:U1(H,"utf8").trim(),plan:[],error:z.message}),$.verbose)console.log(` \u2717 Error: ${z.message}
|
|
358
|
-
`)}let G=Y.filter((H)=>!H.error).length,U=Y.filter((H)=>H.error).length;if($.verbose)console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Summary: ${G} successful, ${U} failed`);if($.json)console.log(JSON.stringify(Y,null,2));return Y}catch(X){throw console.error("Error explaining queries:",X.message),X}}import{writeFileSync as IU}from"fs";import{join as MU}from"path";import wU from"process";async function A1(Z={}){let $=Z.dir||MU(wU.cwd(),"app/Models"),Y=Z.format||"mermaid";try{let X=await Q8({modelsDir:$});if(!X||Object.keys(X).length===0)return console.error("No models found"),"";let J="";if(Y==="mermaid")J=CU(X);else if(Y==="dot")J=SU(X);else return console.error(`Unsupported format: ${Y}`),"";if(Z.output)IU(Z.output,J,"utf8"),console.log(`\u2713 Diagram written to: ${Z.output}`);else console.log(J);return J}catch(X){throw console.error("Error generating diagram:",X.message),X}}function CU(Z){let $=["erDiagram"];for(let[Y,X]of Object.entries(Z)){let J=X.table||`${Y.toLowerCase()}s`,G=X.attributes||{};$.push(` ${J} {`);for(let[U,H]of Object.entries(G)){let z=H.type||"string",A=X.primaryKey===U?"PK":"",W=H.unique?"UK":"",Q=[A,W].filter(Boolean).join(","),L=Q?` "${Q}"`:"";$.push(` ${z} ${U}${L}`)}$.push(" }")}for(let[Y,X]of Object.entries(Z)){let J=X.table||`${Y.toLowerCase()}s`,G=X.relations||{};for(let[U,H]of Object.entries(G)){let{type:z,model:A}=H,W=Z[A]?.table||`${A?.toLowerCase()}s`||"unknown",Q="";if(z==="hasOne")Q="||--||";else if(z==="hasMany")Q="||--o{";else if(z==="belongsTo")Q="}o--||";else if(z==="belongsToMany"||z==="manyToMany")Q="}o--o{";else Q="||--||";$.push(` ${J} ${Q} ${W} : "${U}"`)}}return $.join(`
|
|
359
|
-
`)}function SU(Z){let $=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[Y,X]of Object.entries(Z)){let J=X.table||`${Y.toLowerCase()}s`,G=X.attributes||{},U=[];for(let[z,A]of Object.entries(G)){let W=A.type||"string",Q=X.primaryKey===z?" (PK)":"",L=A.unique?" (UK)":"";U.push(`${z}: ${W}${Q}${L}`)}let H=`${U.join("\\l")}\\l`;$.push(` ${J} [label="{${J}|${H}}"];`)}$.push("");for(let[Y,X]of Object.entries(Z)){let J=X.table||`${Y.toLowerCase()}s`,G=X.relations||{};for(let[U,H]of Object.entries(G)){let{type:z,model:A}=H,W=Z[A]?.table||`${A?.toLowerCase()}s`||"unknown",Q="";if(z==="hasOne")Q="arrowhead=none, arrowtail=normal";else if(z==="hasMany")Q="arrowhead=crow, arrowtail=none";else if(z==="belongsTo")Q="arrowhead=normal, arrowtail=none";else if(z==="belongsToMany"||z==="manyToMany")Q="arrowhead=crow, arrowtail=crow";$.push(` ${J} -> ${W} [label="${U}", ${Q}];`)}}return $.push("}"),$.join(`
|
|
360
|
-
`)}import{existsSync as U7,mkdirSync as NU,readdirSync as PU,writeFileSync as TU}from"fs";import{dirname as W1,join as c8}from"path";import o9 from"process";function z7(Z){let $=Z;while($!==W1($)){if(U7(c8($,"package.json")))return $;$=W1($)}return o9.cwd()}async function j1(Z){if(!U7(Z))return console.log(`-- Seeders directory not found: ${Z}`),[];let Y=PU(Z).sort((J,G)=>J.localeCompare(G)).filter((J)=>(J.endsWith(".ts")||J.endsWith(".js"))&&J!=="index.ts"&&J!=="index.js"),X=[];for(let J of Y){let G=c8(Z,J);try{let U=await import(G),H=U.default||U[Object.keys(U)[0]];if(H&&typeof H==="function"){let z=new H;if(z&&typeof z.run==="function")X.push({name:J.replace(/\.(ts|js)$/,""),className:String(H.name||""),instance:z})}}catch(U){console.error(`-- Failed to load seeder ${J}:`,U)}}return X.sort((J,G)=>J.instance.order-G.instance.order),X}async function Q1(Z={}){let $=z7(o9.cwd()),Y=Z.seedersDir||c8($,"database/seeders"),X=Z.verbose??!0;if(X)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${Y}`);let J=await j1(Y);if(J.length===0){console.log("-- No seeders found");return}if(X)console.log(`-- Found ${J.length} seeder(s)`);let G=JZ();for(let{name:U,instance:H}of J)try{if(X)console.log(`-- Seeding: ${U}`);if(await H.run(G),X)console.log(`-- \u2713 Seeded: ${U}`)}catch(z){throw console.error(`-- \u2717 Failed to seed ${U}:`,z),z}if(X)console.log("-- All seeders completed successfully")}async function qU(Z,$={}){let Y=z7(o9.cwd()),X=c8(Y,"database/seeders"),J=$.verbose??!0;if(J)console.log(`-- Running seeder: ${Z}`);let G=await j1(X),U=G.find((z)=>z.className===Z)??G.find((z)=>z.name===Z);if(!U){let z=G.map((A)=>A.className||A.name).join(", ")||"none";throw console.error(`-- Seeder not found: ${Z}. Available: ${z}`),Error(`Seeder not found: ${Z}. Available: ${z}`)}let H=JZ();try{if(await U.instance.run(H),J)console.log(`-- \u2713 Seeder completed: ${Z}`)}catch(z){throw console.error(`-- \u2717 Seeder failed: ${Z}`,z),z}}async function kU(Z){let $=z7(o9.cwd()),Y=c8($,"database/seeders");if(!U7(Y))NU(Y,{recursive:!0}),console.log(`-- Created seeders directory: ${Y}`);let J=`${Z.replace(/Seeder$/i,"")}Seeder`,G=`${J}.ts`,U=c8(Y,G);if(U7(U))throw console.error(`-- Seeder already exists: ${U}`),Error(`Seeder already exists: ${U}`);let H=`import type { QueryBuilder } from 'bun-query-builder'
|
|
361
|
-
import { Seeder } from 'bun-query-builder'
|
|
362
|
-
import { faker } from '@stacksjs/ts-faker'
|
|
363
|
-
|
|
364
|
-
export default class ${J} extends Seeder {
|
|
365
|
-
/**
|
|
366
|
-
* Run the database seeds.
|
|
367
|
-
*/
|
|
368
|
-
async run(qb: QueryBuilder): Promise<void> {
|
|
369
|
-
console.log('Seeding: ${J}')
|
|
370
|
-
|
|
371
|
-
// Example: Create 10 records with faker
|
|
372
|
-
const records = Array.from({ length: 10 }, () => ({
|
|
373
|
-
name: faker.person.fullName(),
|
|
374
|
-
email: faker.internet.email().toLowerCase(),
|
|
375
|
-
age: faker.number.int({ min: 18, max: 80 }),
|
|
376
|
-
created_at: faker.date.past(),
|
|
377
|
-
updated_at: new Date(),
|
|
378
|
-
}))
|
|
379
|
-
|
|
380
|
-
// Option 1: Kysely-style API
|
|
381
|
-
await qb.insertInto('table_name').values(records).execute()
|
|
382
|
-
|
|
383
|
-
// Option 2: Laravel-style API (equivalent)
|
|
384
|
-
// await qb.table('table_name').insert(records).execute()
|
|
385
|
-
|
|
386
|
-
console.log(\`\u2713 Seeded \${records.length} records\`)
|
|
387
|
-
|
|
388
|
-
// For large datasets, use batch inserts:
|
|
389
|
-
// const batchSize = 100
|
|
390
|
-
// for (let i = 0; i < records.length; i += batchSize) {
|
|
391
|
-
// const batch = records.slice(i, i + batchSize)
|
|
392
|
-
// await qb.insertInto('table_name').values(batch).execute()
|
|
393
|
-
// // Or: await qb.table('table_name').insert(batch).execute()
|
|
394
|
-
// }
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
/**
|
|
398
|
-
* Specify the order in which this seeder should run.
|
|
399
|
-
* Lower numbers run first. Default is 100.
|
|
400
|
-
*/
|
|
401
|
-
get order(): number {
|
|
402
|
-
return 100
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
`;TU(U,H),console.log(`-- \u2713 Created seeder: ${U}`)}async function xU(Z={}){let $=z7(o9.cwd()),Y=Z.modelsDir||c8($,"app/Models"),X=Z.seedersDir||c8($,"database/seeders"),J=Z.verbose??!0;try{let{resetDatabase:G,generateMigration:U,executeMigration:H}=await import("./chunk-rgnkzv8c.js");if(J)console.log("-- Refreshing database...");if(await G(Y),J)console.log("-- Running migrations...");if(await U(Y,{full:!0}),await H(),J)console.log("-- Running seeders...");if(await Q1({seedersDir:X,verbose:J}),J)console.log("-- \u2713 Database refreshed successfully")}catch(G){throw console.error("-- \u2717 Database refresh failed:",G),G}}qZ();function vU(Z,$,Y={}){let X=Q8({modelsDir:Z}),J=G7(X);if(y.debug)y.debug.captureText=!0;let G=JZ({schema:J}),U=G.selectFrom($).limit(Number(Y.limit||10)).toText?.()??"";return console.log(U||"[query]"),{sql:U,qb:G,schema:J}}async function yU(Z,$={}){let Y=JZ(),X=$.params?JSON.parse($.params):void 0,J=await Y.unsafe(Z,X);return console.log(JSON.stringify(J)),J}qZ();import{existsSync as hU}from"fs";import{dirname as _1,join as V1}from"path";import K1 from"process";function bU(Z){let $=Z;while($!==_1($)){if(hU(V1($,"package.json")))return $;$=_1($)}return K1.cwd()}async function L1(Z){if(!Z)Z=V1(bU(K1.cwd()),"app/Models");let $=y.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${Z}`),console.log(`-- Dialect: ${$}`),console.log();let Y=[];try{let X=await Q8({modelsDir:Z}),J=r9(X,{dialect:$}),G=JZ(),U=[];if($==="sqlite")U=(await G.unsafe(`
|
|
406
|
-
SELECT name FROM sqlite_master
|
|
407
|
-
WHERE type = 'table'
|
|
408
|
-
AND name NOT LIKE 'sqlite_%'
|
|
409
|
-
AND name != 'migrations'
|
|
410
|
-
`)).map((W)=>W.name);else if($==="postgres")U=(await G.unsafe(`
|
|
411
|
-
SELECT table_name
|
|
412
|
-
FROM information_schema.tables
|
|
413
|
-
WHERE table_schema = 'public'
|
|
414
|
-
AND table_type = 'BASE TABLE'
|
|
415
|
-
AND table_name != 'migrations'
|
|
416
|
-
`)).map((W)=>W.table_name);else if(YZ($))U=(await G.unsafe(`
|
|
417
|
-
SELECT table_name
|
|
418
|
-
FROM information_schema.tables
|
|
419
|
-
WHERE table_schema = DATABASE()
|
|
420
|
-
AND table_type = 'BASE TABLE'
|
|
421
|
-
AND table_name != 'migrations'
|
|
422
|
-
`)).map((W)=>W.table_name);let H=J.tables.map((A)=>A.table);for(let A of H)if(!U.includes(A))Y.push({type:"missing_table",severity:"error",table:A,message:`Table '${A}' defined in models but not found in database`});for(let A of U)if(!H.includes(A))Y.push({type:"extra_table",severity:"warning",table:A,message:`Table '${A}' exists in database but not defined in models`});for(let A of J.tables){if(!U.includes(A.table))continue;let W=[];if($==="sqlite")W=(await G.unsafe(`PRAGMA table_info(${A.table})`)).map((T)=>({name:T.name,type:T.type.toLowerCase()}));else if($==="postgres")W=(await G.unsafe(`
|
|
423
|
-
SELECT column_name, data_type
|
|
424
|
-
FROM information_schema.columns
|
|
425
|
-
WHERE table_name = $1
|
|
426
|
-
`,[A.table])).map((T)=>({name:T.column_name,type:T.data_type.toLowerCase()}));else if(YZ($))W=(await G.unsafe(`
|
|
427
|
-
SELECT column_name, data_type
|
|
428
|
-
FROM information_schema.columns
|
|
429
|
-
WHERE table_name = ?
|
|
430
|
-
AND table_schema = DATABASE()
|
|
431
|
-
`,[A.table])).map((T)=>({name:T.column_name,type:T.data_type.toLowerCase()}));let Q=W.map((O)=>O.name),L=A.columns.map((O)=>O.name);for(let O of A.columns)if(!Q.includes(O.name))Y.push({type:"missing_column",severity:"error",table:A.table,column:O.name,expected:O.type,message:`Column '${A.table}.${O.name}' defined in model but not found in database`});for(let O of W)if(!L.includes(O.name))Y.push({type:"extra_column",severity:"warning",table:A.table,column:O.name,actual:O.type,message:`Column '${A.table}.${O.name}' exists in database but not defined in model`});for(let O of A.columns){let T=W.find((w)=>w.name===O.name);if(T){let w=(V)=>{return V.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim()},K=w(O.type),B=w(T.type);if(K!==B)Y.push({type:"type_mismatch",severity:"warning",table:A.table,column:O.name,expected:O.type,actual:T.type,message:`Column '${A.table}.${O.name}' type mismatch: expected '${O.type}', found '${T.type}'`})}}}let z=Y.filter((A)=>A.severity==="error").length===0;if(z&&Y.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${Y.length} issue(s)`),console.log();let A=Y.filter((Q)=>Q.severity==="error"),W=Y.filter((Q)=>Q.severity==="warning");if(A.length>0){console.log(`\u2717 Errors (${A.length}):`);for(let Q of A)console.log(` - ${Q.message}`);console.log()}if(W.length>0){console.log(`\u26A0 Warnings (${W.length}):`);for(let Q of W)console.log(` - ${Q.message}`);console.log()}if(!z)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:z,issues:Y}}catch(X){throw console.error("-- Schema validation failed:",X),X}}async function fU(Z){return L1(Z)}async function gU(Z={}){let $=Number(Z.attempts||10),Y=Number(Z.delay||100),X=JZ();try{return await X.waitForReady({attempts:$,delayMs:Y}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}h1();e9();qZ();class i8{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(Z){this.driver=a8(Z.config),this.client=Z.client,this.tableName=Z.config.tableName??""}table(Z){return this.tableName=Z,this}index(Z){return this.indexName=Z,this}entity(Z){return this.entityType=Z,this}whereKey(Z,$,Y){return this.keyConditions.push({attribute:Z,operator:$,value:Y}),this}wherePartitionKey(Z,$){return this.whereKey(Z,"=",$)}whereSortKey(Z,$){return this.whereKey(Z,"=",$)}whereSortKeyBeginsWith(Z,$){return this.keyConditions.push({attribute:Z,operator:"begins_with",value:$}),this}whereSortKeyBetween(Z,$,Y){return this.keyConditions.push({attribute:Z,operator:"BETWEEN",values:[$,Y]}),this}where(Z,$,Y){return this.filterConditions.push({attribute:Z,operator:$,value:Y}),this}whereEquals(Z,$){return this.where(Z,"=",$)}whereLessThan(Z,$){return this.where(Z,"<",$)}whereLessThanOrEqual(Z,$){return this.where(Z,"<=",$)}whereGreaterThan(Z,$){return this.where(Z,">",$)}whereGreaterThanOrEqual(Z,$){return this.where(Z,">=",$)}whereBetween(Z,$,Y){return this.filterConditions.push({attribute:Z,operator:"BETWEEN",values:[$,Y]}),this}whereBeginsWith(Z,$){return this.filterConditions.push({attribute:Z,operator:"begins_with",value:$}),this}whereContains(Z,$){return this.where(Z,"contains",$)}whereExists(Z){return this.where(Z,"attribute_exists")}whereNotExists(Z){return this.where(Z,"attribute_not_exists")}whereIn(Z,$){return this.filterConditions.push({attribute:Z,operator:"IN",values:$}),this}select(...Z){return this.projectionAttrs.push(...Z),this}limit(Z){return this.limitValue=Z,this}ascending(){return this.scanForward=!0,this}descending(){return this.scanForward=!1,this}consistentRead(Z=!0){return this.consistentReadValue=Z,this}startFrom(Z){return this.startKey=Z,this}buildQueryParams(){return this.driver.buildQueryParams({tableName:this.tableName,indexName:this.indexName,keyConditions:this.keyConditions,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,scanIndexForward:this.scanForward,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}buildScanParams(){return this.driver.buildScanParams({tableName:this.tableName,indexName:this.indexName,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}toQueryRequest(){let Z=this.buildQueryParams(),$={TableName:Z.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if(Z.indexName)$.IndexName=Z.indexName;let Y=0;if(Z.keyConditions.length>0){let X=[];for(let J of Z.keyConditions){let G=`#key${Y}`;if($.ExpressionAttributeNames[G]=J.attribute,J.operator==="begins_with"){let U=`:keyval${Y}`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.value}).v,X.push(`begins_with(${G}, ${U})`)}else if(J.operator==="BETWEEN"){let U=`:keyval${Y}a`,H=`:keyval${Y}b`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.values?.[0]}).v,$.ExpressionAttributeValues[H]=this.driver.marshall({v:J.values?.[1]}).v,X.push(`${G} BETWEEN ${U} AND ${H}`)}else{let U=`:keyval${Y}`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.value}).v,X.push(`${G} ${J.operator} ${U}`)}Y++}$.KeyConditionExpression=X.join(" AND ")}if(Z.filterConditions&&Z.filterConditions.length>0){let X=[];for(let J of Z.filterConditions){let G=`#flt${Y}`;if($.ExpressionAttributeNames[G]=J.attribute,J.operator==="attribute_exists")X.push(`attribute_exists(${G})`);else if(J.operator==="attribute_not_exists")X.push(`attribute_not_exists(${G})`);else if(J.operator==="begins_with"||J.operator==="contains"){let U=`:fltval${Y}`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.value}).v,X.push(`${J.operator}(${G}, ${U})`)}else if(J.operator==="BETWEEN"){let U=`:fltval${Y}a`,H=`:fltval${Y}b`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.values?.[0]}).v,$.ExpressionAttributeValues[H]=this.driver.marshall({v:J.values?.[1]}).v,X.push(`${G} BETWEEN ${U} AND ${H}`)}else if(J.operator==="IN"){let U=(J.values??[]).map((H,z)=>`:fltval${Y}_${z}`);J.values?.forEach((H,z)=>{$.ExpressionAttributeValues[`:fltval${Y}_${z}`]=this.driver.marshall({v:H}).v}),X.push(`${G} IN (${U.join(", ")})`)}else{let U=`:fltval${Y}`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.value}).v,X.push(`${G} ${J.operator} ${U}`)}Y++}$.FilterExpression=X.join(" AND ")}if(Z.projectionAttributes&&Z.projectionAttributes.length>0){let X=[];for(let J of Z.projectionAttributes){let G=`#proj${Y}`;$.ExpressionAttributeNames[G]=J,X.push(G),Y++}$.ProjectionExpression=X.join(", ")}if(Z.limit!==void 0)$.Limit=Z.limit;if(Z.scanIndexForward!==void 0)$.ScanIndexForward=Z.scanIndexForward;if(Z.exclusiveStartKey)$.ExclusiveStartKey=this.driver.marshall(Z.exclusiveStartKey);if(Z.consistentRead)$.ConsistentRead=Z.consistentRead;if(Object.keys($.ExpressionAttributeNames).length===0)delete $.ExpressionAttributeNames;if(Object.keys($.ExpressionAttributeValues).length===0)delete $.ExpressionAttributeValues;return $}toScanRequest(){let Z=this.buildScanParams(),$={TableName:Z.tableName};if(Z.indexName)$.IndexName=Z.indexName;if(Z.filterConditions&&Z.filterConditions.length>0){let{expression:Y,expressionAttributeNames:X,expressionAttributeValues:J}=this.driver.buildFilterExpression(Z.filterConditions);$.FilterExpression=Y,$.ExpressionAttributeNames=X,$.ExpressionAttributeValues=J}if(Z.projectionAttributes&&Z.projectionAttributes.length>0){let{expression:Y,expressionAttributeNames:X}=this.driver.buildProjectionExpression(Z.projectionAttributes);$.ProjectionExpression=Y,$.ExpressionAttributeNames={...$.ExpressionAttributeNames,...X}}if(Z.limit!==void 0)$.Limit=Z.limit;if(Z.exclusiveStartKey)$.ExclusiveStartKey=this.driver.marshall(Z.exclusiveStartKey);if(Z.consistentRead)$.ConsistentRead=Z.consistentRead;return $}async query(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toQueryRequest() to get the request params.");let Z=this.toQueryRequest(),$=await this.client.query(Z);return{items:$.Items?.map((Y)=>this.driver.unmarshall(Y)),count:$.Count,scannedCount:$.ScannedCount,lastEvaluatedKey:$.LastEvaluatedKey?this.driver.unmarshall($.LastEvaluatedKey):void 0,consumedCapacity:$.ConsumedCapacity}}async scan(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toScanRequest() to get the request params.");let Z=this.toScanRequest(),$=await this.client.scan(Z);return{items:$.Items?.map((Y)=>this.driver.unmarshall(Y)),count:$.Count,scannedCount:$.ScannedCount,lastEvaluatedKey:$.LastEvaluatedKey?this.driver.unmarshall($.LastEvaluatedKey):void 0,consumedCapacity:$.ConsumedCapacity}}async getAll(){let Z=[],$;do{if($)this.startFrom($);let Y=this.keyConditions.length>0?await this.query():await this.scan();if(Y.items)Z.push(...Y.items);$=Y.lastEvaluatedKey}while($);return Z}async first(){return this.limit(1),(this.keyConditions.length>0?await this.query():await this.scan()).items?.[0]}async count(){if(!this.client)throw Error("DynamoDB client not provided");let Z=this.keyConditions.length>0?this.toQueryRequest():this.toScanRequest();return Z.Select="COUNT",(this.keyConditions.length>0?await this.client.query(Z):await this.client.scan(Z)).Count??0}reset(){return this.indexName=void 0,this.entityType=void 0,this.keyConditions=[],this.filterConditions=[],this.projectionAttrs=[],this.limitValue=void 0,this.scanForward=!0,this.consistentReadValue=!1,this.startKey=void 0,this}}class O8{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(Z){this.driver=a8(Z.config),this.client=Z.client,this.tableName=Z.config.tableName??""}table(Z){return this.tableName=Z,this}key(Z){return this.keyData=Z,this}item(Z){return this.itemData=Z,this}set(Z,$){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[Z]=$,this}setMany(Z){if(!this.updateExpressions.set)this.updateExpressions.set={};return Object.assign(this.updateExpressions.set,Z),this}remove(Z){if(!this.updateExpressions.remove)this.updateExpressions.remove=[];return this.updateExpressions.remove.push(Z),this}add(Z,$){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[Z]=$,this}deleteFromSet(Z,$){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[Z]=$,this}condition(Z){return this.conditionExpr=Z,this}ifNotExists(Z="pk"){return this.conditionExpr=`attribute_not_exists(${Z})`,this}ifExists(Z="pk"){return this.conditionExpr=`attribute_exists(${Z})`,this}returnOld(){return this.returnValuesOption="ALL_OLD",this}returnNew(){return this.returnValuesOption="ALL_NEW",this}toPutRequest(){let Z={TableName:this.tableName,Item:this.driver.marshall(this.itemData)};if(this.conditionExpr)Z.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")Z.ReturnValues=this.returnValuesOption;return Z}toUpdateRequest(){let Z={TableName:this.tableName,Key:this.driver.marshall(this.keyData)},{expression:$,expressionAttributeNames:Y,expressionAttributeValues:X}=this.driver.buildUpdateExpression(this.updateExpressions);if($)Z.UpdateExpression=$,Z.ExpressionAttributeNames=Y,Z.ExpressionAttributeValues=X;if(this.conditionExpr)Z.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")Z.ReturnValues=this.returnValuesOption;return Z}toDeleteRequest(){let Z={TableName:this.tableName,Key:this.driver.marshall(this.keyData)};if(this.conditionExpr)Z.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")Z.ReturnValues=this.returnValuesOption;return Z}toGetRequest(){return{TableName:this.tableName,Key:this.driver.marshall(this.keyData)}}async put(){if(!this.client)throw Error("DynamoDB client not provided");let Z=this.toPutRequest(),$=await this.client.putItem(Z);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let Z=this.toUpdateRequest(),$=await this.client.updateItem(Z);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let Z=this.toDeleteRequest(),$=await this.client.deleteItem(Z);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let Z=this.toGetRequest(),$=await this.client.getItem(Z);if($.Item)return this.driver.unmarshall($.Item);return}}function A3(Z){return new i8(Z)}function W3(Z){return new O8(Z)}function j3(Z){let $=a8(Z.config);return{query:()=>new i8(Z),item:()=>new O8(Z),driver:$,registerEntity:(Y)=>$.registerEntity(Y),buildKey:(Y,X)=>$.buildPrimaryKey(Y,X)}}class c1{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor(Z){this.config=Z,this.pkAttribute=Z.pkAttribute??"pk",this.skAttribute=Z.skAttribute??"sk",this.typeAttribute=Z.typeAttribute??"_type";for(let $ of Z.entities)this.entities.set($.name,$)}getEntity(Z){return this.entities.get(Z)}registerEntity(Z){this.entities.set(Z.name,Z)}buildKey(Z,$){let Y=this.entities.get(Z);if(!Y)throw Error(`Entity not found: ${Z}`);let X=this.interpolatePattern(Y.pkPattern,$),J=this.interpolatePattern(Y.skPattern,$);return{pk:X,sk:J}}buildGSIKey(Z,$,Y){let X=this.entities.get(Z);if(!X)throw Error(`Entity not found: ${Z}`);let J=X.indexes?.find((H)=>H.name===$);if(!J)throw Error(`GSI not found: ${$} for entity ${Z}`);let G=this.interpolatePattern(J.pkPattern,Y),U=J.skPattern?this.interpolatePattern(J.skPattern,Y):void 0;return{pk:G,sk:U}}createItem(Z,$){let{pk:Y,sk:X}=this.buildKey(Z,$),J=this.entities.get(Z),G={[this.pkAttribute]:Y,[this.skAttribute]:X,[this.typeAttribute]:Z,...$};if(J.indexes)for(let U of J.indexes){let H=this.buildGSIKey(Z,U.name,$),z=this.config.indexes?.find((A)=>A.name===U.name);if(z){if(G[z.pkAttribute]=H.pk,z.skAttribute&&H.sk)G[z.skAttribute]=H.sk}}return G}parseEntityType(Z){if(Z[this.typeAttribute])return Z[this.typeAttribute];let $=Z[this.pkAttribute];if(!$)return;for(let[Y,X]of this.entities){let J=X.pkPattern.split("${")[0];if($.startsWith(J))return Y}return}parseItem(Z){let $=this.parseEntityType(Z);if(!$)return;let{[this.pkAttribute]:Y,[this.skAttribute]:X,[this.typeAttribute]:J,...G}=Z;return{type:$,data:G}}getEntityPrefix(Z){let $=this.entities.get(Z);if(!$)throw Error(`Entity not found: ${Z}`);return $.pkPattern.split("${")[0]}generateTableDefinition(){let Z=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],$=[];if(this.config.indexes)for(let Y of this.config.indexes){if(!Z.find((X)=>X.name===Y.pkAttribute))Z.push({name:Y.pkAttribute,type:"S"});if(Y.skAttribute&&!Z.find((X)=>X.name===Y.skAttribute))Z.push({name:Y.skAttribute,type:"S"});$.push({indexName:Y.name,keySchema:{partitionKey:Y.pkAttribute,sortKey:Y.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:Z,globalSecondaryIndexes:$.length>0?$:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern(Z,$){return Z.replace(/\$\{(\w+)\}/g,(Y,X)=>{if(!(X in $))throw Error(`Missing value for pattern key: ${X}`);return String($[X])})}}class u1{manager;entityName;options;constructor(Z,$,Y){this.manager=Z,this.entityName=$,this.options=Y}async create(Z){let $=this.manager.createItem(this.entityName,Z),Y=new O8(this.options).table(this.options.config.tableName).item($).ifNotExists("pk");if(this.options.client)await Y.put();return Z}async get(Z){let{pk:$,sk:Y}=this.manager.buildKey(this.entityName,Z),X=new O8(this.options).table(this.options.config.tableName).key({pk:$,sk:Y});if(!this.options.client)throw Error("DynamoDB client not provided");let J=await X.get();if(!J)return;return this.manager.parseItem(J)?.data}async update(Z,$){let{pk:Y,sk:X}=this.manager.buildKey(this.entityName,Z),J=new O8(this.options).table(this.options.config.tableName).key({pk:Y,sk:X}).setMany($).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let G=await J.update();if(!G)return;return this.manager.parseItem(G)?.data}async delete(Z){let{pk:$,sk:Y}=this.manager.buildKey(this.entityName,Z),X=new O8(this.options).table(this.options.config.tableName).key({pk:$,sk:Y});if(!this.options.client)throw Error("DynamoDB client not provided");return await X.delete(),!0}query(){return new n1(this.manager,this.entityName,this.options)}async findAll(){let Z=this.manager.typeAttribute??"_type",$=new i8(this.options).table(this.options.config.tableName).whereEquals(Z,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await $.getAll()).map((X)=>this.manager.parseItem(X)).filter((X)=>X!==void 0).map((X)=>X.data)}}class n1{manager;entityName;options;builder;pkValue;skConditions=[];constructor(Z,$,Y){this.manager=Z,this.entityName=$,this.options=Y,this.builder=new i8(Y).table(Y.config.tableName)}wherePartitionKey(Z){let{pk:$}=this.manager.buildKey(this.entityName,Z);this.pkValue=$;let Y=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(Y,$),this}whereSortKey(Z){let{sk:$}=this.manager.buildKey(this.entityName,Z),Y=this.manager.skAttribute??"sk";return this.builder.whereSortKey(Y,$),this}whereSortKeyBeginsWith(Z){let $=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith($,Z),this}useIndex(Z,$){let Y=this.manager.buildGSIKey(this.entityName,Z,$),X=this.manager.config.indexes?.find((J)=>J.name===Z);if(!X)throw Error(`GSI configuration not found: ${Z}`);return this.builder.index(Z),this.builder.wherePartitionKey(X.pkAttribute,Y.pk),this}where(Z,$,Y){return this.builder.where(Z,$,Y),this}select(...Z){return this.builder.select(...Z),this}limit(Z){return this.builder.limit(Z),this}descending(){return this.builder.descending(),this}async execute(){if(!this.options.client)throw Error("DynamoDB client not provided");return((await this.builder.query()).items??[]).map(($)=>this.manager.parseItem($)).filter(($)=>$!==void 0).map(($)=>$.data)}async first(){return this.limit(1),(await this.execute())[0]}}function i1(Z){return new c1(Z)}function l1(Z,$,Y){return new u1(Z,$,Y)}var V3={simpleEntity:(Z,$="id")=>({name:Z,pkPattern:`${Z.toUpperCase()}#\${${$}}`,skPattern:"METADATA",keyFields:[$]}),oneToMany:(Z,$,Y="id",X="id")=>({parent:{name:Z,pkPattern:`${Z.toUpperCase()}#\${${Y}}`,skPattern:"METADATA",keyFields:[Y]},child:{name:$,pkPattern:`${Z.toUpperCase()}#\${${Y}}`,skPattern:`${$.toUpperCase()}#\${${X}}`,keyFields:[Y,X]}}),manyToMany:(Z,$,Y="id",X="relatedId")=>({entity:{name:Z,pkPattern:`${Z.toUpperCase()}#\${${Y}}`,skPattern:"METADATA",keyFields:[Y]},relation:{name:$,pkPattern:`${Z.toUpperCase()}#\${${Y}}`,skPattern:`${$.toUpperCase()}#\${${X}}`,keyFields:[Y,X],indexes:[{name:"GSI1",pkPattern:`${Z.toUpperCase()}#\${${X}}`,skPattern:`${$.toUpperCase()}#\${${Y}}`}]}}),hierarchical:(Z,$="rootId",Y="path")=>({name:Z,pkPattern:`ROOT#\${${$}}`,skPattern:`PATH#\${${Y}}`,keyFields:[$,Y]})};function s1(Z,$){let Y={};for(let[X,J]of Object.entries(Z))if(J)Y[X]=J.replace(/\{([^}]+)\}/g,(G,U)=>{return $[U]!==void 0?String($[U]):`{${U}}`});return Y}async function J2(Z){return{models:new Map}}function L3(Z){return Z}function F3(Z){return Z}function B3(Z){return Z}function R3(Z){return Z}class o1{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor(Z){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...Z};let $={region:Z.region,endpoint:Z.endpoint,credentials:Z.credentials,tableName:Z.tableName};this.driver=a8($);let Y={tableName:Z.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=i1(Y),this.queryBuilderOptions={config:$}}setClient(Z){return this.queryBuilderOptions.client=Z,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let Z=await J2({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),$=[];for(let[,Y]of Z.models)this.registerParsedModel(Y),$.push(Y);return $}registerModel(Z){let $=this.parseWithTooling(Z);return this.registerParsedModel($)}registerParsedModel(Z){this.models.set(Z.name,Z);let $=this.toSingleTableEntity(Z);this.singleTableManager.registerEntity($);let Y=this.toEntityMapping(Z);return this.driver.registerEntity(Y),Z}registerModels(Z){return Z.map(($)=>this.registerModel($))}getModel(Z){return this.models.get(Z)}getAllModels(){return Array.from(this.models.values())}repository(Z){if(!this.models.get(Z))throw Error(`Model not found: ${Z}`);return l1(this.singleTableManager,Z,this.queryBuilderOptions)}query(Z){if(!this.models.get(Z))throw Error(`Model not found: ${Z}`);return new i8(this.queryBuilderOptions).table(this.config.tableName).entity(Z)}item(Z){if(!this.models.get(Z))throw Error(`Model not found: ${Z}`);return new O8(this.queryBuilderOptions).table(this.config.tableName)}buildKey(Z,$){let Y=this.models.get(Z);if(!Y)throw Error(`Model not found: ${Z}`);let X=s1(Y.keyPatterns,$);return{pk:X.pk,sk:X.sk}}createItem(Z,$){let Y=this.models.get(Z);if(!Y)throw Error(`Model not found: ${Z}`);let X=s1(Y.keyPatterns,$),J=X.pk,G=X.sk,U={[this.config.pkAttribute]:J,[this.config.skAttribute]:G,[this.config.entityTypeAttribute]:Y.name,...$};if(Y.hasTimestamps){let H=new Date().toISOString();if(!U.createdAt)U.createdAt=H;U.updatedAt=H}if(Y.hasVersioning){if(!U._v)U._v=1}return U}parseItem(Z){let $=Z[this.config.entityTypeAttribute];if(!$)return;let{[this.config.pkAttribute]:Y,[this.config.skAttribute]:X,[this.config.entityTypeAttribute]:J,...G}=Z;return{type:$,data:G}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns(Z){let $=this.models.get(Z);if(!$)throw Error(`Model not found: ${Z}`);return $.accessPatterns}parseWithTooling(Z){let $=Z.name.toUpperCase(),Y=Z.primaryKey??"id",X=this.config.keyDelimiter,J=this.parseAttributes(Z),G=this.parseRelationships(Z,Y),U={pk:`${$}${X}{${Y}}`,sk:`${$}${X}{${Y}}`,...this.deriveGSIKeyPatterns($,Y,X,G)},H=this.deriveAccessPatterns(Z.name,$,Y,G);return{name:Z.name,entityType:$,primaryKey:Y,attributes:J,relationships:G,keyPatterns:U,accessPatterns:H,traits:Z.traits??{},hasTimestamps:Z.traits?.useTimestamps??!1,hasSoftDeletes:Z.traits?.useSoftDeletes??!1,hasUuid:Z.traits?.useUuid??!1,hasTtl:Z.traits?.useTtl??!1,hasVersioning:Z.traits?.useVersioning??!1,original:Z}}parseAttributes(Z){let $=[];if($.push({name:Z.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),Z.attributes)for(let[Y,X]of Object.entries(Z.attributes))$.push({name:Y,fillable:X.fillable??!0,required:X.required??!1,nullable:X.nullable??!0,unique:X.unique??!1,hidden:X.hidden??!1,defaultValue:X.default,cast:X.cast,dynamoDbType:this.inferDynamoDBType(X)});if(Z.traits?.useTimestamps)$.push({name:"createdAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"},{name:"updatedAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"});if(Z.traits?.useSoftDeletes)$.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return $}inferDynamoDBType(Z){if(Z.cast){let $=Z.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes($))return"N";if(["boolean","bool"].includes($))return"BOOL";if(["array","list"].includes($))return"L";if(["object","json","map"].includes($))return"M"}if(Z.validation?.rule){let $=String(Z.validation.rule);if($.includes("integer")||$.includes("numeric")||$.includes("number"))return"N";if($.includes("boolean"))return"BOOL";if($.includes("array"))return"L";if($.includes("object"))return"M"}return"S"}parseRelationships(Z,$){let Y=[];if(Z.hasOne)for(let X of Z.hasOne)Y.push({type:"hasOne",relatedModel:X,foreignKey:`${Z.name.toLowerCase()}Id`,localKey:$,requiresGsi:!0});if(Z.hasMany)for(let X of Z.hasMany)Y.push({type:"hasMany",relatedModel:X,foreignKey:`${Z.name.toLowerCase()}Id`,localKey:$,requiresGsi:!1});if(Z.belongsTo)for(let X of Z.belongsTo)Y.push({type:"belongsTo",relatedModel:X,foreignKey:`${X.toLowerCase()}Id`,localKey:$,requiresGsi:!0});if(Z.belongsToMany){let X=Array.isArray(Z.belongsToMany)?Z.belongsToMany:Object.values(Z.belongsToMany);for(let J of X){let G=typeof J==="string"?J:J?.model;if(!G)continue;let U=[Z.name,G].sort();Y.push({type:"belongsToMany",relatedModel:G,foreignKey:`${Z.name.toLowerCase()}Id`,localKey:$,pivotEntity:U.join(""),requiresGsi:!0})}}return Y}deriveGSIKeyPatterns(Z,$,Y,X){let J={},G=1;for(let U of X)if(U.requiresGsi&&G<=5)J[`gsi${G}pk`]=`${U.relatedModel.toUpperCase()}${Y}{${U.foreignKey}}`,J[`gsi${G}sk`]=`${Z}${Y}{${$}}`,U.gsiIndex=G,G++;return J}deriveAccessPatterns(Z,$,Y,X){let J=[];J.push({name:`Get ${Z} by ID`,description:`Retrieve a single ${Z} by its primary key`,entityType:$,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${$}#123`,exampleSk:`${$}#123`,efficient:!0}),J.push({name:`List all ${Z}s`,description:`Scan all ${Z} entities`,entityType:$,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:$,efficient:!1});for(let G of X){if(G.type==="hasMany")J.push({name:`Get ${G.relatedModel}s for ${Z}`,description:`Query ${G.relatedModel}s related to a ${Z}`,entityType:$,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${$}#123`,exampleSk:`${G.relatedModel.toUpperCase()}#`,efficient:!0});if(G.gsiIndex){let U=`GSI${G.gsiIndex}`;J.push({name:`Get ${Z}s by ${G.relatedModel}`,description:`Query ${Z}s by their related ${G.relatedModel}`,entityType:$,operation:"query",index:U,keyCondition:`gsi${G.gsiIndex}pk = :pk`,examplePk:`${G.relatedModel.toUpperCase()}#123`,efficient:!0})}}return J}toSingleTableEntity(Z){let $=this.extractKeyFields(Z.keyPatterns.pk);return{name:Z.name,pkPattern:Z.keyPatterns.pk,skPattern:Z.keyPatterns.sk,keyFields:$,indexes:this.extractGSIPatterns(Z.keyPatterns)}}extractKeyFields(Z){let $=Z.match(/\{([^}]+)\}/g);if(!$)return[];return $.map((Y)=>Y.slice(1,-1))}extractGSIPatterns(Z){let $=[];for(let Y=1;Y<=5;Y++){let X=`gsi${Y}pk`,J=`gsi${Y}sk`;if(Z[X])$.push({name:`GSI${Y}`,pkPattern:Z[X],skPattern:Z[J]})}return $.length>0?$:void 0}toEntityMapping(Z){return{entityType:Z.name,pkPattern:Z.keyPatterns.pk,skPattern:Z.keyPatterns.sk}}buildGSIConfig(){let Z=this.config.gsiConfig??{},$=[];if(Z.gsi1pk)$.push({name:"GSI1",pkAttribute:Z.gsi1pk,skAttribute:Z.gsi1sk});if(Z.gsi2pk)$.push({name:"GSI2",pkAttribute:Z.gsi2pk,skAttribute:Z.gsi2sk});if(Z.gsi3pk)$.push({name:"GSI3",pkAttribute:Z.gsi3pk,skAttribute:Z.gsi3sk});return $}}function w3(Z){return new o1(Z)}function C3(Z){return Z.accessPatterns}function S3(Z,$="#"){let Y=Z.name.toUpperCase(),X=Z.primaryKey??"id";return{name:Z.name,pkPattern:`${Y}${$}\${${X}}`,skPattern:`${Y}${$}\${${X}}`}}m8();function G7(Z){let $={};for(let Y of Object.keys(Z)){let X=Z[Y],J=X.definition??X.getDefinition?.()??X,G=p8(J),U=J.attributes??{},H={};for(let z of Object.keys(U))H[z]=void 0;$[G]={columns:H,primaryKey:J.primaryKey??"id"}}return $}E0();m8();import{readdirSync as G2}from"fs";import{basename as r1,extname as t1,isAbsolute as U2,join as a1}from"path";import z2 from"process";var H2=new Set([".ts",".mts",".cts",".js",".mjs",".cjs"]);function A2(Z){let $=t1(Z);if(!H2.has($))return!1;let Y=r1(Z,$);if(Y.startsWith("_")||Y==="index")return!1;return!Y.endsWith(".d")}function W2(Z){if(!Z||typeof Z!=="object")return!1;let $=Z;return typeof $.name==="string"||typeof $.table==="string"}function e1(Z){let $=[],Y=G2(Z,{withFileTypes:!0}).sort((X,J)=>X.name.localeCompare(J.name));for(let X of Y){let J=a1(Z,X.name);if(X.isDirectory()){$.push(...e1(J));continue}if(A2(X.name))$.push(J)}return $}async function Q8(Z){let $=Z.cwd??z2.cwd(),Y=U2(Z.modelsDir)?Z.modelsDir:a1($,Z.modelsDir),X={};for(let J of e1(Y)){let G=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,U=await import(`${J}${G}`),H=U.default??U,z=H.definition??H.getDefinition?.()??H;if(!W2(z))continue;let A=z.name??r1(J,t1(J));X[A]={...z,name:A}}return X}m8();A7();function ZJ(Z){let $={},Y={},X={},J={},G={},U={};for(let H of Object.keys(Z)){let z=Z[H],A=z.definition??z.getDefinition?.()??z,W=p8(A);$[H]=W,Y[W]=H,X[W]=A.primaryKey??"id";let Q=[];for(let[K,B]of Object.entries(A.attributes??{}))if(/^(?:datetime|timestamp|timestamptz|date)$/i.test(String(B?.type??"")))Q.push(K);let L=A.traits??{};if(L.useTimestamps??L.timestampable)Q.push("created_at","updated_at");if(Q.length>0)U[W]=[...new Set(Q)];let O=(K)=>{if(!K)return{};let B={};if(Array.isArray(K)){for(let V of K){let F=H7(V);if(F)B[F.model]=F.model}return B}if(typeof K==="object"){for(let[V,F]of Object.entries(K)){let I=H7(F);if(I)B[V]=I.model}return B}return{}},T=(K)=>{if(!K)return{};if(Array.isArray(K)){let B={};for(let V of K)if(typeof V==="string")B[V]=V;else if(V&&typeof V==="object"&&typeof V.model==="string")B[V.model]=V;return B}return K},w=(K)=>{if(!K)return{};return K};if(J[W]={hasOne:O(A.hasOne),hasMany:O(A.hasMany),belongsTo:O(A.belongsTo),belongsToMany:T(A.belongsToMany),hasOneThrough:w(A.hasOneThrough),hasManyThrough:w(A.hasManyThrough),morphOne:O(A.morphOne),morphMany:O(A.morphMany),morphTo:A.morphTo,morphToMany:O(A.morphToMany),morphedByMany:O(A.morphedByMany)},A.scopes&&typeof A.scopes==="object"){G[W]={};for(let K of Object.keys(A.scopes)){let B=A.scopes[K];if(typeof B==="function")G[W][K]=B}}}return{modelToTable:$,tableToModel:Y,primaryKeys:X,relations:J,scopes:G,models:Z,temporalColumns:U}}A7();m8();qZ();import{existsSync as b0,mkdirSync as j2,readdirSync as Q2,readFileSync as _2,writeFileSync as V2}from"fs";import{dirname as $J,join as _7}from"path";import UJ from"process";function fZ(Z){if(y.verbose)console.log(Z)}function l8(Z){return Z.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}function q0(Z){return d8(y.relations?.singularizeStrategy)(Z)}var $$=0,v8=0,s8=0,V7=!0,K7=[],S9=null;function zJ(){return[...K7]}function K2(Z){let $=Z;while($!==$J($)){if(b0(_7($,"package.json")))return $;$=$J($)}return UJ.cwd()}function L2(){let Z=K2(UJ.cwd()),$=T8(Z,y.migrationDir);if(!b0($))j2($,{recursive:!0}),fZ(`-- Created SQL directory: ${$}`);return $}var HJ="-- qb:generated";function AJ(Z){return Z.trimStart().startsWith(HJ)}function WJ(Z){return Z.split(`
|
|
432
|
-
`).filter(($)=>!$.trimStart().startsWith("--")).join(`
|
|
433
|
-
`).replace(/\s+/g," ").trim().replace(/;+$/,"")}function F2(Z){let $=new Set,Y;try{Y=Q2(Z).filter((X)=>X.endsWith(".sql"))}catch{return $}for(let X of Y)try{$.add(WJ(_2(_7(Z,X),"utf8")))}catch{}return $}function jJ(Z,$){if(!Z)return!1;let Y=L2();if(S9===null)S9=F2(Y);let X=WJ(Z);if(X.length>0&&S9.has(X))return fZ(`-- Migration already in the corpus, not writing it again: ${$}`),!1;$$++;let J=V7?String($$).padStart(10,"0"):String(Math.floor(Date.now()/1000)+$$),G=`${J}-${$}.sql`;if(!V7){let H=Number(J);while(b0(_7(Y,G)))H+=1,J=String(H),G=`${J}-${$}.sql`}let U=_7(Y,G);return V2(U,`${HJ}
|
|
434
|
-
${Z}`),fZ(`-- Migration file created: ${G}`),v8++,K7.push(G),S9?.add(X),!0}function B2(Z,$){return Z==="integer"&&$==="bigint"||Z==="string"&&$==="text"}function YJ(Z){if(Z.endsWith("_id"))return"bigint";if(Z.endsWith("_at"))return"datetime";if(Z.startsWith("is_")||Z.startsWith("has_"))return"boolean";return}function XJ(Z){if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean"||typeof Z==="bigint"||Z instanceof Date)return Z;return}function R2(Z){if(Z&&typeof Z==="object"&&"name"in Z){let $=Z;if($.name==="enum"||$.getRules&&Array.isArray($.getRules())){if($.enumValues&&Array.isArray($.enumValues))return $.enumValues.map((Y)=>String(Y));if($._values&&Array.isArray($._values))return $._values.map((Y)=>String(Y));if($.values&&Array.isArray($.values))return $.values.map((Y)=>String(Y))}}if(Z&&typeof Z==="object"){let $=Z,Y=$.allowedValues||$.enumValues||$._values||$.values;if(Array.isArray(Y)&&Y.length>0)return Y.map((X)=>String(X))}return}function x0(Z){if(!Z?.rules||!Array.isArray(Z.rules))return;for(let $ of Z.rules)if($?.name==="max"||$?.name==="maxLength"){if($.params&&typeof $.params.max==="number")return $.params.max;if(Array.isArray($.args)&&typeof $.args[0]==="number")return $.args[0];if(typeof $.value==="number")return $.value;if(typeof $.expectedValue==="number")return $.expectedValue}return}var v0=767;function O2(Z){if(!Z||typeof Z!=="object")return;let $=Z;if($.name)switch(String($.name).toLowerCase()){case"string":{let X=x0($);return X&&X>v0?"text":"string"}case"text":return"text";case"integer":case"int":return"integer";case"bigint":return"bigint";case"float":return"float";case"number":return"integer";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum"}if($.type){let Y=String($.type).toLowerCase();if(Y==="string"||Y==="text")return"string";if(Y==="integer"||Y==="int")return"integer";if(Y==="bigint")return"bigint";if(Y==="float")return"float";if(Y==="number")return"integer";if(Y==="boolean")return"boolean";if(Y==="date")return"date";if(Y==="datetime")return"datetime";if(Y==="timestamptz"||Y==="timestamp_tz")return"timestamptz";if(Y==="json")return"json"}return}function E2(Z){if(typeof Z!=="string")return;switch(Z.trim().toLowerCase().replace(/[\s-]+/g,"_")){case"varchar":case"string":return"string";case"text":return"text";case"bool":case"boolean":return"boolean";case"int":case"integer":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"number":case"numeric":case"decimal":return"decimal";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamp_tz":case"timestamptz":case"timestamp_with_time_zone":return"timestamptz";case"json":case"jsonb":return"json";case"enum":return"enum";default:return}}function r9(Z,$){let Y=ZJ(Z),X=[];for(let H of Object.keys(Z)){let z=Z[H],A=p8(z),W=z.primaryKey??"id",Q=z.autoIncrement!==!1,L=z.attributes??{},O=[],T=[];if(!L[W])O.push({name:l8(W),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});let w=new Map,K=I9(z.belongsTo).length>0,B=new Set(Object.keys(L).map((S)=>l8(S))),V=new Set;for(let S of B){if(!S.endsWith("_type"))continue;let C=`${S.slice(0,-5)}_id`;if(B.has(C))V.add(C)}for(let S of I9(z.belongsTo)){let C=S.foreignKey??`${l8(S.model)}_id`,v=Y.modelToTable[S.model];if(v)w.set(C,{table:v,onDelete:S.onDelete})}for(let S of Object.keys(L)){let C=L[S],v=l8(S),i=Boolean(C.validation?.rule?.isRequired),m=S===W?!1:C.nullable??!(C.required??i),q,l,u=S===W;if(q=E2(C.type)??O2(C.validation?.rule),q==="string"){let c=x0(C.validation?.rule);if(c&&c>v0)q="text"}if(!q||q==="enum"){let c=R2(C.validation?.rule);if(c&&c.length>0)q="enum",l=c}if(!q)q=YJ(v);if(!q){let c=XJ(C.default);if(typeof c==="string")q=c.length>255?"text":"string";else if(typeof c==="number")q=Number.isInteger(c)?"integer":"float";else if(typeof c==="boolean")q="boolean";else if(typeof c==="bigint")q="bigint";else if(c instanceof Date)q="datetime"}if(!q)q=u?"bigint":"string";let r=q==="string"?x0(C.validation?.rule):void 0,b={name:v,type:q,isPrimaryKey:u,isUnique:Boolean(C.unique),isNullable:m,hasDefault:typeof C.default<"u",defaultValue:XJ(C.default),enumValues:l,maxLength:typeof r==="number"&&r>0&&r<=v0?r:void 0};if(v.endsWith("_id")&&C.foreignKey!==!1&&!V.has(v))if(typeof C.foreignKey==="object"&&C.foreignKey!==null){let c=C.foreignKey;if(b.references={table:c.table,column:c.column??"id",onDelete:c.onDelete,onUpdate:c.onUpdate},c.nullable!==void 0)b.isNullable=c.nullable}else{let c=w.get(v),GZ=v.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(mZ,E8,Y8)=>Y8.toUpperCase()),FZ=c?.table??(K?void 0:Y.modelToTable[GZ]);if(FZ){let mZ=Y.primaryKeys[FZ]??"id";b.references={table:FZ,column:mZ,onDelete:c?.onDelete}}}O.push(b)}let F=I9(z.belongsTo);for(let S of F){let C=S.foreignKey??`${l8(S.model)}_id`;if(O.some((m)=>m.name===C))continue;let v=Y.modelToTable[S.model],i=v?Y.primaryKeys[v]??"id":void 0;O.push({name:C,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:v&&i&&!V.has(C)?{table:v,column:i,onDelete:S.onDelete}:void 0})}let I=z.traits;if(I?.useTimestamps??I?.timestampable??!1){if(!O.some((S)=>S.name==="created_at"))O.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:x8});if(!O.some((S)=>S.name==="updated_at"))O.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(I?.useSoftDeletes??I?.softDeletable??!1){if(!O.some((S)=>S.name==="deleted_at"))O.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(I?.useUuid??!1){if(!O.some((S)=>S.name==="uuid"))O.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let S of z.indexes??[])T.push({name:S.name,columns:S.columns.map((C)=>l8(C)),type:S.unique?"unique":"index",where:S.where});for(let S of O)if(S.isUnique&&!S.isPrimaryKey)T.push({name:`${A}_${S.name}_unique`,columns:[S.name],type:"unique"});let d=Array.isArray(z.shardKey)?z.shardKey.map(l8):void 0,P=Array.isArray(z.sortKey)?z.sortKey.map(l8):void 0,M=z.tableKind;X.push({table:A,columns:O,indexes:T,shardKey:d,sortKey:P,tableKind:M})}let J=new Set(X.map((H)=>H.table));function G(H){if(!J.has(H.table))J.add(H.table),X.push(H)}for(let H of Object.keys(Z)){let z=Z[H],A=z?.traits??{},W=p8(z),Q=q0(W);if(A.likeable){let L=typeof A.likeable==="object"?A.likeable:{},O=L.table||`${W}_likes`,T=L.foreignKey||`${Q}_id`;G({table:O,columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"user_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"users",column:"id"}},{name:T,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:W,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:x8},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${O}_user_target_unique`,columns:["user_id",T],type:"unique"}]})}if(A.taggable)G({table:"taggables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"order",type:"integer",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:0},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:x8},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggables_target_index",columns:["taggable_id","taggable_type"],type:"index"},{name:"taggables_type_slug_unique",columns:["taggable_type","slug"],type:"unique"}]}),G({table:"taggable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"tag_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"taggables",column:"id"}},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:x8},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_models_owner_unique",columns:["tag_id","taggable_id","taggable_type"],type:"unique"},{name:"taggable_models_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(A.categorizable)G({table:"categorizables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:x8},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizables_type_slug_unique",columns:["categorizable_type","slug"],type:"unique"}]}),G({table:"categorizable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"category_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"categorizables",column:"id"}},{name:"categorizable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:x8},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_models_owner_unique",columns:["category_id","categorizable_id","categorizable_type"],type:"unique"},{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let H of Object.keys(Z)){let z=Z[H],A=z?.belongsToMany;if(!A||typeof A!=="object"||Array.isArray(A))continue;let W=p8(z),Q=q0(W);for(let[L,O]of Object.entries(A)){let T=O;if(!T||typeof T!=="object")continue;if(T.through)continue;let w=T.pivot;if(!w||!w.columns&&!w.timestamps&&!w.uniques)continue;let K=T.model,V=Z[K]?.table||`${String(K).toLowerCase()}s`,F=q0(V),I=T.table||[Q,F].sort().join("_"),E=T.foreignKey||`${Q}_id`,n=T.relatedKey||`${F}_id`,x=new Set([E,n,...Object.keys(w.columns??{})]),d=new Set;for(let v of x){if(!v.endsWith("_type"))continue;let i=`${v.slice(0,-5)}_id`;if(x.has(i))d.add(i)}let P=(v,i)=>d.has(v)?void 0:{table:i,column:"id"},M=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:E,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:P(E,W)},{name:n,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:P(n,V)}];if(w.columns)for(let[v,i]of Object.entries(w.columns)){let m=i,q=YJ(v)??"string";M.push({name:v,type:q,isPrimaryKey:!1,isUnique:!1,isNullable:m?.nullable??!1,hasDefault:m?.default!==void 0,defaultValue:m?.default})}if(w.timestamps)M.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:x8}),M.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let S=[],C=w.uniques&&w.uniques.length>0?w.uniques:[[E,n]];for(let v=0;v<C.length;v++){let i=C[v];S.push({name:`${I}_${i.join("_")}_unique${v>0?`_${v}`:""}`,columns:[...i],type:"unique"})}G({table:I,columns:M,indexes:S})}}let U=new Map(X.map((H)=>[H.table,H]));for(let H of X)for(let z of H.columns){if(!z.references)continue;let A=U.get(z.references.table)?.columns.find((W)=>W.name===z.references.column);if(!A||z.type===A.type)continue;z.type=A.type,z.maxLength=A.maxLength,z.enumValues=A.enumValues,z.enumTypeName=A.enumTypeName}return{dialect:$.dialect,vitessSharded:$.vitessSharded,tables:X}}function L7(Z,$={}){$$=0,v8=0,s8=0,K7=[],S9=null,V7=!0;let Y=$.dryRun?()=>!1:jJ,X=[],J=B8(Z.dialect,{vitessSharded:Z.vitessSharded}),{tables:G,deferredForeignKeys:U}=QJ(Z.tables,Z.dialect);for(let[z,A]of G.entries()){let W={...A,columns:A.columns.map((w)=>U.has(N9(A.table,w.name))?{...w,references:void 0}:w)},Q=[],L=new Set;for(let w of W.columns)if(w.type==="enum"&&w.enumValues&&w.enumValues.length>0){let K=`${W.table}_${w.name}_type`;if(w.enumTypeName=K,!L.has(K)){let B=J.createEnumType(K,w.enumValues);if(B)Q.push(B);L.add(K)}}let O=J.createTable(W);Q.push(O);for(let w of W.indexes)Q.push(J.createIndex(W.table,w,W.columns));if(z===G.length-1)for(let w of G)for(let K of w.columns){if(!K.references||!U.has(N9(w.table,K.name)))continue;let B=J.addForeignKey(w.table,K.name,K.references.table,K.references.column,K.references.onDelete,K.references.onUpdate);if(B)Q.push(B)}X.push(...Q);let T=Q.join(`
|
|
435
|
-
|
|
436
|
-
`);Y(T,`create-${W.table}-table`)}if(v8+s8===0)fZ("-- Nothing to migrate");else{let z=[];if(v8>0)z.push(`${v8} created`);if(s8>0)z.push(`${s8} updated`);fZ(`-- Migration files: ${z.join(", ")}`)}return X}function N9(Z,$){return`${Z}\x00${$}`}function QJ(Z,$){if($==="sqlite"||Z.length<2)return{tables:Z,deferredForeignKeys:new Set};let Y=new Map(Z.map((z)=>[z.table,z])),X=new Map;for(let z of Z)X.set(z.table,new Set(z.columns.map((A)=>A.references?.table).filter((A)=>Boolean(A&&A!==z.table&&Y.has(A)))));let J=[],G=new Set;while(J.length<Z.length){let z=Z.find((A)=>!G.has(A.table)&&[...X.get(A.table)??[]].every((W)=>G.has(W)));if(!z)break;J.push(z),G.add(z.table)}let U=new Set(Z.filter((z)=>!G.has(z.table)).map((z)=>z.table)),H=new Set;for(let z of Z){if(!U.has(z.table))continue;for(let A of z.columns)if(A.references&&U.has(A.references.table)&&A.references.table!==z.table)H.add(N9(z.table,A.name))}return J.push(...Z.filter((z)=>U.has(z.table))),{tables:J,deferredForeignKeys:H}}function o3(Z){return L7(Z).join(`
|
|
437
|
-
`)}function r3(Z,$){return C2(Z,$).join(`
|
|
438
|
-
`)}function _J(Z){let $=oZ("crypto");function Y(J){if(J==null||typeof J!=="object"||J instanceof Date)return J;if(Array.isArray(J))return J.map((U)=>Y(U));let G={};for(let U of Object.keys(J).sort())G[U]=Y(J[U]);return G}let X=JSON.stringify(Y(Z));return $.createHash("sha256").update(X).digest("hex")}function JJ(Z){let $={};for(let Y of Z)$[Y.table]=Y;return $}function Z$(Z){let $={};for(let Y of Z)$[Y.name]=Y;return $}function y0(Z,$){if($==="sqlite"){if(Z.name.endsWith("_id")&&O9(Z.type))return"INTEGER";switch(Z.type){case"string":case"text":case"date":case"datetime":case"timestamptz":case"json":case"enum":return"TEXT";case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}if($==="mysql"||$==="vitess"||$==="singlestore")switch(Z.type){case"string":return`VARCHAR(${Z.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";case"decimal":return"DECIMAL";case"date":return"DATE";case"datetime":case"timestamptz":return"DATETIME";case"json":return"JSON";case"enum":return"ENUM";default:return Z.type}return Z.type}var x8="UTC_TIMESTAMP";function h0(Z,$){if(!Z.hasDefault||Z.defaultValue===void 0)return;let Y=Z.defaultValue;if(Y instanceof Date)return Y.toISOString();if(typeof Y==="boolean")return Y?"1":"0";if(typeof Y==="bigint"||typeof Y==="number")return String(Y);let X=String(Y).trim();if(X=X.replace(/::[\w ]+$/i,"").trim(),X.startsWith("'")&&X.endsWith("'")||X.startsWith('"')&&X.endsWith('"'))X=X.slice(1,-1);let J=X.toUpperCase();if(["UTC_TIMESTAMP","UTC_TIMESTAMP()","(UTC_TIMESTAMP)","(UTC_TIMESTAMP())","TIMEZONE('UTC', NOW())","TIMEZONE('UTC'::TEXT, NOW())","(NOW() AT TIME ZONE 'UTC')","NOW() AT TIME ZONE 'UTC'"].includes(J.replace(/\s+/g," ")))return x8;if($==="sqlite"&&J==="CURRENT_TIMESTAMP")return x8;if(["CURRENT_TIMESTAMP","NOW()","CURRENT_DATE","CURRENT_TIME","NULL","TRUE","FALSE"].includes(J))return J==="NOW()"?"CURRENT_TIMESTAMP":J;if(Z.type==="boolean"){if(/^(?:1|t|true|yes)$/i.test(X))return"1";if(/^(?:0|f|false|no)$/i.test(X))return"0"}if(/^-?\d+(?:\.\d+)?$/.test(X))return String(Number(X));return X}function D2(Z,$,Y){if(y0(Z,Y)!==y0($,Y))return!0;if(Z.isNullable!==$.isNullable)return!0;if(Z.hasDefault!==$.hasDefault)return!0;if(h0(Z,Y)!==h0($,Y))return!0;if(Z.isUnique!==$.isUnique)return!0;if(Z.type==="enum"&&$.type==="enum"){let X=(Z.enumValues||[]).slice().sort().join(","),J=($.enumValues||[]).slice().sort().join(",");if(X!==J)return!0}return!1}function GJ(Z,$){return JSON.stringify([y0(Z,$),Z.isPrimaryKey,Z.isUnique,Z.isNullable,Z.hasDefault,h0(Z,$)??null,(Z.enumValues??[]).slice().sort(),Z.references?[Z.references.table,Z.references.column,Z.references.onDelete??null,Z.references.onUpdate??null]:null])}function I2(Z,$,Y){let X=Object.keys(Z).filter((W)=>!$[W]),J=Object.keys($).filter((W)=>!Z[W]),G=new Map,U=new Map;for(let W of X){let Q=GJ(Z[W],Y),L=G.get(Q)??[];L.push(W),G.set(Q,L)}for(let W of J){let Q=GJ($[W],Y),L=U.get(Q)??[];L.push(W),U.set(Q,L)}let H=[],z=new Set,A=new Set;for(let[W,Q]of G){let L=U.get(W);if(Q.length===1&&L&&L.length===1)H.push({from:Q[0],to:L[0]}),z.add(Q[0]),A.add(L[0])}return{renames:H,removed:X.filter((W)=>!z.has(W)),added:J.filter((W)=>!A.has(W))}}function M2(Z,$){let Y=Z.columns.find((X)=>X.name===$);if(Y&&(Y.isPrimaryKey||Y.isUnique||Y.references))return!0;return Z.indexes.some((X)=>X.columns.includes($))}function w2(Z,$){if(Boolean(Z)!==Boolean($))return!0;if(!Z||!$)return!1;if((Z.constraintNames?.length??0)>1)return!0;let Y=(X)=>(X??"no action").toLowerCase();return Z.table!==$.table||Z.column!==$.column||Y(Z.onDelete)!==Y($.onDelete)||Y(Z.onUpdate)!==Y($.onUpdate)}function VJ(Z,$){return`${Z.type}:${j8($,Z.name)}:${Z.columns.join(",")}`}function k0(Z,$){let Y={};for(let X of Z)Y[VJ(X,$)]=X;return Y}function f0(Z,$,Y={}){if(!Z||Z.dialect!==$.dialect){let V=L7($,{dryRun:Y.dryRun}),F=$.tables.map((I)=>({kind:"create_table",table:I.table,destructive:!1,sql:""}));return{statements:V,operations:F}}let X=Y.applyRenames!==!1,J=Y.preserveUnknownColumns===!0,G=Y.dryRun?()=>!1:jJ;$$=0,v8=0,s8=0,K7=[],S9=null,V7=!1;let U=[],H=[],z=B8($.dialect,{vitessSharded:$.vitessSharded}),A=$.dialect,W=JJ(Z.tables),Q=JJ($.tables);for(let V of Object.keys(W))if(!Q[V]){let F=z.dropTable(V);U.push(F),H.push({kind:"drop_table",table:V,destructive:!0,sql:F}),G(F,`drop-${V}-table`),fZ(`-- Detected dropped table: ${V}`)}let L=Object.keys(Q).filter((V)=>!W[V]).map((V)=>Q[V]),{tables:O,deferredForeignKeys:T}=QJ(L,A);for(let[V,F]of O.entries()){let I={...F,columns:F.columns.map((P)=>T.has(N9(F.table,P.name))?{...P,references:void 0}:P)},E=[],n=new Set;for(let P of I.columns)if(P.type==="enum"&&P.enumValues&&P.enumValues.length>0){let M=`${I.table}_${P.name}_type`;if(P.enumTypeName=M,!n.has(M)){let S=z.createEnumType(M,P.enumValues);if(S)E.push(S);n.add(M)}}let x=z.createTable(I);E.push(x);for(let P of I.indexes){let M=z.createIndex(I.table,P,I.columns);E.push(M),H.push({kind:"create_index",table:I.table,column:P.name,destructive:!1,sql:M})}for(let P of F.columns)if(P.references&&!T.has(N9(F.table,P.name)))H.push({kind:"add_foreign_key",table:F.table,column:P.name,destructive:!1,sql:x});if(V===O.length-1)for(let P of O)for(let M of P.columns){if(!M.references||!T.has(N9(P.table,M.name)))continue;let S=z.addForeignKey(P.table,M.name,M.references.table,M.references.column,M.references.onDelete,M.references.onUpdate);if(!S)continue;E.push(S),H.push({kind:"add_foreign_key",table:P.table,column:M.name,destructive:!1,sql:S})}U.push(...E),H.push({kind:"create_table",table:I.table,destructive:!1,sql:x});let d=E.join(`
|
|
439
|
-
|
|
440
|
-
`);G(d,`create-${I.table}-table`)}let w=new Set;for(let V of Object.keys(Q)){let F=W[V],I=Q[V];if(!F)continue;let E=Z$(F.columns),n=Z$(I.columns);for(let x of Object.keys(n)){let d=n[x];if(d.type!=="enum"||!d.enumValues||d.enumValues.length===0)continue;let P=`${I.table}_${d.name}_type`;if(d.enumTypeName=P,E[x])continue;if(!w.has(P)){let M=z.createEnumType(P,d.enumValues);if(M)U.push(M),H.push({kind:"create_enum",table:I.table,column:d.name,destructive:!1,sql:M}),G(M,`create-${P}-enum`);w.add(P)}}}for(let V of Object.keys(Q)){let F=W[V],I=Q[V];if(!F)continue;let E=Z$(F.columns),n=k0(F.indexes,F.table),x=Z$(I.columns),d=k0(I.indexes,I.table),P=[],M=Object.keys(E).filter((q)=>!x[q]),S=Object.keys(x).filter((q)=>!E[q]);if(X&&!J){let q=I2(E,x,A);P=q.renames,M=q.removed,S=q.added}if(J){let q=M.map((u)=>E[u]),l=F.indexes.filter((u)=>!d[VJ(u,F.table)]);if(q.length>0||l.length>0){if(q.length>0)fZ(`-- Keeping ${q.length} column(s) on "${I.table}" no model declares: ${M.join(", ")} \u2014 reconciled from the database, where an undeclared column is out of scope rather than removed`);if(l.length>0)fZ(`-- Keeping ${l.length} index(es) on "${I.table}" no model declares: ${l.map((u)=>u.name).join(", ")} \u2014 reconciled from the database, where an undeclared index is out of scope rather than removed`);I={...I,columns:[...I.columns,...q],indexes:[...I.indexes,...l]},x=Z$(I.columns),d=k0(I.indexes,I.table)}M=[]}let C=Object.keys(x).filter((q)=>E[q]&&D2(E[q],x[q],A)),v=Object.keys(x).filter((q)=>E[q]&&w2(E[q].references,x[q].references));if(A==="sqlite"){if(C.length>0||v.length>0||M.some((l)=>M2(F,l))){let l={},u=new Map(P.map((GZ)=>[GZ.to,GZ.from]));for(let GZ of I.columns)if(E[GZ.name])l[GZ.name]=GZ.name;else if(u.has(GZ.name))l[GZ.name]=u.get(GZ.name);let r=`_qb_tmp_${I.table}`,b=0;while((W[r]||Q[r])&&b<100)b+=1,r=`_qb_tmp_${I.table}_${b}`;let c=z.rebuildTable({target:I,tempName:r,columnSource:l});U.push(c);let t=C.some((GZ)=>E[GZ].type!==x[GZ].type);H.push({kind:"rebuild_table",table:I.table,destructive:M.length>0||t,sql:c});for(let GZ of P)H.push({kind:"rename_column",table:I.table,from:GZ.from,to:GZ.to,destructive:!1,confidence:"high",sql:c});for(let GZ of M)H.push({kind:"drop_column",table:I.table,column:GZ,destructive:!0,sql:c});fZ(`-- Detected SQLite table rebuild required: ${I.table}`),G(c,`alter-${I.table}-table`);continue}}let i=[],m=!1;for(let q of Object.keys(n))if(!d[q]){let l=n[q],u=z.dropIndex(I.table,l.name);i.push(u),U.push(u),H.push({kind:"drop_index",table:I.table,column:l.name,destructive:!1,sql:u}),fZ(`-- Detected dropped index: ${l.name} from ${I.table}`),m=!0}for(let q of P){let l=z.renameColumn(I.table,q.from,q.to);i.push(l),U.push(l),H.push({kind:"rename_column",table:I.table,from:q.from,to:q.to,destructive:!1,confidence:"high",sql:l}),fZ(`-- Detected renamed column: ${I.table}.${q.from} -> ${q.to}`),m=!0}for(let q of M){let l=z.dropColumn(I.table,q);i.push(l),U.push(l),H.push({kind:"drop_column",table:I.table,column:q,destructive:!0,sql:l}),fZ(`-- Detected dropped column: ${I.table}.${q}`),m=!0}for(let q of C){let l=E[q],u=x[q],r=z.modifyColumn(I.table,u);i.push(r),U.push(r),H.push({kind:"modify_column",table:I.table,column:q,destructive:l.type!==u.type&&!B2(l.type,u.type),sql:r}),fZ(`-- Detected column change: ${I.table}.${q} (${l.type} -> ${u.type})`),m=!0}for(let q of v){let l=x[q];if(!l.references)continue;let u=z.addForeignKey(I.table,l.name,l.references.table,l.references.column,l.references.onDelete,l.references.onUpdate,E[q].references?.constraintNames);if(!u)continue;i.push(u),U.push(u),H.push({kind:"add_foreign_key",table:I.table,column:q,destructive:!1,sql:u}),fZ(`-- Detected foreign-key change: ${I.table}.${q} -> ${l.references.table}(${l.references.column})`),m=!0}for(let q of S){let l=x[q],u=z.addColumn(I.table,l);if(i.push(u),U.push(u),H.push({kind:"add_column",table:I.table,column:l.name,destructive:!1,sql:u}),fZ(`-- Detected new column: ${I.table}.${l.name}`),m=!0,l.references){let r=z.addForeignKey(I.table,l.name,l.references.table,l.references.column,l.references.onDelete,l.references.onUpdate);if(r)i.push(r),U.push(r),H.push({kind:"add_foreign_key",table:I.table,column:l.name,destructive:!1,sql:r})}}for(let q of Object.keys(d))if(!n[q]){let l=d[q],u=z.createIndex(I.table,l,I.columns);i.push(u),U.push(u),H.push({kind:"create_index",table:I.table,column:l.name,destructive:!1,sql:u}),fZ(`-- Detected new index: ${l.name} in ${I.table}`),m=!0}if(m){let q=i.join(`
|
|
441
|
-
|
|
442
|
-
`);G(q,`alter-${I.table}-table`)}}if(v8+s8===0)fZ("-- Nothing to migrate");else{let V=[];if(v8>0)V.push(`${v8} created`);if(s8>0)V.push(`${s8} updated`);fZ(`-- Migration files: ${V.join(", ")}`)}return{statements:U.length===0?["-- No changes detected"]:U,operations:H}}function C2(Z,$,Y={}){return f0(Z,$,Y).statements}P0();function a3(Z){return Z}class S2{get order(){return 100}get description(){return}}function Zj(Z){return Z}e9();e9();Z7();l$();qZ();function KJ(Z){switch(Z){case"text":return"text";case"string":case"enum":return"varchar";case"integer":case"bigint":return"integer";case"float":case"double":case"decimal":return"fractional";case"boolean":return"boolean";case"date":case"datetime":case"timestamptz":return"date";case"json":return"json";default:return"other"}}function LJ(Z){let $=String(Z??"").toLowerCase().trim();if(/^(?:bool|boolean|bit)\b/.test($)||$==="tinyint(1)")return"boolean";if(/^(?:json|jsonb)\b/.test($))return"json";if(/^(?:bytea|blob|binary|varbinary)\b/.test($))return"binary";if(/^(?:date|time|timestamp|datetime)\b/.test($))return"date";if(/(?:^|\b)(?:varchar|character varying|nvarchar|char)\b/.test($))return"varchar";if(/^(?:text|longtext|mediumtext|tinytext|clob|citext)\b/.test($))return"text";if(/^(?:decimal|numeric|real|double|money)\b/.test($)||/^float\d*\b/.test($))return"fractional";if(/^(?:integer|bigint|smallint|tinyint|serial|bigserial|smallserial|mediumint)\b/.test($)||/^int\d*\b/.test($))return"integer";return"other"}function FJ(Z,$,Y){if(Z===$)return!0;if(Y==="sqlite"){if(Z==="boolean"&&$==="integer")return!0;if((Z==="date"||Z==="json")&&$==="text")return!0}if(YZ(Y)&&Z==="boolean"&&$==="integer")return!0;if(Z==="varchar"&&$==="text")return!0;if(Z==="integer"&&$==="fractional")return!0;if(Z==="other"||$==="other")return!0;return!1}async function N2(Z,$={}){let Y=$.dialect??y.dialect,X=Z.tables.map((A)=>A.table),J=await Q0({tables:X}),G=new Map(J.map((A)=>[A.table.toLowerCase(),A])),U=[],H=[],z=[];for(let A of Z.tables){let W=G.get(A.table.toLowerCase());if(!W){U.push(A.table);continue}let Q=new Map(W.columns.map((L)=>[L.name.toLowerCase(),L]));for(let L of A.columns){let O=Q.get(L.name.toLowerCase()),T=KJ(L.type);if(!O){H.push({table:A.table,column:L.name,expected:T});continue}let w=LJ(O.sqlType);if(!FJ(T,w,Y))z.push({table:A.table,column:L.name,expected:T,actual:w,actualSqlType:O.sqlType})}}return{missingTables:U,missingColumns:H,typeMismatches:z,clean:U.length===0&&H.length===0&&z.length===0}}function P2(Z){if(Z.clean)return"";let $=[];if(Z.missingTables.length>0)$.push(` Missing tables: ${Z.missingTables.join(", ")}`);for(let J of Z.missingColumns.slice(0,10))$.push(` \u2022 ${J.table}.${J.column} is missing (models declare ${J.expected})`);for(let J of Z.typeMismatches.slice(0,10))$.push(` \u2022 ${J.table}.${J.column} is ${J.actualSqlType}, models declare ${J.expected}`);let Y=Math.min(Z.missingColumns.length,10)+Math.min(Z.typeMismatches.length,10),X=Z.missingColumns.length+Z.typeMismatches.length;if(X>Y)$.push(` + ${X-Y} more`);return["The live schema does not match the models.",...$,"","Migrations will NOT fix this on their own: the runner only applies files that have","not run yet, and a corrected `CREATE TABLE IF NOT EXISTS` is a no-op against a table","that already exists. Regenerate and apply the difference, or rebuild the schema."].join(`
|
|
443
|
-
`)}async function k2(Z,$,Y){if(Y.length===0)return;let X=SJ(U9());try{await NJ(Z,$);for(let J of Y)await F7(Z,J,$),XZ(`-- \u2713 Recorded applied migration: ${J}`)}catch(J){XZ(`-- Could not record applied migrations (the schema change itself succeeded): ${J instanceof Error?J.message:String(J)}`)}}function MJ(Z,$){try{return AJ(Y$($8(Z,$),"utf8"))}catch{return!1}}function x2(Z){let $=Z instanceof Error?Z.message:String(Z);return/duplicate column name/i.test($)||/duplicate key name/i.test($)||/\balready exists\b/i.test($)}function XZ(Z){if(y.verbose)console.log(Z)}function wJ(Z){return $8(Z,y.snapshotDir||".qb")}function d0(Z,$){return $8(wJ(Z),`model-snapshot.${$}.json`)}function v2(Z,$){let Y=d0(Z,$);if(!y8(Y))return;try{let X=Y$(Y,"utf8"),J=JSON.parse(X);if(J?.plan&&Array.isArray(J.plan.tables)&&J.plan.dialect)return J.plan;if(Array.isArray(J?.tables)&&J?.dialect)return J;XZ("-- Invalid snapshot format, treating as no previous state");return}catch(X){XZ(`-- Could not load snapshot, treating as no previous state: ${X instanceof Error?X.message:String(X)}`);return}}function CJ(Z,$,Y){let X=d0(Z,$),J=wJ(Z),G=_J(Y);if(y8(X))try{let H=JSON.parse(Y$(X,"utf8"));if(H?.hash===G&&H?.dialect===$&&H?.plan){XZ("-- Model snapshot unchanged");return}}catch{}if(!y8(J))OJ(J,{recursive:!0}),XZ(`-- Created snapshot directory: ${J}`);let U={plan:Y,hash:G,dialect:$,updatedAt:new Date().toISOString()};IJ(X,JSON.stringify(U,null,2)),XZ(`-- Model snapshot saved to ${X}`)}function pU(Z,$={}){let Y=$.dialect??Z.dialect;CJ($.workspaceRoot??U9(),Y,Z)}function U9(){return B0()}function SJ(Z){let $=T8(Z,y.migrationDir);if(!y8($))OJ($,{recursive:!0}),XZ(`-- Created SQL directory: ${$}`);return $}async function F0(Z,$={}){if(await i$(),!Z)Z=$8(p0.cwd(),"app/Models");let Y=$.dialect||y.dialect||"postgres",X=U9(),J=await Q8({modelsDir:Z}),G=r9(J,{dialect:Y,vitessSharded:$.vitessSharded}),U,H=!1;if(!$.full)if(U=v2(X,Y),U)XZ("-- Comparing with stored model snapshot");else{let O=$8(Z,`.qb-migrations.${Y}.json`),T=String($.state||O);if(y8(T))try{let w=Y$(T,"utf8"),K=JSON.parse(w);if(U=K?.plan&&K.plan.tables?K.plan:K?.tables?K:void 0,U)XZ("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!U||$.fromDb)try{let w=await rX(Y),K=new Set(G.tables.map((V)=>V.table)),B=w.tables.filter((V)=>K.has(V.table));if(B.length>0)U={dialect:w.dialect,tables:B},H=!0,XZ(`-- No snapshot; reconciling against live database (${B.length} matching table${B.length===1?"":"s"})`)}catch(w){XZ(`-- Could not introspect live database, treating as no previous state: ${w instanceof Error?w.message:String(w)}`)}if(!U)XZ("-- No previous snapshot found, generating full migration")}else XZ("-- Full migration requested, ignoring any previous state");let z=$.full?{statements:L7(G,{dryRun:$.dryRun}),operations:G.tables.map((O)=>({kind:"create_table",table:O.table,destructive:!1,sql:""}))}:f0(U,G,{applyRenames:$.applyRenames,dryRun:$.dryRun,preserveUnknownColumns:H}),A=z.statements,W=z.operations,Q=A.join(`
|
|
444
|
-
`),L=A.some((O)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(O));if($.apply){let O=T2($8(q2(),"qb-migrate-")),T=$8(O,"migration.sql");try{if(L){IJ(T,Q);let w=JZ();await w.file(T),XZ("-- Migration applied"),await k2(w,Y,zJ())}else XZ("-- No changes; nothing to apply")}catch(w){throw console.error("-- Migration failed:",w),w}finally{DJ(O,{recursive:!0,force:!0})}}if(!$.dryRun)CJ(X,Y,G);return{sql:Q,sqlStatements:A,hasChanges:L,plan:G,operations:W}}var BJ="bun-query-builder:migrate",y2=/\bCONCURRENTLY\b|^\s*VACUUM\b|^\s*BEGIN\s*(?:;|TRANSACTION\b)|^\s*PRAGMA\s+foreign_keys\b/im;function RJ(Z){return Z==="postgres"||Z==="sqlite"}async function h2(Z,$){if(Z==="sqlite")return await $();let Y=JZ(),X;try{X=await Y.reserve()}catch{return await $()}let J=!1;try{return await X.advisoryLock(BJ),J=!0,await $()}finally{try{if(J)await X.advisoryUnlock(BJ)}finally{X.release?.()}}}async function dU(Z){await i$();let $=U9(),Y=SJ($),X=y.dialect||"postgres",G=EJ(Y).filter((U)=>U.endsWith(".sql")).sort();if(G.length===0)return XZ("-- No migration files found to execute"),!0;XZ(`-- Found ${G.length} script files to execute`);try{let U=JZ();return await h2(X,async()=>{await NJ(U,X);let H=await p2(U,X),z=G.filter((A)=>!H.includes(A));if(z.length===0)return XZ("-- No pending migrations to execute"),!0;XZ(`-- Executing ${z.length} migration${z.length===1?"":"s"}`);for(let A of z){let W=$8(Y,A);XZ(`-- Executing: ${A}`);try{if(RJ(X)&&!y2.test(Y$(W,"utf-8")))await U.transaction(async(L)=>{await L.file(W),await F7(L,A,X)});else if(await U.file(W),await F7(U,A,X),!RJ(X))XZ(`-- (${X} commits DDL implicitly, so ${A} was not applied atomically)`);else XZ(`-- (${A} contains a statement that cannot run in a transaction, so it was not applied atomically)`);XZ(`-- \u2713 Migration ${A} executed and recorded`)}catch(Q){if(MJ(Y,A)&&x2(Q)){await F7(U,A,X),XZ(`-- \u2713 Migration ${A} was already applied; recorded it (${Q instanceof Error?Q.message:String(Q)})`);continue}throw console.error(`-- \u2717 Migration ${A} failed:`,Q),Q}}return XZ("-- All migrations executed successfully"),!0})}catch(U){throw console.error("-- Migration execution failed:",U),U}return!0}async function mU(Z,$={}){if(await i$(),!Z)Z=$8(p0.cwd(),"app/Models");let Y=$.dialect||y.dialect||"postgres",X=B8(Y),J=U9(),G=async(U)=>{let H=X.dropTable(U);await z0(async(z)=>{if(Y==="sqlite")await z.unsafe("PRAGMA foreign_keys = OFF").execute();if(Y==="mysql"||Y==="vitess")await z.unsafe("SET FOREIGN_KEY_CHECKS = 0").execute();try{await z.unsafe(H).execute()}finally{if(Y==="sqlite")await z.unsafe("PRAGMA foreign_keys = ON").execute();if(Y==="mysql"||Y==="vitess")await z.unsafe("SET FOREIGN_KEY_CHECKS = 1").execute()}})};try{try{await G("migrations"),XZ("-- Dropped migrations table")}catch(z){console.error(z)}let U=[],H=[];try{let z=await Q8({modelsDir:Z}),A=r9(z,{dialect:Y});U=A.tables.map((Q)=>Q.table);let W=new Set;for(let Q of A.tables)for(let L of Q.columns)if(L.type==="enum"&&L.enumValues&&L.enumValues.length>0){let O=`${Q.table}_${L.name}_type`;W.add(O)}H=Array.from(W)}catch(z){console.error(z),U=[],H=[]}if(U.length===0)XZ("-- No tables found to drop");else{XZ(`-- Dropping ${U.length} tables: ${U.join(", ")}`);for(let z of U.reverse())try{await G(z),XZ(`-- Dropped table: ${z}`)}catch(A){console.error(A),XZ(`-- Table ${z} may not exist, skipping drop`)}}if(H.length>0){XZ(`-- Dropping ${H.length} enum types: ${H.join(", ")}`);for(let z of H)try{let A=X.dropEnumType(z);if(A)await z0(async(W)=>{await W.unsafe(A).execute(),XZ(`-- Dropped enum type: ${z}`)})}catch(A){console.error(A),XZ(`-- Enum type ${z} may not exist, skipping drop`)}}else XZ("-- No enum types found to drop");if(U.length>0&&!$.preserveMigrationState)try{await b2(Z,J,$)}catch(z){console.error(z),XZ("-- Could not clean up migration files")}else if(U.length===0)XZ("-- No models directory found; keeping committed migration files in place");else XZ("-- Preserving migration files and model snapshot for fresh replay");if(!$.preserveMigrationState)try{await g2(J)}catch(z){console.error(z),XZ("-- Could not clear generated directory")}return XZ("-- Database reset completed successfully"),!0}catch(U){return console.error("-- Database reset failed:",U),!1}}async function b2(Z,$,Y={}){if(!Z)Z=$8(p0.cwd(),"app/Models");if(!$)$=U9();let X=String(Y.dialect||y.dialect||"postgres"),J=d0($,X);if(y8(J))g0(J),XZ(`-- Removed model snapshot file: ${J}`);let G=$8(Z,`.qb-migrations.${X}.json`),U=String(Y.state||G);if(y8(U))g0(U),XZ(`-- Removed legacy migration state file: ${U}`);f2(T8($,y.migrationDir))}function f2(Z){if(!y8(Z))return;let $=0,Y=[];for(let X of EJ(Z).filter((J)=>J.endsWith(".sql"))){if(!MJ(Z,X)){Y.push(X);continue}g0($8(Z,X)),XZ(`-- Removed generated migration file: ${X}`),$+=1}if(XZ(`-- Cleaned up ${$} generated migration file${$===1?"":"s"} from migrations directory`),Y.length>0)XZ(`-- Kept ${Y.length} hand-written migration${Y.length===1?"":"s"}: ${Y.slice(0,5).join(", ")}${Y.length>5?`, +${Y.length-5} more`:""}`)}async function cj(Z,$){}async function g2(Z){if(!Z)Z=U9();let $=$8(Z,"generated");if(y8($))try{DJ($,{recursive:!0,force:!0}),XZ("-- Cleared generated directory")}catch(Y){console.error("-- Failed to clear generated directory:",Y)}}async function NJ(Z,$){let X=B8($).createMigrationsTable();try{await Z.unsafe(X).execute(),XZ("-- Migrations table ready")}catch(J){throw console.error("-- Failed to create migrations table:",J),J}}async function p2(Z,$){let Y=B8($);try{return(await Z.unsafe(Y.getExecutedMigrationsQuery()).execute()).map((J)=>J.migration)}catch(X){return console.error("-- Failed to get executed migrations:",X),[]}}async function F7(Z,$,Y){let X=B8(Y);try{XZ(`-- Recording migration: ${$}`),await Z.unsafe(X.recordMigrationQuery(),[$]).execute(),XZ(`-- Successfully recorded migration: ${$}`)}catch(J){throw console.error(`-- Failed to record migration ${$}:`,J),J}}
|
|
445
|
-
export{YZ as a,RX as b,y as c,n$ as d,e,NZ as f,i$ as g,DX as h,y4 as i,r5 as j,t5 as k,d9 as l,TX as m,_6 as n,A0 as o,p8 as p,V6 as q,K6 as r,d8 as s,e8 as t,CH as u,F6 as v,vH as w,U8 as x,B6 as y,E6 as z,JZ as A,fX as B,gX as C,P6 as D,T6 as E,q6 as F,pX as G,x6 as H,h6 as I,b6 as J,f6 as K,dX as L,g6 as M,mX as N,cX as O,p6 as P,d6 as Q,uX as R,m6 as S,c6 as T,nX as U,j0 as V,lX as W,Q0 as X,JU as Y,hZ as Z,o$ as _,r$ as $,t$ as aa,e$ as ba,B8 as ca,pU as da,F0 as ea,dU as fa,mU as ga,b2 as ha,cj as ia,g2 as ja,GU as ka,_U as la,X1 as ma,LU as na,G1 as oa,RU as pa,H1 as qa,A1 as ra,Q1 as sa,qU as ta,kU as ua,xU as va,vU as wa,yU as xa,L1 as ya,fU as za,gU as Aa,B1 as Ba,N1 as Ca,O1 as Da,E1 as Ea,Z3 as Fa,$3 as Ga,k1 as Ha,x1 as Ia,Y3 as Ja,X3 as Ka,b1 as La,f1 as Ma,g1 as Na,p1 as Oa,d1 as Pa,T0 as Qa,m1 as Ra,X2 as Sa,i8 as Ta,O8 as Ua,A3 as Va,W3 as Wa,j3 as Xa,c1 as Ya,u1 as Za,n1 as _a,i1 as $a,l1 as ab,V3 as bb,s1 as cb,J2 as db,L3 as eb,F3 as fb,B3 as gb,R3 as hb,o1 as ib,w3 as jb,C3 as kb,S3 as lb,G7 as mb,Q8 as nb,ZJ as ob,zJ as pb,HJ as qb,AJ as rb,WJ as sb,B2 as tb,r9 as ub,L7 as vb,o3 as wb,r3 as xb,_J as yb,y0 as zb,x8 as Ab,h0 as Bb,f0 as Cb,C2 as Db,a3 as Eb,S2 as Fb,Zj as Gb,KJ as Hb,LJ as Ib,FJ as Jb,N2 as Kb,P2 as Lb};
|