bun-query-builder 0.2.55 → 0.2.58

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.
@@ -1,22 +1,22 @@
1
1
  // @bun
2
- import{Sb as q1,Vb as k1}from"./chunk-7e64yq76.js";import{Xb as t8}from"./chunk-y718nsbf.js";import{oc as pU,pc as rU,qc as z8,rc as sZ}from"./chunk-x8tfs1sw.js";import{existsSync as g0,statSync as p0}from"fs";import{resolve as k9}from"path";import xJ from"process";import{existsSync as hJ,mkdirSync as i2,readdirSync as l2,readFileSync as bJ,writeFileSync as s2}from"fs";import{homedir as H9}from"os";import{dirname as a2,resolve as V8}from"path";import y$ from"process";import{existsSync as d0,statSync as m0}from"fs";import{existsSync as v7,mkdirSync as fJ,readdirSync as gJ,writeFileSync as pJ}from"fs";import{homedir as A9}from"os";import{dirname as c0,resolve as nZ}from"path";import r8 from"process";import{join as dJ,relative as mJ,resolve as u0}from"path";import E$ from"process";import{existsSync as TY,mkdirSync as zz,readdirSync as Hz,writeFileSync as Az}from"fs";import{homedir as K7}from"os";import{dirname as Qz,resolve as uZ}from"path";import v9 from"process";import{join as cJ,relative as uJ,resolve as n0}from"path";import I$ from"process";import{existsSync as qY,mkdirSync as Fz,readdirSync as Bz,writeFileSync as Rz}from"fs";import{dirname as Dz,resolve as M$}from"path";import y7 from"process";import{Buffer as v8}from"buffer";import{createCipheriv as nJ,createDecipheriv as iJ,randomBytes as L7}from"crypto";import{closeSync as F7,createReadStream as i0,createWriteStream as lJ,existsSync as B7,fsyncSync as l0,openSync as s0,writeFileSync as sJ}from"fs";import{access as oJ,constants as o0,mkdir as rJ,readdir as X$,rename as r0,stat as W9,unlink as J$,writeFile as R7}from"fs/promises";import{join as j9}from"path";import fZ from"process";import{pipeline as aJ}from"stream/promises";import{createGzip as a0}from"zlib";import Q9 from"process";import O8 from"process";import{Buffer as B8}from"buffer";import{createCipheriv as tJ,createDecipheriv as eJ,randomBytes as O7}from"crypto";import{closeSync as D7,createReadStream as t0,createWriteStream as ZG,existsSync as G$,fsyncSync as e0,openSync as ZY,writeFileSync as $G}from"fs";import{access as YG,constants as $Y,mkdir as XG,readdir as U$,rename as YY,stat as _9,unlink as z$,writeFile as E7}from"fs/promises";import{isAbsolute as JG,join as V9,resolve as GG}from"path";import QZ from"process";import{pipeline as UG}from"stream/promises";import{createGzip as XY}from"zlib";import K9 from"process";import D8 from"process";import H$ from"process";import{existsSync as A$}from"fs";import{resolve as I7}from"path";import{existsSync as zG}from"fs";import{existsSync as HG,readdirSync as AG}from"fs";import{extname as M7,resolve as JY}from"path";import WG from"process";import{join as jG,relative as QG,resolve as GY}from"path";import w$ from"process";import{Buffer as R8}from"buffer";import{createCipheriv as _G,createDecipheriv as VG,randomBytes as w7}from"crypto";import{closeSync as C7,createReadStream as UY,createWriteStream as KG,existsSync as W$,fsyncSync as zY,openSync as HY,writeFileSync as LG}from"fs";import{access as FG,constants as AY,mkdir as BG,readdir as j$,rename as WY,stat as L9,unlink as Q$,writeFile as S7}from"fs/promises";import{isAbsolute as RG,join as F9,resolve as OG}from"path";import _Z from"process";import{pipeline as DG}from"stream/promises";import{createGzip as jY}from"zlib";import B9 from"process";import E8 from"process";import V$ from"process";import{existsSync as K$}from"fs";import{resolve as wY}from"path";import{existsSync as d5}from"fs";class CY{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(!g0(Z))return!0;return p0(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=g0(Y)?p0(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 SY{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 PY(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 vJ(Z){return PY(Z).flatMap((Y)=>NY.map((X)=>k9(Z.directory,`${Y}${X}`)))}function yJ(Z={}){let $=k9(Z.cwd||xJ.cwd());return Array.from(new Set([$,k9($,"config"),k9($,".config"),Z.configDir?k9($,Z.configDir):void 0].filter((Y)=>Boolean(Y))))}function MG(Z,$){this[Z]=IG.bind(null,$)}class l7{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(!d0(Z))return!0;return m0(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=d0(Y)?m0(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 s7{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 SG(Z,$={}){let X=Object.keys($).sort().map((J)=>`${J}:${$[J]}`).join("|");return X?`${Z}:${X}`:Z}function NG(Z,$){try{return JSON.stringify(Z)===JSON.stringify($)}catch{return Z===$}}function PG(Z){return Z.getStats().size*2}function o7(Z,$){if(Array.isArray($)&&Array.isArray(Z)&&$.length===2&&Z.length===2&&MZ($[0])&&"id"in $[0]&&$[0].id===3&&MZ($[1])&&"id"in $[1]&&$[1].id===4)return $;if(MZ($)&&MZ(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(MZ(Z)&&"arr"in Z&&Array.isArray(Z.arr)&&MZ($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&Z.length>0&&MZ($[0])&&MZ(Z[0])){let X=[...$];for(let J of Z)if(MZ(J)&&"name"in J){if(!X.find((U)=>MZ(U)&&("name"in U)&&U.name===J.name))X.push(J)}else if(MZ(J)&&"path"in J){if(!X.find((U)=>MZ(U)&&("path"in U)&&U.path===J.path))X.push(J)}else if(!X.some((G)=>C$(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(!MZ($)||!MZ(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(MZ(J)&&MZ(Y[X]))Y[X]=o7(Y[X],J);else if(Array.isArray(J)&&Array.isArray(Y[X]))if(J.length>0&&Y[X].length>0&&MZ(J[0])&&MZ(Y[X][0])){let G=[...J];for(let U of Y[X])if(MZ(U)&&"name"in U){if(!G.find((z)=>MZ(z)&&("name"in z)&&z.name===U.name))G.push(U)}else if(MZ(U)&&"path"in U){if(!G.find((z)=>MZ(z)&&("path"in z)&&z.path===U.path))G.push(U)}else if(!G.some((H)=>C$(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 C$(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(!C$(Z[Y],$[Y]))return!1;return!0}if(MZ(Z)&&MZ($)){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(!C$(Z[J],$[J]))return!1}return!0}return!1}function MZ(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}async function TG(Z,$){if(!qY(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 o7($,X)}catch{return null}}catch{return null}}async function qG({name:Z="",cwd:$,defaultConfig:Y}){let X=$||y7.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=M$(X,`${U}${H}`),A=await TG(z,Y);if(A!==null)return A}try{let U=M$(X,"package.json");if(qY(U)){let z=(await import(U))[Z];if(z&&typeof z==="object"&&!Array.isArray(z))try{return o7(Y,z)}catch{}}}catch{}return Y}function kG(Z,$={}){let Y=I$.cwd();while(Y.includes("storage"))Y=n0(Y,"..");let X=n0(Y,Z||"");if($?.relative)return uJ(I$.cwd(),X);return X}async function xG(){try{let Z=await qG({name:"clarity",defaultConfig:F$,cwd:I$.cwd(),endpoint:"",headers:{}});return{...F$,...Z}}catch{return F$}}function CZ(){if(O8.env.NODE_ENV==="test"||O8.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vG(){if(O8.env.NODE_ENV==="test"||O8.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof O8<"u"){let Z=O8.type;if(Z==="renderer"||Z==="worker")return!1;return!!(O8.versions&&(O8.versions.node||O8.versions.bun))}return!1}class xY{async format(Z){let $=await vG(),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 S${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={...b7},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new xY,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??fZ.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{...B$,...Z.fingersCrossed};if(!Z.fingersCrossedEnabled)return null;if(!Z.fingersCrossed)return{...B$};return{...B$,...Z.fingersCrossed}}normalizeOptions(Z){let $={format:"json",level:"info",logDirectory:b7.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 oJ(this.config.logDirectory,o0.F_OK|o0.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await rJ(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:v8.from(Z);try{if(!B7(this.currentLogFile))await R7(this.currentLogFile,"",{mode:420});if(J=s0(this.currentLogFile,"a",420),sJ(J,z,{flag:"a"}),l0(J),J!==void 0)F7(J),J=void 0;if((await W9(this.currentLogFile)).size===0){if(await R7(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 R=H*2**G;await new Promise((O)=>setTimeout(O,R)),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{F7(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(CZ())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 L7(16).toString("hex")}generateKey(){return L7(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=L7(16),X=nJ("aes-256-gcm",$,Y),J=v8.concat([X.update(Z,"utf8"),X.final()]),G=X.getAuthTag();return{encrypted:v8.concat([Y,J,G]),iv:Y}}async compressData(Z){return new Promise(($,Y)=>{let X=a0(),J=[];X.on("data",(G)=>J.push(G)),X.on("end",()=>$(v8.from(v8.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(CZ())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 X$(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 r0(Y,H),$.compress)try{let z=`${H}.gz`;await this.compressLogFile(H,z),await J$(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 R7(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 r0(Y,G)}if(this.currentLogFile=X,$.maxFiles){let G=(await X$(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,H)=>H.localeCompare(U));for(let U of G.slice($.maxFiles))await J$(j9(this.config.logDirectory,U))}}}async compressLogFile(Z,$){let Y=i0(Z),X=lJ($),J=a0();await aJ(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()})),B7(this.currentLogFile))try{let Z=s0(this.currentLogFile,"r+");l0(Z),F7(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(!CZ()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await X$(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await J$(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?EZ.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=fZ.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} ${EZ.cyan(J)}`;if(!U)return A.trim();let W=H(A).trim().length,Q=H($).length,R=Math.max(1,z-2-W-Q);return`${A.trim()}${" ".repeat(R)}${$}`}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&&!CZ()){let A=cY[Z],W=this.options.showTags!==!1&&this.name?EZ.gray(this.formatTag(this.name)):"",Q;switch(Z){case"debug":Q=this.formatConsoleMessage({timestamp:J,icon:A,tag:W,message:EZ.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:EZ.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 R=H.split(`
3
- `);for(let O of R)if(O.trim()&&!O.includes(U))console.error(this.formatConsoleMessage({timestamp:J,message:EZ.gray(` ${O}`),level:Z,showTimestamp:!1}))}break}}else if(!CZ()){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}
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
4
  `;if(H)z+=`${H}
5
- `;z=z.replace(this.ANSI_PATTERN,""),await this.writeToFile(z)}time(Z){let $=performance.now();if(this.fancy&&!CZ()){let Y=this.options.showTags!==!1&&this.name?EZ.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:EZ.blue("\u25D0"),tag:Y,message:`${EZ.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&&!CZ()){let W=this.options.showTags!==!1&&this.name?EZ.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:H,icon:EZ.green("\u2713"),tag:W,message:`${G}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!CZ())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 S$($,{...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(CZ())throw Error("createReadStream is not supported in browser environments");if(!B7(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return i0(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=v8.isBuffer(Z)?Z:v8.from(Z,"base64"),J=X.slice(0,16),G=X.slice(-16),U=X.slice(16,-16),H=iJ("aes-256-gcm",Y,J);return H.setAuthTag(G),v8.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 CZ()}isServerMode(){return!CZ()}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&&!CZ()){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:EZ.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:EZ.cyan(H)})),A.forEach((W)=>console.error(this.formatConsoleMessage({timestamp:Y,message:EZ.cyan(W),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:EZ.cyan(z),showTimestamp:!1}))}else if(!CZ())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(CZ())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${EZ.cyan("?")} ${Z} (y/n) `);let Y=(X)=>{let J=X.toString().trim().toLowerCase();fZ.stdin.removeListener("data",Y);try{if(typeof fZ.stdin.setRawMode==="function")fZ.stdin.setRawMode(!1)}catch{}fZ.stdin.pause(),console.error(""),$(J==="y"||J==="yes")};try{if(typeof fZ.stdin.setRawMode==="function")fZ.stdin.setRawMode(!0)}catch{}fZ.stdin.resume(),fZ.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&&!CZ()){let U=this.options.showTags!==!1&&this.name?EZ.gray(this.formatTag(this.name)):"",H=EZ.blue("\u25D0");console.error(`${H} ${U} ${EZ.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||CZ()||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||CZ())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||CZ())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||CZ())return;fZ.stdout.write(`${"\r".padEnd(fZ.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||CZ()||!fZ.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=EZ.green("\u2501".repeat(X)),U=EZ.gray("\u2501".repeat(J)),H=`[${G}${U}]`,z=`${Y}%`.padStart(4),A=Z.message?` ${Z.message}`:"",W=$||Y===100?EZ.green("\u2713"):EZ.blue("\u25B6"),Q=this.options.showTags!==!1&&this.name?` ${EZ.gray(this.formatTag(this.name))}`:"",R=`\r${W}${Q} ${H} ${z}${A}`,O=fZ.stdout.columns||80,N=" ".repeat(Math.max(0,O-R.replace(this.ANSI_PATTERN,"").length));if(Z.lastRenderedLine=`${R}${N}`,fZ.stdout.write(Z.lastRenderedLine),$)fZ.stdout.write(`
10
- `)}finishProgressBar(Z,$){if(!this.enabled||!this.fancy||CZ()||!fZ.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(CZ()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await X$(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 J$(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 L$(Z,$){if(Array.isArray($)&&Array.isArray(Z)&&$.length===2&&Z.length===2&&FZ($[0])&&"id"in $[0]&&$[0].id===3&&FZ($[1])&&"id"in $[1]&&$[1].id===4)return $;if(FZ($)&&FZ(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(FZ(Z)&&"arr"in Z&&Array.isArray(Z.arr)&&FZ($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&Z.length>0&&FZ($[0])&&FZ(Z[0])){let X=[...$];for(let J of Z)if(FZ(J)&&"name"in J){if(!X.find((U)=>FZ(U)&&("name"in U)&&U.name===J.name))X.push(J)}else if(FZ(J)&&"path"in J){if(!X.find((U)=>FZ(U)&&("path"in U)&&U.path===J.path))X.push(J)}else if(!X.some((G)=>N$(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(!FZ($)||!FZ(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(FZ(J)&&FZ(Y[X]))Y[X]=L$(Y[X],J);else if(Array.isArray(J)&&Array.isArray(Y[X]))if(J.length>0&&Y[X].length>0&&FZ(J[0])&&FZ(Y[X][0])){let G=[...J];for(let U of Y[X])if(FZ(U)&&"name"in U){if(!G.find((z)=>FZ(z)&&("name"in z)&&z.name===U.name))G.push(U)}else if(FZ(U)&&"path"in U){if(!G.find((z)=>FZ(z)&&("path"in z)&&z.path===U.path))G.push(U)}else if(!G.some((H)=>N$(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 r7(Z,$,Y="replace"){if($===null||$===void 0)return Z;if(Array.isArray($))return Y==="replace"?$:L$(Z,$);if(Array.isArray(Z))return Y==="replace"?$:L$(Z,$);if(!FZ($)||!FZ(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]=L$(U,G);else if(FZ(G)&&FZ(U))X[J]=r7(U,G,Y);else X[J]=G}return X}function N$(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(!N$(Z[Y],$[Y]))return!1;return!0}if(FZ(Z)&&FZ($)){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(!N$(Z[J],$[J]))return!1}return!0}return!1}function FZ(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}async function _$(Z,$,Y="replace"){if(!TY(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 r7($,J,Y)}catch{return null}}catch{return null}}function yG(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],R=(_)=>_.replace(/([A-Z])/g,"_$1").toUpperCase(),O=`${X}_${Q.map(R).join("_")}`,N=`${X}_${Q.map((_)=>_.toUpperCase()).join("_")}`;if(Y)pZ.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 _=v9.env[O]||v9.env[N];if(_!==void 0){if(Y)pZ.info(`Using environment variable ${_?O:N} for config ${Z}.${Q.join(".")}`);if(typeof W==="number")z[A]=Number(_);else if(typeof W==="boolean")z[A]=_.toLowerCase()==="true";else if(Array.isArray(W))try{let F=JSON.parse(_);if(Array.isArray(F))z[A]=F;else z[A]=_.split(",").map((L)=>L.trim())}catch{z[A]=_.split(",").map((F)=>F.trim())}else z[A]=_}}}return z}return G(J)}async function hG({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)?yG(Z,J,G):J,A=Y||v9.cwd(),W=[".ts",".js",".mjs",".cjs",".json"];if(G)pZ.info(`Loading configuration for "${Z}"${$?` (alias: "${$}")`:""} from ${A}`);let Q=[Z,`.${Z}`].filter(Boolean),R=[`${Z}.config`,`.${Z}.config`].filter(Boolean),O=$?[$,`.${$}`]:[],N=$?[`${$}.config`,`.${$}.config`]:[],_=Array.from(new Set([A,uZ(A,"config"),uZ(A,".config"),X?uZ(A,X):void 0].filter(Boolean)));for(let F of _){if(G)pZ.info(`Searching for configuration in: ${F}`);let K=[uZ(A,"config"),uZ(A,".config")].concat(X?[uZ(A,X)]:[]).includes(F)?[...Q,...R,...O,...N]:[...R,...Q,...N,...O];for(let I of K)for(let B of W){let x=uZ(F,`${I}${B}`),P=await _$(x,z,H);if(P!==null){if(G)pZ.success(`Configuration loaded from: ${x}`);return P}}}if(Z){let F=uZ(K7(),".config",Z),L=["config",`${Z}.config`];if($)L.push(`${$}.config`);if(G)pZ.info(`Checking user config directory: ${F}`);for(let K of L)for(let I of W){let B=uZ(F,`${K}${I}`),x=await _$(B,z,H);if(x!==null){if(G)pZ.success(`Configuration loaded from user config directory: ${B}`);return x}}}if(Z){let F=uZ(K7(),".config"),L=[`.${Z}.config`];if($)L.push(`.${$}.config`);if(G)pZ.info(`Checking user config directory for dotfile configs: ${F}`);for(let K of L)for(let I of W){let B=uZ(F,`${K}${I}`),x=await _$(B,z,H);if(x!==null){if(G)pZ.success(`Configuration loaded from user config directory dotfile: ${B}`);return x}}}if(Z){let F=K7(),L=[`.${Z}.config`,`.${Z}`];if($)L.push(`.${$}.config`),L.push(`.${$}`);if(G)pZ.info(`Checking user home directory for dotfile configs: ${F}`);for(let K of L)for(let I of W){let B=uZ(F,`${K}${I}`),x=await _$(B,z,H);if(x!==null){if(G)pZ.success(`Configuration loaded from user home directory: ${B}`);return x}}}try{let F=uZ(A,"package.json");if(TY(F)){let L=await import(F),K=L[Z];if(!K&&$){if(K=L[$],K&&G)pZ.success(`Using alias "${$}" configuration from package.json`)}if(K&&typeof K==="object"&&!Array.isArray(K))try{if(G)pZ.success(`Configuration loaded from package.json: ${K===L[Z]?Z:$}`);return r7(z,K,H)}catch(I){if(G)pZ.warn("Failed to merge package.json config:",I)}}}catch(F){if(G)pZ.warn("Failed to load package.json:",F)}if(G)pZ.info(`No configuration found for "${Z}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return z}function bG(Z,$={}){let Y=E$.cwd();while(Y.includes("storage"))Y=u0(Y,"..");let X=u0(Y,Z||"");if($?.relative)return mJ(E$.cwd(),X);return X}async function fG(){try{let Z=await hG({name:"clarity",alias:"logging",defaultConfig:R$,cwd:E$.cwd()});return{...R$,...Z||{}}}catch{return R$}}function kZ(){if(D8.env.NODE_ENV==="test"||D8.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function gG(){if(D8.env.NODE_ENV==="test"||D8.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D8<"u"){let Z=D8.type;if(Z==="renderer"||Z==="worker")return!1;return!!(D8.versions&&(D8.versions.node||D8.versions.bun))}return!1}class vY{async format(Z){let $=await gG(),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 P${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={...f7},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new vY,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{...O$,...Z.fingersCrossed};if(!Z.fingersCrossedEnabled)return null;if(!Z.fingersCrossed)return{...O$};return{...O$,...Z.fingersCrossed}}normalizeOptions(Z){let $={format:"json",level:"info",logDirectory:f7.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!kZ()&&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 YG(this.config.logDirectory,$Y.F_OK|$Y.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await XG(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:B8.from(Z);try{if(!G$(this.currentLogFile))await E7(this.currentLogFile,"",{mode:420});if(J=ZY(this.currentLogFile,"a",420),$G(J,z,{flag:"a"}),e0(J),J!==void 0)D7(J),J=void 0;if((await _9(this.currentLogFile)).size===0){if(await E7(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 R=H*2**G;await new Promise((O)=>setTimeout(O,R)),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{D7(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(kZ())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 O7(16).toString("hex")}generateKey(){return O7(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=O7(16),X=tJ("aes-256-gcm",$,Y),J=B8.isBuffer(Z)?Z:B8.from(Z,"utf8"),G=X.update(J),U=X.final(),H=G.length+U.length,z=X.getAuthTag(),A=B8.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=XY(),J=[];X.on("data",(G)=>J.push(G)),X.on("end",()=>$(B8.from(B8.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(kZ())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 U$(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 YY(Y,H),$.compress)try{let z=`${H}.gz`;await this.compressLogFile(H,z),await z$(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 E7(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 YY(Y,G)}if(this.currentLogFile=X,$.maxFiles){let G=(await U$(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,H)=>H.localeCompare(U));for(let U of G.slice($.maxFiles))await z$(V9(this.config.logDirectory,U))}}}async compressLogFile(Z,$){let Y=t0(Z),X=ZG($),J=XY();await UG(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()})),G$(this.currentLogFile))try{let Z=ZY(this.currentLogFile,"r+");e0(Z),D7(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(!kZ()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await U$(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await z$(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()?VZ.gray(Z.toLocaleTimeString()):Z.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||kZ())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} ${VZ.cyan(J)}`;if(!U)return A.trim();let W=H(A).trim().length,Q=H($).length,R=Math.max(1,z-2-W-Q);return`${A.trim()}${" ".repeat(R)}${$}`}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=VZ.underline(VZ.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)=>VZ.bgGray(X)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,X)=>VZ.bold(X)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,X)=>VZ.italic(X)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,X)=>VZ.italic(X)),$=$.replace(/~([^~]+)~/g,(Y,X)=>VZ.strikethrough(X)),$}supportsHyperlinks(){if(kZ())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(JG($)||$.startsWith("./")||$.startsWith("../"))$=GG($);else return null;return G$($)?$: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?"":uY[Z],R=this.options.showTags!==!1&&this.name?VZ.gray(this.formatTag(this.name)):"",O;switch(Z){case"debug":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:VZ.gray(z),level:Z}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:VZ.green(z),level:Z}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.error(O),H){let N=H.split(`
11
- `);for(let _ of N)if(_.trim()&&!_.includes(U))console.error(this.formatConsoleMessage({timestamp:J,message:VZ.gray(` ${_}`),level:Z,showTimestamp:!1}))}break}}else if(!kZ()){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}
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
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()&&!kZ()&&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()&&!kZ()&&QZ.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(H)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,H)},interrupt:(H,z="info")=>{if(!kZ()&&QZ.stdout.isTTY)QZ.stdout.write(`
14
- `);if(this[z==="warning"?"warn":z](H),this.activeProgressBar&&this.shouldStyleConsole()&&!kZ()&&QZ.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Z){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?VZ.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:this.options.showIcons===!1?"":VZ.blue("\u25D0"),tag:Y,message:`${VZ.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?VZ.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:H,icon:this.options.showIcons===!1?"":VZ.green("\u2713"),tag:W,message:`${G}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!kZ())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 P$($,{...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(kZ())throw Error("createReadStream is not supported in browser environments");if(!G$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return t0(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=B8.isBuffer(Z)?Z:B8.from(Z,"base64"),J=X.subarray(0,16),G=X.subarray(X.length-16),U=X.subarray(16,X.length-16),H=eJ("aes-256-gcm",Y,J);H.setAuthTag(G);let z=H.update(U),A=H.final(),W=z.length+A.length,Q=B8.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 kZ()}isServerMode(){return!kZ()}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((R)=>R.length))+2,A=`\u250C${"\u2500".repeat(z)}\u2510`,W=`\u2514${"\u2500".repeat(z)}\u2518`,Q=H.map((R)=>{return this.formatConsoleMessage({timestamp:Y,message:VZ.cyan(R),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:VZ.cyan(A),showTimestamp:!1})),Q.forEach((R)=>console.error(R)),console.error(this.formatConsoleMessage({timestamp:Y,message:VZ.cyan(W),showTimestamp:!1}))}else if(!kZ())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(kZ())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${VZ.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 R=$[A++];switch(Q){case"s":return String(R);case"d":case"i":return Number(R).toString();case"j":case"o":return JSON.stringify(R,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?VZ.gray(this.formatTag(this.name)):"",A=this.options.showIcons===!1?"":`${VZ.blue("\u25D0")} `;console.error(`${A}${z} ${VZ.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=VZ.green("\u2501".repeat(X)),U=VZ.gray("\u2501".repeat(J)),H=`[${G}${U}]`,z=`${Y}%`.padStart(4),A=Z.message?` ${Z.message}`:"",W=this.options.showIcons===!1?"":$||Y===100?VZ.green("\u2713"):VZ.blue("\u25B6"),Q=this.options.showTags!==!1&&this.name?` ${VZ.gray(this.formatTag(this.name))}`:"",R=`\r${W}${Q} ${H} ${z}${A}`,O=QZ.stdout.columns||80,N=" ".repeat(Math.max(0,O-R.replace(this.ANSI_PATTERN,"").length));if(Z.lastRenderedLine=`${R}${N}`,QZ.stdout.write(Z.lastRenderedLine),$)QZ.stdout.write(`
19
- `)}finishProgressBar(Z,$){if(!this.enabled||!this.fancy||kZ()||!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(kZ()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await U$(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 z$(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 yY(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 hY(Z){return Z instanceof aZ}function pG(Z){return Z instanceof T$}function dG(Z){if(hY(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 h${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 b9.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=H$.env[z]||(A?H$.env[A]:void 0);if(W!==void 0){if(X.verbose){let Q=H$.env[z]?z:A}try{Z[J]=this.parseEnvironmentValue(W,typeof G,z,X.customParsers,X.configName)}catch(Q){if(Q instanceof q$)throw Q;throw y8.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 y8.envVar(Y,Z,`${$} (via ${G.name} parser)`,J)}return Z}getEnvironmentVariables(Z){let $={},Y=Z.toUpperCase();for(let[X,J]of Object.entries(H$.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 ${$}:
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
20
 
21
21
  `;for(let X of Z)Y+=`${X.key}
22
22
  `,Y+=` Type: ${X.type}
@@ -28,25 +28,25 @@ import{Sb as q1,Vb as k1}from"./chunk-7e64yq76.js";import{Xb as t8}from"./chunk-
28
28
  `;Y+=`| Variable | Type | Description | Example |
29
29
  `,Y+=`|----------|------|-------------|----------|
30
30
  `;for(let X of Z)Y+=`| \`${X.key}\` | ${X.type} | ${X.description} | \`${X.example}\` |
31
- `;return Y}}function mG(Z,$){let Y=dY("process");if(typeof Y>"u"||!Y.env)return $;let X=Y.env[Z];return X!==void 0?X:$}function bY(Z,$,Y={}){return fY(Z,$,Y,new WeakMap)}function fY(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 gY(Z,$,J,X);if(!Y8($)||!Y8(Z))return $;return iG(Z,$,Y,X)}function gY(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 cG(Z,$);case"smart":return uG(Z,$,X);default:return $}return $}function cG(Z,$){let Y=[...$];for(let X of Z)if(!Y.some((J)=>h7(J,X)))Y.push(X);return Y}function uG(Z,$,Y){if($.length===0)return Z;if(Z.length===0)return $;if(Y8($[0])&&Y8(Z[0]))return nG(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 nG(Z,$,Y){let X=[...$];for(let J of Z){if(!Y8(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)=>Y8(A)&&(H in A)&&A[H]===J[H])){U=!0;break}}if(!U)X.push(J)}return X}function iG(Z,$,Y,X){let J=$;if(Y8(J)&&X.has(J))return X.get(J);let G={...Z};if(Y8(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(Y8(H)&&Y8(z))G[U]=fY(z,H,Y,X);else if(Array.isArray(H)||Array.isArray(z))G[U]=gY(z,H,Y.arrayMergeMode||"smart",X);else G[U]=H}return G}function a7(Z,$,Y="replace"){return bY(Z,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function h7(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(!h7(Z[Y],$[Y]))return!1;return!0}if(Y8(Z)&&Y8($)){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(!h7(Z[J],$[J]))return!1}return!0}return!1}function Y8(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}class b${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(!A$(Z))return null;try{let A=`?t=${Date.now()}`,W=await import(Z+A),Q=W.default||W,R="default"in W,O=Object.keys(W).length>0;if(!R&&!O)throw new y9(Z,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new y9(Z,Error("Configuration must export a valid object"),"unknown");let F={config:a7($,Q,X),source:{type:"file",path:Z,priority:100,timestamp:new Date}};if(J)R9.setWithFileCheck("file",F,Z,G);return F}catch(A){throw A instanceof Error?y8.configLoad(Z,A):y8.configLoad(Z,Error(String(A)))}};if(U)return b9.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(I7($,`${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 yY(async()=>{return A$(Z)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Z,$,Y){let X=[];if(!A$(Z))return X;if($||Y){let J=this.generateNamePatterns($||"",Y);for(let G of J)for(let U of this.extensions){let H=I7(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=I7(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(!A$(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 t7{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=[],R={stopOnFirstError:X,validateRequired:J,validateTypes:G,customRules:U,trackPerformance:H,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(Z,$,R);else if(Array.isArray($))return this.validateWithRules(Z,[...$,...U],R);else return this.validateWithJSONSchema(Z,$,R)}catch(O){return W.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:W,warnings:Q}}};if(H)return await b9.track("validateConfiguration",A);return A()}async validateWithSchemaFile(Z,$,Y){try{if(!zG($))throw new h9($,[{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 h9($,[{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:iY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class e7{fileLoader=new b$;envProcessor=new h$;validator=new t7;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")),R=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(A&&(R||W))throw z;if(Q&&(!A||!R))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)U8.warn(`Slow configuration loading detected: ${z.duration}ms for ${U.name}`);H.metrics=z}return H}catch(H){let z=Date.now()-$;throw U8.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(),R=[],O=await this.loadLocalConfiguration(X,J,Q,U,H,A,W,z,Y);if(O)return R.push(...this.getLocalSearchPaths(X,J,Q,U)),this.finalizeResult(O,R,z,X,W);let N=await this.loadHomeConfiguration(X,J,H,A,W,z);if(N)return R.push(...this.getHomeSearchPaths(X,J)),this.finalizeResult(N,R,z,X,W);let _=await this.loadPackageJsonConfiguration(X,J,Q,H,A,W,z);if(_)return R.push(nZ(Q,"package.json")),this.finalizeResult(_,R,z,X,W);if(R.push(...this.getAllSearchPaths(X,J,Q,U)),$)throw y8.configNotFound(X,R,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?x9(Z,J,U):J,W=this.getLocalDirectories(Y,X);for(let Q of W){if(U)U8.info(`Searching for configuration in: ${Q}`);let R=this.fileLoader.generateConfigPaths(Z,Q,$),O=await this.fileLoader.tryLoadFromPaths(R,A,{arrayStrategy:G,verbose:U,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(O){if(U)U8.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=[nZ(A9(),".config",Z),nZ(A9(),".config"),A9()];for(let z of H){if(J)U8.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)U8.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=nZ(Y,"package.json");if(!v7(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)U8.success(`Configuration loaded from package.json: ${Q}`);return{config:a7(H,W,J),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(G)U8.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 y8.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,nZ(Z,"config"),nZ(Z,".config"),$?nZ(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(nZ(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=[nZ(A9(),".config",Z),nZ(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 QY(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 lG(Z){return I8.loadConfig({...Z,__strictErrorHandling:!0})}async function pY(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 I8.loadConfig(Z);else X=await I8.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)U8.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 I8.applyEnvironmentVariables(H.name||"",$,!0,H.verbose||!1))?.config??$;return $}}async function sG(Z={defaultConfig:{}}){if(typeof Z==="string"){let{cwd:$}=await import("process");try{return(await I8.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"&&QY(Y)))return(await I8.applyEnvironmentVariables(Z,{},!0,!1)).config;throw Y}}try{return(await I8.loadConfig({...Z,cwd:Z.cwd||r8.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&QY($)))return(await I8.applyEnvironmentVariables(Z.name||"",Z.defaultConfig||{},Z.checkEnv!==!1,Z.verbose||!1)).config;throw $}}async function oG(Z,$,Y="replace"){let X=new b$;try{let J=await X.loadFromPath(Z,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return J?J.config:null}catch{return null}}function x9(Z,$,Y=!1){let X=new h$,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],R=[`${J}_${Q.join("_").toUpperCase()}`,`${J}_${Q.map((_)=>_.toUpperCase()).join("")}`,`${J}_${Q.map((_)=>_.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,N;for(let _ of R)if(O=r8.env[_],O!==void 0){N=_;break}if(O!==void 0&&N)if(typeof W==="boolean")z[A]=["true","1","yes"].includes(O.toLowerCase());else if(typeof W==="number"){let _=Number(O);if(!Number.isNaN(_))z[A]=_}else if(Array.isArray(W))try{z[A]=JSON.parse(O)}catch{z[A]=O.split(",").map((_)=>_.trim())}else z[A]=O;else if(W&&typeof W==="object"&&!Array.isArray(W))z[A]=G(W,Q)}return z}return G($)}function rG(Z){let $=nZ(r8.cwd(),Z.configDir),Y=nZ(r8.cwd(),Z.generatedDir),X=nZ(Y,"config-types.ts");if(!v7(c0(X)))fJ(c0(X),{recursive:!0,mode:511});let J=v7($)?gJ($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],G=`// Generated by bunfig v${w5}
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
32
  export type ConfigNames = ${J.length?`'${J.join("' | '")}'`:"string"}
33
- `;pJ(X,G,{mode:438})}function aG(Z){let $=null,Y=null,X=()=>{if(!Y)Y=pY(Z).then((G)=>{return $=G,G},(G)=>{let U="defaultConfig"in Z?Z.defaultConfig:{};if($=U,"verbose"in Z&&Z.verbose)U8.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 tG(Z){let $=JY(WG.cwd(),Z?.configDir||"./config");function Y(){if(!HG($))return[];let J=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),G=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=AG($).filter((z)=>J.has(M7(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=M7(A).toLowerCase(),Q=H.get(z);if(!Q){H.set(z,A);continue}let R=M7(Q).toLowerCase();if(G.indexOf(W)<G.indexOf(R))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=JY($,A.file).replace(/\\/g,"/");return` '${A.base}': typeof import('${W}').default`}).join(`,
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
35
  `)}
36
36
  }`:"Record<string, any>";return`export type ConfigNames = ${U}
37
37
  export type ConfigByName = ${H}
38
38
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
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 S5(Z,$={}){let Y=w$.cwd();while(Y.includes("storage"))Y=GY(Y,"..");let X=GY(Y,Z||"");if($?.relative)return QG(w$.cwd(),X);return X}function vZ(){if(E8.env.NODE_ENV==="test"||E8.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function P5(){if(E8.env.NODE_ENV==="test"||E8.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof E8<"u"){let Z=E8.type;if(Z==="renderer"||Z==="worker")return!1;return!!(E8.versions&&(E8.versions.node||E8.versions.bun))}return!1}class rY{async format(Z){let $=await P5(),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 f${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={...k$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new rY,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{...k7,...Z.fingersCrossed};if(!Z.fingersCrossedEnabled)return null;if(!Z.fingersCrossed)return{...k7};return{...k7,...Z.fingersCrossed}}normalizeOptions(Z){let $={format:"json",level:"info",logDirectory:k$.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!vZ()&&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 FG(this.config.logDirectory,AY.F_OK|AY.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await BG(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:R8.from(Z);try{if(!W$(this.currentLogFile))await S7(this.currentLogFile,"",{mode:420});if(J=HY(this.currentLogFile,"a",420),LG(J,z,{flag:"a"}),zY(J),J!==void 0)C7(J),J=void 0;if((await L9(this.currentLogFile)).size===0){if(await S7(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 R=H*2**G;await new Promise((O)=>setTimeout(O,R)),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{C7(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(vZ())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 w7(16).toString("hex")}generateKey(){return w7(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=w7(16),X=_G("aes-256-gcm",$,Y),J=R8.isBuffer(Z)?Z:R8.from(Z,"utf8"),G=X.update(J),U=X.final(),H=G.length+U.length,z=X.getAuthTag(),A=R8.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=jY(),J=[];X.on("data",(G)=>J.push(G)),X.on("end",()=>$(R8.from(R8.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(vZ())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 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 L9(Y).catch(()=>null))try{if(await WY(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 S7(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 WY(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$(F9(this.config.logDirectory,U))}}}async compressLogFile(Z,$){let Y=UY(Z),X=KG($),J=jY();await DG(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=HY(this.currentLogFile,"r+");zY(Z),C7(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(!vZ()&&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$(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||vZ())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,R=Math.max(1,z-2-W-Q);return`${A.trim()}${" ".repeat(R)}${$}`}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(vZ())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(RG($)||$.startsWith("./")||$.startsWith("../"))$=OG($);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){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?"":v5[Z],R=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:R,message:LZ.gray(z),level:Z}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:LZ.green(z),level:Z}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.error(O),H){let N=H.split(`
41
- `);for(let _ of N)if(_.trim()&&!_.includes(U))console.error(this.formatConsoleMessage({timestamp:J,message:LZ.gray(` ${_}`),level:Z,showTimestamp:!1}))}break}}else if(!vZ()){if(console.error(`${G} ${this.environment}.${Z.toUpperCase()}: ${U}`),H)console.error(H)}let W=`${G} ${this.environment}.${Z.toUpperCase()}: ${A}
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
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()&&!vZ()&&_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()&&!vZ()&&_Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(H)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,H)},interrupt:(H,z="info")=>{if(!vZ()&&_Z.stdout.isTTY)_Z.stdout.write(`
44
- `);if(this[z==="warning"?"warn":z](H),this.activeProgressBar&&this.shouldStyleConsole()&&!vZ()&&_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(!vZ())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 f$($,{...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(vZ())throw Error("createReadStream is not supported in browser environments");if(!W$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return UY(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=R8.isBuffer(Z)?Z:R8.from(Z,"base64"),J=X.subarray(0,16),G=X.subarray(X.length-16),U=X.subarray(16,X.length-16),H=VG("aes-256-gcm",Y,J);H.setAuthTag(G);let z=H.update(U),A=H.final(),W=z.length+A.length,Q=R8.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 vZ()}isServerMode(){return!vZ()}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((R)=>R.length))+2,A=`\u250C${"\u2500".repeat(z)}\u2510`,W=`\u2514${"\u2500".repeat(z)}\u2518`,Q=H.map((R)=>{return this.formatConsoleMessage({timestamp:Y,message:LZ.cyan(R),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:LZ.cyan(A),showTimestamp:!1})),Q.forEach((R)=>console.error(R)),console.error(this.formatConsoleMessage({timestamp:Y,message:LZ.cyan(W),showTimestamp:!1}))}else if(!vZ())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(vZ())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 R=$[A++];switch(Q){case"s":return String(R);case"d":case"i":return Number(R).toString();case"j":case"o":return JSON.stringify(R,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))}`:"",R=`\r${W}${Q} ${H} ${z}${A}`,O=_Z.stdout.columns||80,N=" ".repeat(Math.max(0,O-R.replace(this.ANSI_PATTERN,"").length));if(Z.lastRenderedLine=`${R}${N}`,_Z.stdout.write(Z.lastRenderedLine),$)_Z.stdout.write(`
49
- `)}finishProgressBar(Z,$){if(!this.enabled||!this.fancy||vZ()||!_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(vZ()){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=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 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 y5(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 $0{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 i7.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=V$.env[z]||(A?V$.env[A]:void 0);if(W!==void 0){if(X.verbose){let Q=V$.env[z]?z:A}try{Z[J]=this.parseEnvironmentValue(W,typeof G,z,X.customParsers,X.configName)}catch(Q){if(Q instanceof Z0)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(V$.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 ${$}:
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
50
 
51
51
  `;for(let X of Z)Y+=`${X.key}
52
52
  `,Y+=` Type: ${X.type}
@@ -58,47 +58,47 @@ export type ConfigOf = Config
58
58
  `;Y+=`| Variable | Type | Description | Example |
59
59
  `,Y+=`|----------|------|-------------|----------|
60
60
  `;for(let X of Z)Y+=`| \`${X.key}\` | ${X.type} | ${X.description} | \`${X.example}\` |
61
- `;return Y}}function h5(Z,$,Y={}){return JX(Z,$,Y,new WeakMap)}function JX(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 GX(Z,$,J,X);if(!X8($)||!X8(Z))return $;return p5(Z,$,Y,X)}function GX(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 b5(Z,$);case"smart":return f5(Z,$,X);default:return $}return $}function b5(Z,$){let Y=[...$];for(let X of Z)if(!Y.some((J)=>n7(J,X)))Y.push(X);return Y}function f5(Z,$,Y){if($.length===0)return Z;if(Z.length===0)return $;if(X8($[0])&&X8(Z[0]))return g5(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 g5(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 p5(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]=JX(z,H,Y,X);else if(Array.isArray(H)||Array.isArray(z))G[U]=GX(z,H,Y.arrayMergeMode||"smart",X);else G[U]=H}return G}function UX(Z,$,Y="replace"){return h5(Z,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function n7(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(!n7(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(!n7(Z[J],$[J]))return!1}return!0}return!1}function X8(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}class zX{extensions=NY;async loadFromPath(Z,$,Y={}){let{arrayStrategy:X="replace",useCache:J=!0,cacheTtl:G,trackPerformance:U=!0,verbose:H=!1}=Y;if(J){let A=D$.getWithFileCheck("file",Z);if(A){if(H)console.log(`Configuration loaded from cache: ${Z}`);return A}}let z=async()=>{if(!K$(Z))return null;try{let A=`?t=${Date.now()}`,W=await import(Z+A),Q=W.default||W,R="default"in W,O=Object.keys(W).length>0;if(!R&&!O)throw new x$(Z,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new x$(Z,Error("Configuration must export a valid object"),"unknown");let F={config:UX($,Q,X),source:{type:"file",path:Z,priority:100,timestamp:new Date}};if(J)D$.setWithFileCheck("file",F,Z,G);return F}catch(A){throw A instanceof Error?o8.configLoad(Z,A):o8.configLoad(Z,Error(String(A)))}};if(U)return i7.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 vJ({name:Z,directory:$,alias:Y})}generateNamePatterns(Z,$){return PY({name:Z,alias:$})}checkFileAccess(Z){return y5(async()=>{return K$(Z)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Z,$,Y){let X=[];if(!K$(Z))return X;if($||Y){let J=this.generateNamePatterns($||"",Y);for(let G of J)for(let U of this.extensions){let H=wY(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=wY(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(!K$(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 HX{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=[],R={stopOnFirstError:X,validateRequired:J,validateTypes:G,customRules:U,trackPerformance:H,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(Z,$,R);else if(Array.isArray($))return this.validateWithRules(Z,[...$,...U],R);else return this.validateWithJSONSchema(Z,$,R)}catch(O){return W.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:W,warnings:Q}}};if(H)return await i7.track("validateConfiguration",A);return A()}async validateWithSchemaFile(Z,$,Y){try{if(!d5($))throw new v$($,[{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 v$($,[{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:m5},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function c5(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 AX{fileLoader=new zX;envProcessor=new $0;validator=new HX;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")),R=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(A&&(R||W))throw z;if(Q&&(!A||!R))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)G8.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 G8.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,R=U||y$.cwd(),O=[];if(G){let K=V8(R,G);O.push(K);let I=A?q9(X,z,Q):z,B=await this.fileLoader.tryLoadFromPaths([K],I,{arrayStrategy:W,verbose:Q,cacheTtl:Y?.ttl,useCache:!Y?.ttl||Y.ttl>100});if(!B)throw o8.configNotFound(X||G,O,J);if(Q)G8.success(`Configuration loaded from explicit path: ${K}`);return this.finalizeResult(B,O,A,X,Q)}let N=await this.loadLocalConfiguration(X,J,R,H,z,W,Q,A,Y);if(N)return O.push(...this.getLocalSearchPaths(X,J,R,H)),this.finalizeResult(N,O,A,X,Q);let _=await this.loadHomeConfiguration(X,J,z,W,Q,A);if(_)return O.push(...this.getHomeSearchPaths(X,J)),this.finalizeResult(_,O,A,X,Q);let F=await this.loadPackageJsonConfiguration(X,J,R,z,W,Q,A);if(F)return O.push(V8(R,"package.json")),this.finalizeResult(F,O,A,X,Q);if(O.push(...this.getAllSearchPaths(X,J,R,H)),$)throw o8.configNotFound(X,O,J);return{...await this.applyEnvironmentVariables(X,z,A,Q),warnings:[`No configuration file found for "${X}"${c5(J)}, using defaults with environment variables`]}}async loadLocalConfiguration(Z,$,Y,X,J,G,U,H,z){let A=H?q9(Z,J,U):J,W=this.getLocalDirectories(Y,X);for(let Q of W){if(U)G8.info(`Searching for configuration in: ${Q}`);let R=this.fileLoader.generateConfigPaths(Z,Q,$),O=await this.fileLoader.tryLoadFromPaths(R,A,{arrayStrategy:G,verbose:U,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(O){if(U)G8.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?q9(Z,Y,J):Y,H=[V8(H9(),".config",Z),V8(H9(),".config"),H9()];for(let z of H){if(J)G8.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)G8.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration(Z,$,Y,X,J,G,U){let H=U?q9(Z,X,G):X;try{let z=V8(Y,"package.json");if(!hJ(z))return null;let A={};try{A=JSON.parse(bJ(z,"utf8"))}catch(R){if(G)G8.warn("Failed to parse package.json:",[R instanceof Error?R:Error(String(R))]);return null}let W=A[Z],Q=Z;if(!W&&$){let R=Array.isArray($)?$:[$];for(let O of R){if(!O)continue;if(A[O]){W=A[O],Q=O;break}}}if(W&&typeof W==="object"&&!Array.isArray(W)){if(G)G8.success(`Configuration loaded from package.json: ${Q}`);return{config:UX(H,W,J),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(G)G8.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:q9(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 D$.get(Y)||null}cacheResult(Z,$,Y,X){let J=this.generateCacheKey(Z,X);D$.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 yJ({cwd:Z,configDir:$})}getAllSearchPaths(Z,$,Y,X){let J=[];return J.push(...this.getLocalSearchPaths(Z,$,Y,X)),J.push(...this.getHomeSearchPaths(Z,$)),J.push(V8(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=[V8(H9(),".config",Z),V8(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 WX(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 x7.loadConfig(Z);else X=await x7.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)G8.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 x7.applyEnvironmentVariables(H.name||"",$,!0,H.verbose||!1))?.config??$;return $}}function q9(Z,$,Y=!1){let X=new $0,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],R=[`${J}_${Q.join("_").toUpperCase()}`,`${J}_${Q.map((_)=>_.toUpperCase()).join("")}`,`${J}_${Q.map((_)=>_.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,N;for(let _ of R)if(O=y$.env[_],O!==void 0){N=_;break}if(O!==void 0&&N)if(typeof W==="boolean")z[A]=["true","1","yes"].includes(O.toLowerCase());else if(typeof W==="number"){let _=Number(O);if(!Number.isNaN(_))z[A]=_}else if(Array.isArray(W))try{z[A]=JSON.parse(O)}catch{z[A]=O.split(",").map((_)=>_.trim())}else z[A]=O;else if(W&&typeof W==="object"&&!Array.isArray(W))z[A]=G(W,Q)}return z}return G($)}var D$,i7,NY,EG,IG=(Z)=>Z,wG=(Z,$)=>{for(var Y in $)EG(Z,Y,{get:$[Y],enumerable:!0,configurable:!0,set:MG.bind($,Y)})},CG=(Z,$)=>()=>(Z&&($=Z(Z=0)),$),kY,dY,R9,b9,mY,eG,Z5,_Y,F$,b7,gZ,EZ,$5,VY,Y5,KY,X5,J5,N7,G5,LY,FY,P7,U5,z5,H5,A5,B$,cY,W5,pZ,j5,Q5,BY,R$,f7,xZ,VZ,_5,RY,V5,OY,K5,L5,T7,F5,DY,EY,B5,q7,R5,O5,D5,E5,I5,O$,uY,M5,w5="0.15.6",aZ,T$,y9,g7,p7,q$,d7,m7,h9,c7,u7,y8,nY,iY,U8,I8,lY,sY,C5,N5,oY,k$,H4,hZ,LZ,A4,T5,W4,q5,j4,Q4,IY,_4,k5,x5,V4,MY,K4,L4,F4,B4,R4,k7,v5,O4,H8,aY,x$,tY,eY,Z0,ZX,$X,v$,YX,XX,o8,m5,G8,x7,w4,C4;var jX=z8(()=>{D$=new CY,i7=new SY,NY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];EG=Object.defineProperty;kY={};wG(kY,{withErrorRecovery:()=>yY,tryLoadConfig:()=>oG,loadConfigWithResult:()=>lG,loadConfig:()=>pY,isRetryableError:()=>dG,isConfigNotFoundError:()=>pG,isBunfigError:()=>hY,globalPerformanceMonitor:()=>b9,globalCache:()=>R9,getEnvOrDefault:()=>mG,generateConfigTypes:()=>rG,defaultGeneratedDir:()=>sY,defaultConfigDir:()=>lY,deepMergeWithArrayStrategy:()=>a7,deepMerge:()=>bY,createLibraryConfig:()=>aG,config:()=>sG,bunfigPlugin:()=>tG,applyEnvVarsToConfig:()=>x9,TypeGenerationError:()=>m7,SchemaValidationError:()=>h9,PluginError:()=>u7,PerformanceMonitor:()=>s7,FileSystemError:()=>d7,ErrorFactory:()=>y8,EnvVarError:()=>q$,EnvProcessor:()=>h$,ConfigValidator:()=>t7,ConfigValidationError:()=>g7,ConfigNotFoundError:()=>T$,ConfigMergeError:()=>p7,ConfigLoader:()=>e7,ConfigLoadError:()=>y9,ConfigFileLoader:()=>b$,ConfigCache:()=>l7,CacheUtils:()=>mY,BunfigError:()=>aZ,BrowserConfigError:()=>c7,ArrayMergeStrategies:()=>nY});C5=CG(async()=>{dY=import.meta.require,R9=new l7,b9=new s7,mY={createKey:SG,isEquivalent:NG,estimateMemoryUsage:PG},eG=M$(y7.cwd(),"config"),Z5=M$(y7.cwd(),"src/generated"),_Y=I$.env.CLARITY_LOG_DIR||cJ(kG(),"logs"),F$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_Y,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},b7=await xG(),gZ={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"},EZ=gZ,$5=gZ.red,VY=gZ.green,Y5=gZ.yellow,KY=gZ.blue,X5=gZ.magenta,J5=gZ.cyan,N7=gZ.white,G5=gZ.gray,LY=gZ.bgRed,FY=gZ.bgYellow,P7=gZ.bold,U5=gZ.dim,z5=gZ.italic,H5=gZ.underline,A5=gZ.reset,B$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cY={debug:"\uD83D\uDD0D",info:KY("\u2139"),success:VY("\u2713"),warning:FY(N7(P7(" WARN "))),error:LY(N7(P7(" ERROR ")))},W5=new S$("stacks"),pZ=new S$("bunfig",{showTags:!0}),j5=uZ(v9.cwd(),"config"),Q5=uZ(v9.cwd(),"src/generated"),BY=E$.env.CLARITY_LOG_DIR||dJ(bG(),"logs"),R$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:BY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},f7=await fG(),xZ={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"},VZ=xZ,_5=xZ.red,RY=xZ.green,V5=xZ.yellow,OY=xZ.blue,K5=xZ.magenta,L5=xZ.cyan,T7=xZ.white,F5=xZ.gray,DY=xZ.bgRed,EY=xZ.bgYellow,B5=xZ.bgGray,q7=xZ.bold,R5=xZ.dim,O5=xZ.italic,D5=xZ.underline,E5=xZ.strikethrough,I5=xZ.reset,O$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},uY={debug:"\uD83D\uDD0D",info:OY("\u2139"),success:RY("\u2713"),warning:EY(T7(q7(" WARN "))),error:DY(T7(q7(" ERROR ")))},M5=new P$("stacks"),aZ=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}${$}`}},T$=class extends aZ{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})}},y9=class extends aZ{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}},g7=class extends aZ{code="CONFIG_VALIDATION_ERROR";constructor($,Y,X){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:X,validationErrors:Y,errorCount:Y.length})}},p7=class extends aZ{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}},q$=class extends aZ{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})}},d7=class extends aZ{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}},m7=class extends aZ{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}},h9=class extends aZ{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,X){super(`Schema validation failed${X?` for config "${X}"`:""}`,{schemaPath:$,configName:X,validationErrors:Y,errorCount:Y.length})}},c7=class extends aZ{code="BROWSER_CONFIG_ERROR";constructor($,Y,X,J){super(`Failed to fetch configuration from "${$}": ${Y} ${X}`,{endpoint:$,status:Y,statusText:X,configName:J})}},u7=class extends aZ{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}},y8={configNotFound(Z,$,Y){return new T$(Z,$,Y)},configLoad(Z,$,Y){return new y9(Z,$,Y)},configValidation(Z,$,Y){return new g7(Z,$,Y)},configMerge(Z,$,Y,X){return new p7(Z,$,Y,X)},envVar(Z,$,Y,X){return new q$(Z,$,Y,X)},fileSystem(Z,$,Y){return new d7(Z,$,Y)},typeGeneration(Z,$,Y){return new m7(Z,$,Y)},schemaValidation(Z,$,Y){return new h9(Z,$,Y)},browserConfig(Z,$,Y,X){return new c7(Z,$,Y,X)},plugin(Z,$,Y){return new u7(Z,$,Y)}},nY={replace:"replace",concat:"concat",smart:"smart"},iY=/^https?:\/\//,U8=new P$("bunfig",{showTags:!0}),I8=new e7,lY=nZ(r8.cwd(),"config"),sY=nZ(r8.cwd(),"src/generated")});N5=w$.env.CLARITY_LOG_DIR||jG(S5(),"logs"),oY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:N5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},k$={...oY},H4=(async()=>{try{let{loadConfig:Z}=await C5().then(()=>kY),$=await Z({name:"clarity",alias:"logging",defaultConfig:oY,cwd:w$.cwd()});if($)Object.assign(k$,$)}catch{}return k$})();hZ={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=hZ,A4=hZ.red,T5=hZ.green,W4=hZ.yellow,q5=hZ.blue,j4=hZ.magenta,Q4=hZ.cyan,IY=hZ.white,_4=hZ.gray,k5=hZ.bgRed,x5=hZ.bgYellow,V4=hZ.bgGray,MY=hZ.bold,K4=hZ.dim,L4=hZ.italic,F4=hZ.underline,B4=hZ.strikethrough,R4=hZ.reset,k7={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},v5={debug:"\uD83D\uDD0D",info:q5("\u2139"),success:T5("\u2713"),warning:x5(IY(MY(" WARN "))),error:k5(IY(MY(" ERROR ")))};O4=new f$("stacks");H8=class H8 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}`}};aY=class aY extends H8{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})}};x$=class x$ extends H8{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=$}};tY=class tY extends H8{code="CONFIG_VALIDATION_ERROR";constructor(Z,$,Y){super(`Configuration validation failed for "${Z}"`,{configPath:Z,configName:Y,validationErrors:$,errorCount:$.length})}};eY=class eY extends H8{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}};Z0=class Z0 extends H8{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})}};ZX=class ZX extends H8{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}};$X=class $X extends H8{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}};v$=class v$ extends H8{code="SCHEMA_VALIDATION_ERROR";constructor(Z,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:Z,configName:Y,validationErrors:$,errorCount:$.length})}};YX=class YX extends H8{code="BROWSER_CONFIG_ERROR";constructor(Z,$,Y,X){super(`Failed to fetch configuration from "${Z}": ${$} ${Y}`,{endpoint:Z,status:$,statusText:Y,configName:X})}};XX=class XX extends H8{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 aY(Z,$,Y)},configLoad(Z,$,Y){return new x$(Z,$,Y)},configValidation(Z,$,Y){return new tY(Z,$,Y)},configMerge(Z,$,Y,X){return new eY(Z,$,Y,X)},envVar(Z,$,Y,X){return new Z0(Z,$,Y,X)},fileSystem(Z,$,Y){return new ZX(Z,$,Y)},typeGeneration(Z,$,Y){return new $X(Z,$,Y)},schemaValidation(Z,$,Y){return new v$(Z,$,Y)},browserConfig(Z,$,Y,X){return new YX(Z,$,Y,X)},plugin(Z,$,Y){return new XX(Z,$,Y)}};m5=/^https?:\/\//;G8=new f$("bunfig",{showTags:!0});x7=new AX;w4=V8(y$.cwd(),"config"),C4=V8(y$.cwd(),"src/generated")});import QX from"process";function YZ(Z=b.dialect){return Z==="mysql"||Z==="singlestore"||Z==="vitess"}function _X(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return!1;let $=Object.getPrototypeOf(Z);return $===Object.prototype||$===null}function Y0(Z,$,Y=new Set){let X={...Z};Y.add($);for(let J of Object.keys($)){if(LX.has(J))continue;let G=$[J];if(_X(G)&&!Y.has(G)){let U=X[J];X[J]=Y0(_X(U)?U:{},G,Y)}else X[J]=G}return Y.delete($),X}function p$(Z){if(Z)return Z;let $=QX.env.DB_DIALECT||QX.env.DB_CONNECTION;if($)return $;return b.dialect||"postgres"}function r(Z){if(b.dialect==="postgres")return`$${Z}`;return"?"}function PZ(Z,$=1){if(Z<=0)return"";if(b.dialect==="postgres"){let Y=`$${$}`;for(let X=1;X<Z;X++)Y+=`, $${$+X}`;return Y}return Z===1?"?":`?${", ?".repeat(Z-1)}`}async function d$(){if(!g$.fileLoaded){g$.fileLoaded=!0;let Z=await WX({name:"query-builder",alias:"qb",defaultConfig:KX}),$={};for(let[Y,X]of Object.entries(Z??{}))if(!g$.explicit.has(Y))$[Y]=X;FX($)}return b}function FX(Z){let $=Y0(b,Z),Y=b;for(let X of Object.keys($)){if(LX.has(X))continue;Y[X]=$[X]}}function BX(Z){if(Z.dialect&&f9&&Z.dialect!==f9){let $=`${f9}->${Z.dialect}`;if(!VX.has($))VX.add($),console.warn(`[query-builder] Configuring dialect '${Z.dialect}' overrides the previously configured dialect '${f9}'. 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)f9=Z.dialect;for(let $ of Object.keys(Z))g$.explicit.add($);FX(Z)}function T4(Z){return Z}var KX,LX,u5,b,n5,g$,f9=null,VX;var TZ=z8(()=>{jX();KX={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}},LX=new Set(["__proto__","constructor","prototype"]);u5=Symbol.for("bun-query-builder.config"),b=globalThis[u5]??=Y0({},KX),n5=Symbol.for("bun-query-builder.config-state"),g$=globalThis[n5]??={explicit:new Set,fileLoaded:!1};VX=new Set});function l5(){let Z=b.sqlite?.pragmas;return Array.isArray(Z)?Z:i5}function g9(Z){for(let $ of l5())try{Z.run($)}catch{}}var i5;var m$=z8(()=>{TZ();i5=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"]});var{SQL:RX}=globalThis.Bun;import{Database as o5}from"bun:sqlite";import{mkdirSync as r5}from"fs";import{dirname as a5}from"path";import d9 from"process";function p9(Z){return Z}function s5(Z){return Z!==null&&typeof Z==="object"?Z:null}function OX(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=t5(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 t5(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 MX{db;constructor(Z){if(Z!==":memory:"&&!Z.startsWith(":")){let $=a5(Z);if($&&$!==".")r5($,{recursive:!0})}this.db=new o5(Z),g9(this.db)}query(Z,$=[]){let Y=OX(Z,$);return this.db.prepare(Y.sql).all(...Y.params)}run(Z,$=[]){let Y=OX(Z,$);return this.db.prepare(Y.sql).run(...Y.params)}close(){this.db.close()}get database(){return this.db}}function DX(Z){return{__raw:!0,value:Z,toString:()=>Z}}function EX(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 e5(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=EX(Y.trim());if(Q)$.push(Q);Y="";continue}Y+=A}let H=EX(Y.trim());if(H)$.push(H);return $}function IX(Z){let $=new MX(Z);function Y(G,...U){let H=G[0],z=[];for(let A=0;A<U.length;A++){let W=U[A],Q=s5(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 R=Q.raw,O=Q.__raw?Q.value:typeof R==="string"?R:R();H+=O+(G[A+1]||"")}else if(Array.isArray(W)){let R=W.map(()=>"?").join(", ");H+=R+(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,p9(z));return Promise.resolve(W)}else{let W=$.run(H,p9(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 DX(G);return Y([""])}X.raw=(G)=>DX(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,p9(U));return Promise.resolve(A)}else{let A=$.run(G,p9(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,p9(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=e5(z);for(let W of A){let Q=W.trim();if(!Q||Q.startsWith("--"))continue;let R=Q.toUpperCase();if(R.startsWith("SELECT")||R.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 Z6(Z){let $=Z.replace(/^(?:sqlite|sqlite3|file):/i,"");if($===Z)return Z;return($.startsWith("///")?$.slice(2):$.startsWith("//")?$.slice(2):$)||":memory:"}function c$(Z=b.database){let $=d9.env.DB_DATABASE||Z?.database||"";return String($).replace(/^['"]|['"]$/g,"")}function $6(Z,$){if((Z==="postgres"||Z==="mysql"||Z==="singlestore"||Z==="vitess")&&d9.env.DB_CONNECTION===Z){let A=d9.env,W=(A.DB_DATABASE||$.database||"").replace(/^['"]|['"]$/g,""),Q=A.DB_USERNAME||$.username,R=A.DB_PASSWORD??$.password??"",O=A.DB_HOST||$.host||"localhost",N=A.DB_PORT||$.port,_=Z==="postgres"?"postgres":"mysql",F=A.DB_SSL==="true"||A.DB_SSL==="1"||$.ssl?"?ssl=true":"";return`${_}://${Q}:${R}@${O}${N?`:${N}`:""}/${W}${F}`}if($.url)return Z==="sqlite"?Z6($.url):$.url;let{database:Y,username:X,password:J,host:G="localhost",port:U,ssl:H}=$,z=H||d9.env.DB_SSL==="true"||d9.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 wX(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 Y6(){let Z=b.dialect,$=$6(Z,b.database);try{if(Z==="sqlite")return IX($);let Y=wX(b.database.pool);return Object.keys(Y).length>0?new RX($,Y):new RX($)}catch(Y){if(console.error(`[query-builder] Failed to create database connection for dialect '${Z}': ${Y.message}`),Z==="sqlite")return IX(":memory:");throw Y}}function X6(){let Z=b.database;return JSON.stringify({dialect:b.dialect,database:Z.database,username:Z.username,password:Z.password,host:Z.host,port:Z.port,url:Z.url,pool:wX(Z.pool)})}function h8(Z=!1){let $=X6();if(Z||a8!==null&&X0!==$||!a8){if(a8)CX();a8=Y6(),X0=$}return a8}function J6(){let Z=a8;return a8=null,X0=null,Z}async function G6(Z){if(!Z||typeof Z.close!=="function")return;await Z.close()}function CX(){G6(J6()).catch(($)=>{console.error(`[query-builder] Failed to close database connection: ${$.message}`)})}async function J0(Z){try{return await Z(h8())}catch($){if($?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||$?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let Y=h8(!0);return await Z(Y)}throw $}}function U6(){return new Proxy(function(){},{get(Z,$){let Y=h8(),X=Y[$];if(typeof X==="function")return X.bind(Y);return X},apply(Z,$,Y){return h8()(...Y)}})}var a8=null,X0=null,ZZ;var b8=z8(()=>{TZ();m$();ZZ=U6()});function O9(Z){return Z==="integer"||Z==="bigint"||Z==="float"||Z==="double"||Z==="decimal"}function SX(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 l$(Z){switch(Z){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}var G0=()=>{};function U0(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 f8(Z){return typeof Z?.table==="string"&&Z.table.length>0?Z.table:U0(String(Z?.name??""))}function W6(Z){return Z.endsWith("s")?Z.slice(0,-1):Z}function j6(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 g8(Z){if(Z==="none")return($)=>$;if(Z==="inflect")return j6;return W6}var p8=()=>{};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 tZ(Z,$,Y,X){if($.length===0)return Y?"1 = 1":"1 = 0";return`${Z} ${Y?"NOT IN":"IN"} (${X})`}function _6(Z,$){if($!=="postgres")return Z;let Y="",X=0,J=0;while(J<Z.length){let G=Z[J];if(G==="'"){let U=NX(Z,J,"'");Y+=Z.slice(J,U),J=U;continue}if(G==='"'){let U=NX(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 NX(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 PX="1 = 0";var o$=()=>{};function E9(Z){if(typeof Z==="number")return{length:Z};return Z}function L0(Z){if(typeof Z==="number")return{max:Z};return Z}function fU(Z){return typeof Z==="function"}function gU(Z){return Z.replace(/[A-Z]/g,($)=>$.toLowerCase())}function _1(Z,$){if(!$||typeof $.fractionDigits!=="number")return Z;return Number(Z.toFixed($.fractionDigits))}function m8(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[gU(X)];if(fU(G))return G.bind(Y);return}})}function V1(Z){let $=(W)=>{let Q=Array.isArray(W)?W:[],R=Math.floor(Math.random()*Q.length);return Q[R]},Y=()=>Z.string,X=()=>Z.number,J=()=>Z.random,G=m8(Z.string,{alpha:(W)=>Y()?.alpha?.(E9(W)),alphanumeric:(W)=>Y()?.alphanumeric?.(E9(W)),numeric:(W)=>Y()?.numeric?.(E9(W)),sample:(W)=>Y()?.sample?.(E9(W)),hexadecimal:(W)=>Y()?.hexadecimal?.(E9(W))}),U=m8(Z.number,{int:(W)=>X()?.int?.(L0(W)),float:(W)=>{let Q=L0(W);return _1(Number(X()?.float?.(Q)??0),Q)}}),H=m8(Z.helpers,{arrayElement:$,arrayElements:(W,Q)=>{let R=[...Array.isArray(W)?W:[]],O=typeof Q==="number"?Q:Math.max(1,Math.floor(Math.random()*R.length));for(let N=R.length-1;N>0;N-=1){let _=Math.floor(Math.random()*(N+1));[R[N],R[_]]=[R[_],R[N]]}return R.slice(0,Math.min(O,R.length))},shuffle:(W)=>{let Q=[...Array.isArray(W)?W:[]];for(let R=Q.length-1;R>0;R-=1){let O=Math.floor(Math.random()*(R+1));[Q[R],Q[O]]=[Q[O],Q[R]]}return Q},maybe:(W,Q)=>{let R=typeof Q?.probability==="number"?Q.probability:0.5;return Math.random()<R?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?.(L0(W))??0),float:(W)=>_1(Number(X()?.float?.(W)??0),W),uuid:()=>crypto.randomUUID(),string:(W)=>String(Y()?.alphanumeric?.({length:W??10})??""),hexadecimal:(W)=>String(Y()?.hexadecimal?.(E9(W))??""),array:(W)=>Array.from({length:W??3},()=>Y()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:Y()?.alphanumeric?.({length:8})})},location:m8(Z.address),address:m8(Z.address),vehicle:m8(Z.vehicle,{vrm:()=>Z.vehicle?.registration?.()}),company:m8(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 R=W[Q];if(R&&typeof R==="object")return m8(R);return R}})}var F0=()=>{};function G7(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(G7).filter((Y)=>Y!==null)}var U7=()=>{};import{Database as E0}from"bun:sqlite";function J9(){let Z=new Date().toISOString();return YZ(b.dialect)?Z.slice(0,19).replace("T"," "):Z}function N8(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(!E1.test(Z))throw TypeError(`[bun-query-builder] ${$}: identifier '${Z}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function I1(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||!E1.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 dU(Z,$){M0.set(Z,$),M9.clear()}function M1(){M0.clear(),M9.clear()}function eZ(Z){if(!z7)try{z7=(o9(),pU(T1)).getModel}catch{z7=()=>{return}}return z7(Z)??M0.get(Z)}function K1(Z){let $=H7.get(Z);if($!==void 0)return $;let Y=0,X=Z.replace(/\?/g,()=>`$${++Y}`);if(H7.size>=mU)H7.clear();return H7.set(Z,X),X}function L1(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 F1(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 I0{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 w1{dialect;constructor(Z){this.dialect=Z}conn(){return h8()}text(Z){return this.dialect==="postgres"?K1(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:L1(Y),lastInsertId:F1(Y)}}async insert(Z,$,Y){if(this.dialect==="postgres"){let G=await this.conn().unsafe(`${K1(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=F1(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:L1(X)||1,lastInsertId:J}}}function oW(Z){if(Z.database instanceof E0)X9=Z.database;else X9=new E0(Z.database||":memory:",{create:!0}),g9(X9);P8=null,s9=null}function OZ(){if(X9){if(!P8||s9!==X9)P8=new I0(X9),s9=X9,B0="sqlite",R0=null;return P8}let Z=b.dialect,$=b.database?.database??null;if(P8&&s9===null&&B0===Z&&R0===$)return P8;if(s9=null,B0=Z,R0=$,Z==="sqlite"){let Y=new E0($||":memory:",{create:!0});g9(Y),P8=new I0(Y)}else P8=new w1(Z);return P8}function rW(){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 cU(Z){let $=B1.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 B1.set(Z,Y),Y}function C1(Z){let $={};for(let[Y,X]of Object.entries(Z))$[DZ(Y)]=X;return $}function uU(Z){for(let $ in Z)if(DZ($)!==$)return C1(Z);return Z}function nU(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 rZ{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_relations={};constructor(Z,$={}){this._definition=Z,this._attributes=uU({...$}),this._original=null;let Y=cU(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=S1(Z,G);if(!H||H.type!=="belongsToMany")throw Error(`[orm] relation '${G}' did not resolve to a belongsToMany on '${Z.name}'`);let z=eZ(H.relatedModelName),A=z?.getDefinition?.()||z?.definition;if(!A)throw Error(`[orm] related model '${H.relatedModelName}' is not registered`);return new N1(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=nU($,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 $=C1(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 rZ(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[c8]=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 ${c8} = ? WHERE ${Z} = ?`,[null,$]),this._attributes[c8]=null,this._original=null,this}trashed(){return this._attributes[c8]!=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 rZ(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 j8(Z){return DZ(Z)}function DZ(Z){let $=R1.get(Z);if($!==void 0)return $;return $=Z.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),R1.set(Z,$),$}function Y9(Z){let $=O1.get(Z);if($!==void 0)return $;return $=U0(Z),O1.set(Z,$),$}function D1(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 sU(Z,$){let Y=Z.name??Z.table??"model",J=lU.filter((U)=>D1(Z,U).some((H)=>H.toLowerCase()===$.toLowerCase())).filter((U)=>!A7.includes(U));if(J.length>0)return`[orm] '${Y}' declares '${$}' as ${J.join("/")}, which eager loading does not support yet. Supported kinds: ${A7.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let G=A7.flatMap((U)=>D1(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 S1(Z,$){let{name:Y,table:X}=Z,J=Z.primaryKey||"id";function G(_){if(!_)return null;if(Array.isArray(_)){for(let F of _){let L=typeof F==="string"?F:F?.model||"";if(L&&L.toLowerCase()===$.toLowerCase())return L}return null}if(typeof _==="object"){for(let[F,L]of Object.entries(_))if(F===$||F.toLowerCase()===$.toLowerCase())return typeof L==="string"?L:L?.model||L?.target||F}return null}function U(){let _=Z.belongsTo;if(!_)return null;let F=$.toLowerCase(),L=(K)=>{if(typeof K==="string")return{model:K};if(K&&typeof K==="object"&&typeof K.model==="string")return{model:K.model,foreignKey:K.foreignKey};return null};if(Array.isArray(_)){for(let K of _){let I=L(K);if(I&&I.model.toLowerCase()===F)return I}return null}if(typeof _==="object"){for(let[K,I]of Object.entries(_))if(K===$||K.toLowerCase()===F)return L(I)}return null}function H(){let _=Z.belongsToMany;if(!_)return null;if(Array.isArray(_)){for(let F of _)if(typeof F==="string"){if(F.toLowerCase()===$.toLowerCase())return{entry:F}}else if(F&&typeof F==="object"&&F.model){if(F.model.toLowerCase()===$.toLowerCase())return{entry:F}}return null}if(typeof _==="object"){for(let[F,L]of Object.entries(_))if(F===$||F.toLowerCase()===$.toLowerCase())return{entry:L}}return null}let z=G(Z.hasMany);if(z){let F=eZ(z)?.getTable?.()||Y9(z),L=DZ(Y)+"_id";return{type:"hasMany",relatedModelName:z,relatedTable:F,foreignKey:L,localKey:J}}let A=G(Z.hasOne);if(A){let F=eZ(A)?.getTable?.()||Y9(A),L=DZ(Y)+"_id";return{type:"hasOne",relatedModelName:A,relatedTable:F,foreignKey:L,localKey:J}}let W=U();if(W){let _=W.model,F=eZ(_),L=F?.getTable?.()||Y9(_),K=F?.getDefinition?.()?.primaryKey||"id",I=W.foreignKey||`${DZ(_)}_id`;return{type:"belongsTo",relatedModelName:_,relatedTable:L,foreignKey:I,localKey:K}}let Q=H();if(Q){let _=typeof Q.entry==="object",F=_?Q.entry.model:Q.entry,K=eZ(F)?.getTable?.()||Y9(F),I=_?Q.entry:null,B,x;if(I?.table)B=I.table;else if(I?.through){x=I.through;let C=eZ(I.through);if(!C)throw Error(`[orm] belongsToMany relation '${$}' on '${Y}' references unknown through model '${I.through}'. Make sure '${I.through}' is registered.`);B=C.getTable?.()||C.getDefinition?.()?.table||Y9(I.through)}else{let C=l9(X),y=l9(K);B=[C,y].sort().join("_")}let P=I?.foreignKey||`${l9(X)}_id`,k=I?.relatedKey||`${l9(K)}_id`,w=[];if(I?.pivot?.columns)for(let C of Object.keys(I.pivot.columns))w.push(C);if(x){let C=eZ(x),y=C?.getDefinition?.()||C?.definition,M=y?.attributes??{},h=y?.primaryKey??"id";for(let m of Object.keys(M)){if(m===P||m===k||m===h)continue;if(!w.includes(m))w.push(m)}}return{type:"belongsToMany",relatedModelName:F,relatedTable:K,foreignKey:P,localKey:J,pivotTable:B,pivotFkParent:P,pivotFkRelated:k,pivotColumns:w,pivotModelName:x,pivotTimestamps:Boolean(I?.pivot?.timestamps)}}let R=(_,F)=>{if(!_||typeof _!=="object"||Array.isArray(_))return null;let L=_[$]??_[Object.keys(_).find((y)=>y.toLowerCase()===$.toLowerCase())??""];if(!L||typeof L!=="object")return null;let{through:K,target:I}=L;if(!K||!I)return null;let B=eZ(K),x=B?.getDefinition?.()||B?.definition,P=B?.getTable?.()||x?.table||Y9(K),k=x?.primaryKey||"id",C=eZ(I)?.getTable?.()||Y9(I);return{type:F,relatedModelName:I,relatedTable:C,foreignKey:`${DZ(Y)}_id`,localKey:J,throughTable:P,throughForeignKey:`${DZ(Y)}_id`,throughLocalKey:k,targetForeignKey:`${l9(P)}_id`}},O=R(Z.hasManyThrough,"hasManyThrough");if(O)return O;let N=R(Z.hasOneThrough,"hasOneThrough");if(N)return N;return null}function D0(Z,$){let Y=new Set;for(let X of Z){let J=X.get($);if(J!=null)Y.add(J)}return[...Y]}function l9(Z){return g8(b.relations?.singularizeStrategy)(Z)}class N1{_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(I1(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 ${O0}${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(O0))J[H.slice(O0.length)]=z;else if(H!==$&&H!==Y)G[H]=z;let U=new rZ(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((R)=>H[R]);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 HZ{_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 N8(Z,"whereNull(column)"),this._wheres.push({column:Z,operator:"=",value:null,boolean:"and"}),this}orWhereNull(Z){return N8(Z,"orWhereNull(column)"),this._wheres.push({column:Z,operator:"=",value:null,boolean:"or"}),this}whereNotNull(Z){return N8(Z,"whereNotNull(column)"),this._wheres.push({column:Z,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(Z){return N8(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 HZ(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 N8(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,$){N8(Z,"whereNotBetween(column)");let Y=j8(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(I1(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=j8(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=tZ(j8(Y.column),J,Y.operator==="not in",J.map(()=>"?").join(", ")),Z.push(...J)}else X=`${j8(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"?`${c8} IS NOT NULL`:`${c8} 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:j8(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)=>`${j8(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=S1(this._definition,Z),M9.size>=iU)M9.clear();M9.set(J,G)}if(!G)throw Error(sU(this._definition,Z));if(G.type==="hasMany"||G.type==="hasOne"){let U=D0($,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=eZ(G.relatedModelName),W=A?.getDefinition?.()||A?.definition||this._definition;if(G.type==="hasMany"){let Q=new Map;for(let R of z){let O=R[G.foreignKey];if(!Q.has(O))Q.set(O,[]);Q.get(O).push(R)}for(let R of $){let O=Q.get(R.get(X))||[];R.setRelation(Z,O.map((N)=>new rZ(W,N)))}}else{let Q=new Map;for(let R of z){let O=R[G.foreignKey];if(!Q.has(O))Q.set(O,R)}for(let R of $){let O=Q.get(R.get(X));R.setRelation(Z,O?new rZ(W,O):null)}}}if(G.type==="belongsTo"){let U=new Set;for(let O of $){let N=O._attributes[G.foreignKey];if(N!=null)U.add(N)}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=eZ(G.relatedModelName),Q=W?.getDefinition?.()||W?.definition||this._definition,R=new Map;for(let O of A)R.set(O[G.localKey],O);for(let O of $){let N=O._attributes[G.foreignKey],_=R.get(N);O.setRelation(Z,_?new rZ(Q,_):null)}}if(G.type==="belongsToMany"){let U=D0($,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 K of $)K.setRelation(Z,[]);return}let A=new Set;for(let K of z){let I=K[G.pivotFkRelated];if(I!=null)A.add(I)}let W=[...A],Q=eZ(G.relatedModelName),R=Q?.getDefinition?.()||Q?.definition||this._definition,O=R?.primaryKey||"id",N=[];if(W.length>0){let K=W.map(()=>"?").join(", ");N=await Y.all(`SELECT * FROM ${G.relatedTable} WHERE ${O} IN (${K})`,W)}let _=new Map;for(let K of N)_.set(K[O],K);let F=new Map;for(let K of z){let I=K[G.pivotFkParent];if(!F.has(I))F.set(I,[]);F.get(I).push(K)}let L=new Set([G.pivotFkParent,G.pivotFkRelated]);for(let K of $){let I=K.get(X),x=(F.get(I)||[]).map((P)=>{let k=_.get(P[G.pivotFkRelated]);if(!k)return null;let w=new rZ(R,k),C={};for(let[y,M]of Object.entries(P))if(!L.has(y))C[y]=M;return w.pivot=C,w}).filter((P)=>P!==null);K.setRelation(Z,x)}}if(G.type==="hasManyThrough"||G.type==="hasOneThrough"){let U=D0($,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 L of $)L.setRelation(Z,G.type==="hasManyThrough"?[]:null);return}let W=new Map;for(let L of A)W.set(L[H],L[G.throughForeignKey]);let Q=[...new Set(A.map((L)=>L[H]))],R=Q.map(()=>"?").join(", "),O=await Y.all(`SELECT * FROM ${G.relatedTable} WHERE ${G.targetForeignKey} IN (${R})`,Q),N=eZ(G.relatedModelName),_=N?.getDefinition?.()||N?.definition||this._definition,F=new Map;for(let L of O){let K=W.get(L[G.targetForeignKey]);if(K==null)continue;if(!F.has(K))F.set(K,[]);F.get(K).push(new rZ(_,L))}for(let L of $){let K=F.get(L.get(X))||[];L.setRelation(Z,G.type==="hasManyThrough"?K:K[0]??null)}}}async get(){let Z=OZ(),{sql:$,params:Y}=this.buildQuery(),J=(await Z.all($,Y)).map((G)=>new rZ(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){N8(Z,"increment(column)"),this.assertNoUnappliedClauses("increment");let Y=OZ(),X=[$],J=j8(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 HZ(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){N8(Z,"pluck(column)");let $=OZ(),Y=[],X=j8(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)=>`${j8(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,$){N8($,`${Z}(column)`);let Y=OZ(),X=[],J=`SELECT ${Z}(${j8($)}) 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])=>`${j8(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 oU(Z){let $={query:()=>new HZ(Z),where(Y,X,J){return new HZ(Z).where(Y,X,J)},orWhere(Y,X,J){return new HZ(Z).orWhere(Y,X,J)},whereIn(Y,X){return new HZ(Z).whereIn(Y,X)},whereNotIn(Y,X){return new HZ(Z).whereNotIn(Y,X)},whereNull(Y){return new HZ(Z).whereNull(Y)},whereNotNull(Y){return new HZ(Z).whereNotNull(Y)},whereLike(Y,X){return new HZ(Z).whereLike(Y,X)},orderBy(Y,X="asc"){return new HZ(Z).orderBy(Y,X)},orderByDesc(Y){return new HZ(Z).orderByDesc(Y)},select(...Y){return new HZ(Z).select(...Y)},with(...Y){return new HZ(Z).with(...Y)},limit:(Y)=>new HZ(Z).limit(Y),take:(Y)=>new HZ(Z).take(Y),skip:(Y)=>new HZ(Z).skip(Y),withTrashed:()=>new HZ(Z).withTrashed(),onlyTrashed:()=>new HZ(Z).onlyTrashed(),async find(Y){let X=OZ(),J=Z.primaryKey||"id",G=w9(Z)?` AND ${c8} IS NULL`:"",U=await X.get(`SELECT * FROM ${Z.table} WHERE ${J} = ?${G}`,[Y]);return U?new rZ(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 ${c8} IS NULL`:"";return(await X.all(`SELECT * FROM ${Z.table} WHERE ${J} IN (${Y.map(()=>"?").join(", ")})${G}`,Y)).map((H)=>new rZ(Z,H))},all:()=>new HZ(Z).get(),first:()=>new HZ(Z).first(),firstOrFail:()=>new HZ(Z).firstOrFail(),last:()=>new HZ(Z).last(),count:()=>new HZ(Z).count(),exists:()=>new HZ(Z).exists(),doesntExist:()=>new HZ(Z).doesntExist(),paginate:(Y,X)=>new HZ(Z).paginate(Y,X),whereBetween(Y,X){return new HZ(Z).whereBetween(Y,X)},whereNotBetween(Y,X){return new HZ(Z).whereNotBetween(Y,X)},async create(Y){let X=new rZ(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 HZ(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 HZ(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 rZ(Z,Y)},latest:(Y="created_at")=>new HZ(Z).orderByDesc(Y),oldest:(Y="created_at")=>new HZ(Z).orderBy(Y,"asc"),max:(Y)=>new HZ(Z).max(Y),min:(Y)=>new HZ(Z).min(Y),avg:(Y)=>new HZ(Z).avg(Y),sum:(Y)=>new HZ(Z).sum(Y),pluck(Y){return new HZ(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 HZ(Z).where(G,U)}return Reflect.get(Y,X)}})}function P1(Z){let $=oU(Z);if(Z?.name)dU(Z.name,$);return $}async function aW(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=SX(U.type),A=l$(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 tW(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-5vqqnp0w.js");Y=V1(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 E1,z7=null,M0,H7,mU=500,X9=null,P8=null,s9=null,B0=null,R0=null,c8="deleted_at",O0="__btm_rel__",B1,R1,O1,M9,iU=1000,A7,lU;var w0=z8(()=>{G0();TZ();b8();m$();F0();U7();p8();o$();E1=/^[A-Z_][A-Z0-9_]*$/i;M0=new Map;H7=new Map;B1=new WeakMap;R1=new Map,O1=new Map,M9=new Map;A7=["hasMany","hasOne","belongsTo","belongsToMany"],lU=[...A7,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"]});var T1={};rU(T1,{registerModel:()=>C0,registerBrowserModels:()=>tU,hasModel:()=>h1,getModelRegistry:()=>y1,getModel:()=>x1,getAllModels:()=>v1,defineModel:()=>f1,clearModelRegistry:()=>b1});function x1(Z){return C9.get(Z)}function v1(){return[...C9.values()]}function y1(){return Object.fromEntries(C9)}function h1(Z){return C9.has(Z)}function b1(){C9.clear(),M1()}function C0(Z,$){return C9.set(Z,$),$}function aU(){return typeof window<"u"&&typeof document<"u"}function f1(Z){let $;if(aU())$=q1(Z);else{let Y=P1(Z);$=Object.assign(Y,{definition:Z,getDefinition:()=>Z,getTable:()=>Z.table,getName:()=>Z.name})}return C0(Z.name,$),$}function tU(Z){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...Z}}var C9;var o9=z8(()=>{k1();w0();C9=new Map});TZ();b8();import{existsSync as k8,mkdirSync as LJ,mkdtempSync as w2,readdirSync as FJ,readFileSync as t9,rmSync as BJ,unlinkSync as y0,writeFileSync as RJ}from"fs";import{tmpdir as C2}from"os";import{join as Z8}from"path";import h0 from"process";TZ();function z6(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 H6(Z,$=63){if(Z.length<=$)return Z;let Y=`_${z6(Z)}`;return Z.slice(0,$-Y.length)+Y}function A8(Z,$){let Y=`${Z}_`,X=$.startsWith(Y)?$:`${Y}${$}`;return H6(X)}class yZ{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)} (
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
65
  ${$.join(`,
66
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)*yZ.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?yZ.KEY_PREFIX_CHARACTERS*yZ.BYTES_PER_CHARACTER:H.bytes,narrowable:!H.indexableWhole||H.bytes>yZ.KEY_PREFIX_CHARACTERS*yZ.BYTES_PER_CHARACTER}}),J=()=>X.reduce((G,U)=>G+U.bytes,0);while(J()>yZ.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 ${yZ.MAX_KEY_BYTES}. Every column in it is already at its ${yZ.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);G.prefixed=!0,G.bytes=yZ.KEY_PREFIX_CHARACTERS*yZ.BYTES_PER_CHARACTER}return X.map((G)=>G.prefixed?`${this.quoteIdentifier(G.name)}(${yZ.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=A8(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(`
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
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=A8(Z,$);return`DROP INDEX ${this.quoteIdentifier(Y)} ON ${this.quoteIdentifier(Z)};`}dropEnumType(Z){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
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
70
  id INT AUTO_INCREMENT PRIMARY KEY,
71
71
  migration VARCHAR(255) NOT NULL UNIQUE,
72
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 u${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(`,
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
74
  `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(Z.table)} (
75
75
  ${$}
76
- );`}createIndex(Z,$){let Y=$.type==="unique"?"UNIQUE ":"",X=A8(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(`
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
77
  `);return A?`${A}
78
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=A8(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 (
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
80
  id SERIAL PRIMARY KEY,
81
81
  migration VARCHAR(255) NOT NULL UNIQUE,
82
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 n$ extends yZ{createTable(Z){let $=Z.columns.map((G)=>this.renderColumn(G)).join(`,
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
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
85
  `);return`CREATE${this.tableKindSuffix(Z.tableKind)} TABLE IF NOT EXISTS ${this.quoteIdentifier(Z.table)} (
86
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 i$ extends yZ{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 (
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
88
  migration VARCHAR(255) NOT NULL PRIMARY KEY,
89
89
  executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
90
- )`}}G0();class s${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 l$(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(`,
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
91
  `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(Z.table)} (
92
92
  ${$}
93
- );`}createIndex(Z,$){let Y=$.type==="unique"?"UNIQUE ":"",X=A8(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(`,
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
94
  `),U=`CREATE TABLE ${J(Y)} (
95
95
  ${G}
96
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=A8(Z,$);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(Y)};`}dropEnumType(Z){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
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
98
  id INTEGER PRIMARY KEY AUTOINCREMENT,
99
99
  migration TEXT NOT NULL UNIQUE,
100
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 K8(Z,$={}){switch(Z){case"postgres":return new u$;case"mysql":return new yZ;case"singlestore":return new n$;case"vitess":return new i$($.vitessSharded??b.vitess?.sharded??!0);case"sqlite":return new s$;default:throw Error(`Unsupported dialect: ${Z}`)}}b8();async function A6(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=XZ();console.log("-- Setting up test table...");try{await ZZ.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await ZZ.unsafe(`
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
102
  CREATE TABLE bench_users (
103
103
  id INTEGER PRIMARY KEY AUTOINCREMENT,
104
104
  name TEXT NOT NULL,
@@ -106,10 +106,10 @@ ${z};`:`${z};`}addColumn(Z,$){let Y=this.getColumnType($),X=[this.quoteIdentifie
106
106
  active INTEGER DEFAULT 1,
107
107
  created_at TEXT
108
108
  )
109
- `).execute();for(let U=0;U<100;U++)await ZZ.unsafe(`
109
+ `).execute();for(let U=0;U<100;U++)await $Z.unsafe(`
110
110
  INSERT INTO bench_users (name, email, created_at)
111
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 ZZ.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(U){console.error("-- Warning: Failed to cleanup test table:",U)}}TZ();b8();TZ();p8();function Q6(Z){return g8(b.relations?.singularizeStrategy)(Z)}function e8(Z,$,Y,X={}){let J=X.singularize??Q6,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,R;if(z?.table)Q=z.table;else if(z?.through){if(R=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 K=J($),I=J(W);Q=[K,I].sort().join("_")}let O=z?.foreignKey??`${J($)}_id`,N=z?.relatedKey??`${J(W)}_id`,_={};if(z?.pivot?.columns)Object.assign(_,z.pivot.columns);if(R&&X.models){let K=X.models[R],I=K?.definition??K?.getDefinition?.()??K,B=I?.attributes??{};for(let[x,P]of Object.entries(B)){if(x===O||x===N||x===(I?.primaryKey??"id"))continue;_[x]={default:P?.default,nullable:P?.nullable,validation:P?.validation}}}let F=Boolean(z?.pivot?.timestamps),L=Object.keys(_);return{pivotTable:Q,fkParent:O,fkRelated:N,pivotColumns:L,pivotColumnDefs:_,pivotModelName:R,timestamps:F,relatedModelName:A,relatedTable:W,hasConfig:H}}function*DH(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}}}}p8();o$();function C8(Z){return typeof Z==="object"&&Z!==null&&"raw"in Z&&typeof Z.raw==="string"}function r$(Z){return typeof Z==="object"&&Z!==null&&"sql"in Z&&typeof Z.sql==="string"&&(!("parameters"in Z)||Array.isArray(Z.parameters))}function a$(Z,$){let Y=Z.parameters??[];if(b.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 r($+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 PH(Z,...$){if(typeof Z==="string")return{raw:Z};let Y=Z[0];for(let X=0;X<$.length;X++)Y+=w8($[X])+Z[X+1];return{raw:Y}}function oZ(Z){return YZ(b.dialect)?`\`${Z.replace(/`/g,"``")}\``:`"${Z.replace(/"/g,'""')}"`}function t$(Z,$=1){let Y=Object.keys(Z[0]??{}),X=[],J=$,G=Z.map((U)=>{return`(${Y.map((z)=>{return X.push(U[z]),r(J++)}).join(", ")})`});return{colsSql:Y.map(oZ).join(", "),valuesSql:G.join(", "),params:X,nextIndex:J}}function m9(Z){return Boolean(Z&&(Z.onSlowQuery||Z.slowQueryThresholdMs!=null&&Z.slowQueryThresholdMs>=0))}function M8(Z,$=b.dialect){if(!YZ($))return Z;if(/^[A-Z_][\w$]*$/i.test(Z))return`\`${Z}\``;let Y=/^([A-Z_][\w$]*)\.([A-Z_][\w$]*)$/i.exec(Z);if(Y)return`\`${Y[1]}\`.\`${Y[2]}\``;return Z}function TX(Z){if(typeof Z==="string")return M8(Z);if(C8(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 V6(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 jZ={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},qX=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function l(Z,$){if(!jZ.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 qZ(Z,$){if(typeof Z!=="string")throw TypeError(`[query-builder] ${$}: operator must be a string, got ${typeof Z}`);let Y=Z.toLowerCase();if(!qX.has(Y))throw TypeError(`[query-builder] ${$}: refusing to use '${Z}' as a SQL operator \u2014 not in the allowed set (${[...qX].join(", ")})`);return Z}function J8(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 K6($),Z;if(Z===null||Z===void 0)throw TypeError(`[query-builder] ${$}: fragment must be a SqlFragment, got ${Z}`);if(C8(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 kX=new Set;function K6(Z){if(kX.has(Z))return;kX.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 L6(Z,$=b.dialect){return YZ($)?Z.replace(/\\/g,"\\\\").replace(/'/g,"''"):Z.replace(/'/g,"''")}function w8(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`'${L6(Z)}'`;if(Z instanceof Date)return`'${Z.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof Z}`)}function F6(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 xX{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 Z7=new xX;function B6(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 R6(Z,$){if(!$||$.length===0)return!1;let Y=Z&&(Z.code||Z.sqlState||Z.sqlstate);if(!Y)return!1;return $.includes(Y)}function O6(Z){return new Promise(($)=>setTimeout($,Z))}var e$=new Map,D6=500;function c9(Z){let $=e$.get(Z);if($!==void 0)return $;let Y=E6(Z);if(e$.size>=D6)e$.clear();return e$.set(Z,Y),Y}function E6(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 R=Z.charCodeAt(W)&-33;if(R!==71&&R!==79&&R!==72&&R!==76&&R!==87)continue;let O=Z.slice(W);for(let{key:N,tokens:_}of $){let F=O.match(_);if(!F)continue;Y.push({key:N,start:W}),W+=F[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,R=W+1<Y.length?Y[W+1].start:Z.length,O=Z.slice(Q,R).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 I6(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 XZ(Z){let $=Z?.sql??h8(),Y=Z?.meta,X=Z?.schema;function J(_){if(typeof _==="number")return _;let F=String(_),L=7;for(let K=0;K<F.length;K++)L=L*31+F.charCodeAt(K)|0;return Math.abs(L)}function G(){if(!Z?.hooks)return b.hooks;return{...b.hooks,...Z.hooks}}let U=new Map;function H(_){if(Array.isArray(_)){let[B,x,P]=_;l(B,"where(column)");let k=String(B);switch(x){case"in":if(Array.isArray(P)){let w=PZ(P.length);return $.unsafe(`${k} IN (${w})`,P)}return $.unsafe(`${k} IN (${r(1)})`,[P]);case"not in":if(Array.isArray(P)){let w=PZ(P.length);return $.unsafe(`${k} NOT IN (${w})`,P)}return $.unsafe(`${k} NOT IN (${r(1)})`,[P]);case"like":return $.unsafe(`${k} LIKE ${r(1)}`,[P]);case"is":case"is not":{if(P!==null&&P!==void 0)throw TypeError(`[query-builder] where(..., '${x}', ?): operator '${x}' only accepts NULL/undefined as value, got ${typeof P} (${String(P)})`);return $.unsafe(`${k} IS ${x==="is not"?"NOT ":""}NULL`)}case"!=":return $.unsafe(`${k} <> ${r(1)}`,[P]);case"<":case">":case"<=":case">=":case"=":return $.unsafe(`${k} ${x} ${r(1)}`,[P]);default:throw TypeError(`[query-builder] where(..., '${String(x)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in _)return _.raw;let F=Object.keys(_);if(F.length===0)return $.unsafe("");let L=[],K=[],I=1;for(let B of F){l(B,"where(object key)");let x=_[B];if(Array.isArray(x)){let P=PZ(x.length,I);L.push(`${B} IN (${P})`),K.push(...x),I+=x.length}else L.push(`${B} = ${r(I++)}`),K.push(x)}return $.unsafe(L.join(" AND "),K)}function z(_,F,L){if(!L)return F;let K=H(L);return $`${F} WHERE ${K}`}function A(_){let F=b.debug?.captureText;if(b.debug)b.debug.captureText=!0;let L=String(_);if(b.debug)b.debug.captureText=F;return L}function W(_){if(!_||typeof _!=="object")return;if(Array.isArray(_.values))return _.values;if(Array.isArray(_.parameters))return _.parameters;if(Array.isArray(_.params))return _.params;return}function Q(_,F,L){let K=G(),I=K?.slowQueryThresholdMs,B=I!=null&&I>=0,x=Boolean(K?.onSlowQuery||B),P=K&&(K.onQueryStart||K.onQueryEnd||K.onQueryError||K.startSpan||x),k=L?.timeoutMs&&L.timeoutMs>0||L?.signal;if(!P&&!k)return _.execute();let w=A(_),C=W(_),y=Date.now(),M;try{if(K?.onQueryStart?.({sql:w,params:C,kind:F}),K?.startSpan)M=K.startSpan({sql:w,params:C,kind:F})}catch{}let h=!1,m=(c,i)=>{if(h)return;h=!0;let v=Date.now()-y;try{if(c)K?.onQueryError?.({sql:w,params:C,error:c,durationMs:v,kind:F});else if(K?.onQueryEnd?.({sql:w,params:C,durationMs:v,rowCount:i,kind:F}),B&&v>=I)if(K?.onSlowQuery)K.onSlowQuery({sql:w,params:C,durationMs:v,kind:F});else console.warn(`[query-builder] slow query (${v}ms >= ${I}ms): ${w}`)}catch{}try{M?.end(c)}catch{}},n=_.execute(),s=[n],T;if(L?.timeoutMs&&L.timeoutMs>0){let c=new Promise((i,v)=>{T=setTimeout(()=>{try{_.cancel?.()}catch{}let t=Error(`Query timed out after ${L.timeoutMs}ms`);t.code="EBQBTIMEOUT",v(t)},L.timeoutMs)});s.push(c)}if(L?.signal){if(L.signal.aborted){try{_.cancel?.()}catch{}let i=Error("Query aborted");return i.code="EBQBABORT",m(i),Promise.reject(i)}let c=()=>{try{_.cancel?.()}catch{}};L.signal.addEventListener("abort",c,{once:!0}),n.finally(()=>{L.signal?.removeEventListener("abort",c)})}return Promise.race(s).then((c)=>{clearTimeout(T);let i=Array.isArray(c)?c.length:typeof c==="number"?c:void 0;return m(void 0,i),c}).catch((c)=>{throw clearTimeout(T),m(c),c})}function R(_){if(typeof _==="number")return Number.isFinite(_)?_:0;if(typeof _==="bigint")return Number(_);if(!_||typeof _!=="object")return 0;let F=_;for(let L of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(F[L]!==void 0&&F[L]!==null)return R(F[L]);if(Array.isArray(_))return _.reduce((L,K)=>L+R(K),0);return 0}function O(_,F){let L=F??A(_);return{sql:L,toString:()=>L,execute:()=>_.execute(),values:()=>_.values(),raw:()=>_.raw()}}function N(_,F){let L=$,K=F&&F.length>0?`SELECT ${F.join(", ")} FROM ${String(_)}`:`SELECT * FROM ${String(_)}`,I=[],B=[],x=!1,P=null,k=()=>{if(P===null){let j=c9(h());P=B.length>0?$.unsafe(j,B):$.unsafe(j)}return P},w=(j,V)=>{I.push({conn:j,sql:V}),P=null},C=(j,V)=>{w(j==="OR"?"OR":"AND",V)},y=/\(|\)|\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,M=(j)=>{y.lastIndex=0;let V=0,D;while(D=y.exec(j))if(D[0]==="(")V++;else if(D[0]===")")V=Math.max(0,V-1);else if(V===0)return D.index;return-1},h=(j)=>{let V=Z9(j?[...I,j]:I);if(!V)return K;if(x){let E=jZ.WHERE.test(K)?"AND":"WHERE";return`${K} ${E} ${V}`}let D=M(K);return D>=0?`${K.slice(0,D)}WHERE ${V} ${K.slice(D)}`:`${K} WHERE ${V}`},m=(j,V)=>{let D=N(_);V(D);let E=D.__whereState?.();if(!E||!E.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let S=B.length,q=S>0&&b.dialect==="postgres"?E.body.replace(/\$(\d+)/g,(g,p)=>`$${Number(p)+S}`):E.body;B.push(...E.params),w(j,`(${q})`)},n=(j,V,D,E,S,q)=>{if(typeof E==="string"&&S!==void 0){l(String(E),`${D}(column)`),qZ(S,`${D}(operator)`);let g=B.length+1;return B.push(q),w(V,`${String(E)} ${String(S)} ${r(g)}`),j}if(Array.isArray(E)){let[g,p,u]=E,f=String(g);l(f,`${D}(column)`);let d=qZ(p,`${D}(operator)`);if(d==="in"||d==="not in"){let a=Array.isArray(u)?u:[u],JZ=PZ(a.length,B.length+1),SZ=tZ(M8(f),a,d==="not in",JZ);B.push(...a),w(V,SZ)}else{let a=B.length+1;B.push(u),w(V,`${f} ${d} ${r(a)}`)}return j}if(typeof E==="function")return m(V,E),j;if(E&&typeof E==="object"&&!("raw"in E)){let g=[];for(let p of Object.keys(E)){l(p,`${D}(column)`);let u=E[p];if(Array.isArray(u)){let f=PZ(u.length,B.length+1);g.push(tZ(M8(p),u,!1,f)),B.push(...u)}else{let f=B.length+1;g.push(`${p} = ${r(f)}`),B.push(u)}}if(g.length>0)w(V,g.length>1?`(${g.join(" AND ")})`:g[0]);return j}if(E&&typeof E.raw<"u")return w(V,E.raw),j;return j},s=(j,V)=>{if(I.length>0)K=h(),I.length=0;x=!0;let D=V.__rawState?.();if(D){let E=B.length,S=b.dialect==="postgres"?D.sql.replace(/\$(\d+)/g,(q,g)=>`$${Number(g)+E}`):D.sql;K+=` ${j} ${S}`,B.push(...D.params)}else K+=` ${j} ${String(V.toSQL())}`;P=null},T=(j)=>{let V=/\(|\)|\b(?:WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET|UNION)\b/gi,D=0,E=-1,S;while(S=V.exec(K))if(S[0]==="(")D++;else if(S[0]===")")D=Math.max(0,D-1);else if(D===0){E=S.index;break}K=E>=0?`${K.slice(0,E)}${j} ${K.slice(E)}`:`${K} ${j}`,P=null},c=new Set,i,v,t=!1,o=!1,KZ=!1,AZ=new Map,mZ=new Set,x8=60000,BZ=(j)=>g8(b.relations.singularizeStrategy)(j),$8=(j)=>{if(!Y)return null;return e8(Y,String(_),j,{singularize:BZ,models:Y.models})},l8=(j)=>{if(!j||typeof j!=="object"||mZ.size===0)return j;let V;for(let D of Object.keys(j))if(D.startsWith("pivot_")){if(!V)V={};V[D.slice(6)]=j[D],delete j[D]}if(V)j.pivot=V;return j},s8=(j)=>{if(mZ.size===0||!j)return j;if(Array.isArray(j))for(let V=0;V<j.length;V++)l8(j[V]);else l8(j);return j},F8=(j)=>{if(!Y)return;if(c.has(j.pivotTable))return;let V=String(_),D=Y.primaryKeys[V]??"id";l(j.pivotTable,"wherePivot auto-join (pivot table)"),l(j.fkParent,"wherePivot auto-join (parent FK)"),l(V,"wherePivot auto-join (parent table)"),l(D,"wherePivot auto-join (parent PK)"),P=L`${k()} LEFT JOIN ${L(j.pivotTable)} ON ${L(`${j.pivotTable}.${j.fkParent}`)} = ${L(`${V}.${D}`)}`,K=`${K} LEFT JOIN ${j.pivotTable} ON ${j.pivotTable}.${j.fkParent} = ${V}.${D}`,c.add(j.pivotTable)},P9=(j)=>{if(jZ.SELECT_STAR.test(K))K=K.replace(jZ.SELECT_STAR,`SELECT *, ${j}`);else if(jZ.SELECT.test(K))K=K.replace(jZ.SELECT_FROM,`SELECT $1, ${j} FROM`);let V=String(k());if(jZ.SELECT_STAR.test(V)){let D=V.replace(jZ.SELECT_STAR,`SELECT *, ${j}`);P=$.unsafe(D)}else if(jZ.SELECT.test(V)){if(jZ.SELECT_FROM.exec(V)){let E=V.replace(jZ.SELECT_FROM,`SELECT $1, ${j} FROM`);P=$.unsafe(E)}}},Q8=(j,V,D,E)=>{P9(`${j} ${F6(D,E)} AS ${V}`)},e9=(j,V,D,E)=>{l(j,"relationship subquery (parent table)"),l(V,"relationship subquery (target table)"),l(D,"relationship subquery (primary key)");let S=`${j.endsWith("s")?j.slice(0,-1):j}_id`;l(S,"relationship subquery (foreign key)");let q=`SELECT 1 FROM ${V} WHERE ${V}.${S} = ${j}.${D}`;if(E){let p=E({where:(u,f,d)=>{return l(u,"relationship subquery condition"),`${V}.${u} ${qZ(f,"whereHas callback")} ${w8(d)}`}});if(p)q+=` AND ${p}`}return q},Z$=(j,V,D,E)=>{l(j,"relationship subquery (parent table)"),l(V,"relationship subquery (target table)"),l(D,"relationship subquery (primary key)");let S=`${V.endsWith("s")?V.slice(0,-1):V}_id`;l(S,"relationship subquery (foreign key)");let q=`SELECT 1 FROM ${V} WHERE ${V}.${D} = ${j}.${S}`;if(E){let p=E({where:(u,f,d)=>{return l(u,"relationship subquery condition"),`${V}.${u} ${qZ(f,"whereHas callback")} ${w8(d)}`}});if(p)q+=` AND ${p}`}return q},$$=(j,V,D,E,S,q)=>{l(j,"relationship subquery (parent table)"),l(V,"relationship subquery (target table)"),l(D,"relationship subquery (primary key)"),l(E,"relationship subquery (target primary key)");let g=q&&Y?e8(Y,j,q,{singularize:BZ,models:Y.models}):null,p=BZ(j),u=BZ(V),f=g?.pivotTable??[p,u].sort().join("_"),d=g?.fkParent??`${p}_id`,a=g?.fkRelated??`${u}_id`;l(f,"relationship subquery (pivot table)"),l(d,"relationship subquery (foreign key A)"),l(a,"relationship subquery (foreign key B)");let JZ=`SELECT 1 FROM ${f} JOIN ${V} ON ${V}.${E} = ${f}.${a} WHERE ${f}.${d} = ${j}.${D}`;if(S){let e=S({where:(NZ,cZ,iZ)=>{return l(NZ,"relationship subquery condition"),`${V}.${NZ} ${qZ(cZ,"whereHas callback")} ${w8(iZ)}`}});if(e)JZ+=` AND ${e}`}return JZ},wJ=(j,V,D)=>{l(j,"withCount (parent table)"),l(V,"withCount (target table)"),l(D,"withCount (primary key)");let E=`${j.endsWith("s")?j.slice(0,-1):j}_id`;return l(E,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${V} WHERE ${V}.${E} = ${j}.${D})`},CJ=(j,V,D,E)=>{l(j,"withCount (parent table)"),l(V,"withCount (target table)"),l(D,"withCount (primary key)");let S=E&&Y?e8(Y,j,E,{singularize:BZ,models:Y.models}):null,q=BZ(j),g=BZ(V),p=S?.pivotTable??[q,g].sort().join("_"),u=S?.fkParent??`${q}_id`;return l(p,"withCount (pivot table)"),l(u,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${p} WHERE ${p}.${u} = ${j}.${D})`},Y$=(j,V,D)=>{if(!Y)return;l(D,`with${j[0]}${j.slice(1).toLowerCase()} (column)`);let E=String(_),S=Y.relations?.[E];if(!S)return;let q=Object.entries(S).find(([e,NZ])=>NZ&&typeof NZ==="object"&&(V in NZ));if(!q)return;let[g,p]=q,u=p[V],f=typeof u==="string"?u:u?.model||u?.target||u,d=Y.modelToTable[f]||f,a=Y.primaryKeys[E]??"id";l(d,`with${j} (target table)`);let JZ=`${j}(${d}.${D})`,SZ;if(g==="hasMany"||g==="hasOne"){let e=`${E.endsWith("s")?E.slice(0,-1):E}_id`;l(e,`with${j} (foreign key)`),SZ=`(SELECT ${JZ} FROM ${d} WHERE ${d}.${e} = ${E}.${a})`}else if(g==="belongsToMany"){let e=Y?e8(Y,E,V,{singularize:BZ,models:Y.models}):null,NZ=BZ(E),cZ=BZ(d),iZ=e?.pivotTable??[NZ,cZ].sort().join("_"),dZ=e?.fkParent??`${NZ}_id`,GZ=e?.fkRelated??`${cZ}_id`,T9=Y.primaryKeys[d]??"id";l(iZ,`with${j} (pivot table)`),l(dZ,`with${j} (foreign key)`),l(GZ,`with${j} (related key)`),SZ=`(SELECT ${JZ} FROM ${iZ} JOIN ${d} ON ${d}.${T9} = ${iZ}.${GZ} WHERE ${iZ}.${dZ} = ${E}.${a})`}else return;P9(`${SZ} AS ${V}_${j.toLowerCase()}_${D}`)},f0=()=>{if(AZ.size===0)return;let j=[];for(let[V,D]of AZ.entries()){let E=$8(V);if(!E)continue;for(let q of D)l(q,"withPivot");let S=D.map((q)=>`${E.pivotTable}.${q} AS pivot_${q}`);j.push(...S)}if(j.length>0){let V=j.join(", ");P9(V)}};return new Proxy({distinct(){return K=K.replace(/^SELECT\s+/i,"SELECT DISTINCT "),P=null,this},distinctOn(...j){let V=j.map(String).join(", ");return K=K.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${V}) `),P=null,this},selectRaw(j){let V=$9(j,"selectRaw(fragment)"),D=K.indexOf(" FROM ");if(D!==-1)K=`${K.substring(0,D)}, ${V}${K.substring(D)}`;else K+=`, ${V}`;return P=null,this},rowNumber(j="row_number",V,D){let E=[];if(V){let p=Array.isArray(V)?V:[V];E.push(`PARTITION BY ${p.join(", ")}`)}if(D&&D.length)E.push(`ORDER BY ${D.map(([p,u])=>`${p} ${u==="desc"?"DESC":"ASC"}`).join(", ")}`);let q=`ROW_NUMBER() ${E.length?`OVER (${E.join(" ")})`:"OVER ()"} AS ${j}`,g=K.indexOf(" FROM ");if(g!==-1)K=`${K.substring(0,g)}, ${q}${K.substring(g)}`;else K+=`, ${q}`;return P=null,this},denseRank(j="dense_rank",V,D){let E=Array.isArray(V)?V:V?[V]:[],S=[];if(E.length)S.push(`PARTITION BY ${E.join(", ")}`);if(D&&D.length)S.push(`ORDER BY ${D.map(([u,f])=>`${u} ${f==="desc"?"DESC":"ASC"}`).join(", ")}`);let g=`DENSE_RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${j}`,p=K.indexOf(" FROM ");if(p!==-1)K=`${K.substring(0,p)}, ${g}${K.substring(p)}`;else K+=`, ${g}`;return P=null,this},rank(j="rank",V,D){let E=Array.isArray(V)?V:V?[V]:[],S=[];if(E.length)S.push(`PARTITION BY ${E.join(", ")}`);if(D&&D.length)S.push(`ORDER BY ${D.map(([u,f])=>`${u} ${f==="desc"?"DESC":"ASC"}`).join(", ")}`);let g=`RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${j}`,p=K.indexOf(" FROM ");if(p!==-1)K=`${K.substring(0,p)}, ${g}${K.substring(p)}`;else K+=`, ${g}`;return P=null,this},over(j,V,D={}){return Q8(j,V,D.partitionBy,D.orderBy),this},lag(j,V={}){let D=[j,String(V.offset??1)];if(V.defaultValue!==void 0)D.push(String(V.defaultValue));return Q8(`LAG(${D.join(", ")})`,V.alias??`${j}_lag`,V.partitionBy,V.orderBy),this},lead(j,V={}){let D=[j,String(V.offset??1)];if(V.defaultValue!==void 0)D.push(String(V.defaultValue));return Q8(`LEAD(${D.join(", ")})`,V.alias??`${j}_lead`,V.partitionBy,V.orderBy),this},sumOver(j,V={}){return Q8(`SUM(${j})`,V.alias??`${j}_sum`,V.partitionBy,V.orderBy),this},avgOver(j,V={}){return Q8(`AVG(${j})`,V.alias??`${j}_avg`,V.partitionBy,V.orderBy),this},countOver(j="*",V={}){return Q8(`COUNT(${j})`,V.alias??"count_over",V.partitionBy,V.orderBy),this},minOver(j,V={}){return Q8(`MIN(${j})`,V.alias??`${j}_min`,V.partitionBy,V.orderBy),this},maxOver(j,V={}){return Q8(`MAX(${j})`,V.alias??`${j}_max`,V.partitionBy,V.orderBy),this},firstValue(j,V={}){return Q8(`FIRST_VALUE(${j})`,V.alias??`${j}_first`,V.partitionBy,V.orderBy),this},lastValue(j,V={}){return Q8(`LAST_VALUE(${j})`,V.alias??`${j}_last`,V.partitionBy,V.orderBy),this},selectAll(){return this},select(j){if(!j)return this;let V=Array.isArray(j)?j:[j];if(V.length===0)return this;let D=V.map(TX),E=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(K),S=E?E[1]:"",q=K.indexOf(" FROM ");if(q!==-1)K=`SELECT ${S}${D.join(", ")}${K.substring(q)}`;else K=`SELECT ${S}${D.join(", ")} FROM ${_}`;return P=null,this},addSelect(...j){if(!j.length)return this;let V=j.map(TX),D=K.indexOf(" FROM ");if(D!==-1)K=`${K.substring(0,D)}, ${V.join(", ")}${K.substring(D)}`;else K+=`, ${V.join(", ")}`;return P=null,this},with(...j){if(!Y||!j||j.length===0)return this;let V=[];for(let f of j){if(!f)continue;if(typeof f==="string")V.push({name:f});else if(typeof f==="object"&&!Array.isArray(f))for(let[d,a]of Object.entries(f))if(typeof a==="function")V.push({name:d,callback:a});else V.push({name:d})}if(V.length===0)return this;let D=b.relations.maxEagerLoad??50;if(V.length>D)throw Error(`[query-builder] Too many relationships to eager load (${V.length}). Maximum allowed: ${D}`);let E=String(_),S=new Set,q=new Set,g=new Map,p=(f)=>{let d=Y.relations?.[f];if(!d)return[];return[...Object.keys(d.hasOne||{}),...Object.keys(d.hasMany||{}),...Object.keys(d.belongsTo||{}),...Object.keys(d.belongsToMany||{}),...Object.keys(d.hasOneThrough||{}),...Object.keys(d.hasManyThrough||{}),...Object.keys(d.morphOne||{}),...Object.keys(d.morphMany||{}),...Object.keys(d.morphToMany||{}),...Object.keys(d.morphedByMany||{})]},u=(f,d,a=0,JZ)=>{let SZ=b.relations.maxDepth??10;if(a>=SZ)throw Error(`[query-builder] Maximum relationship depth (${SZ}) exceeded at '${d}'. Consider using separate queries or increasing maxDepth.`);let e=Y.relations?.[f];if(!e)return f;let NZ=(UZ)=>{if(b.softDeletes?.enabled&&b.softDeletes?.defaultFilter){let zZ=b.softDeletes.column||"deleted_at";return` AND ${UZ}.${zZ} IS NULL`}return""},cZ=(UZ)=>{if(!JZ)return"";let zZ=[],IZ=(WZ,lZ,_8)=>{l(String(WZ),"with() constraint column");let z9=qZ(lZ,"with() constraint operator");zZ.push(`${UZ}.${String(WZ)} ${z9} ${w8(_8)}`)},RZ=(WZ)=>()=>{throw Error(`[query-builder] with('${d}', ...): ${WZ} 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.)`)},wZ={where:(WZ,lZ,_8)=>{if(Array.isArray(WZ))IZ(WZ[0],WZ[1],WZ[2]);else if(WZ&&typeof WZ==="object")for(let z9 of Object.keys(WZ))IZ(z9,"=",WZ[z9]);else if(lZ!==void 0&&_8!==void 0)IZ(WZ,lZ,_8);else if(lZ!==void 0)IZ(WZ,"=",lZ);return wZ},whereIn:(WZ,lZ)=>{return l(String(WZ),"with() constraint column"),zZ.push(`${UZ}.${String(WZ)} IN (${lZ.map(w8).join(", ")})`),wZ},whereNull:(WZ)=>{return l(String(WZ),"with() constraint column"),zZ.push(`${UZ}.${String(WZ)} IS NULL`),wZ},whereNotNull:(WZ)=>{return l(String(WZ),"with() constraint column"),zZ.push(`${UZ}.${String(WZ)} IS NOT NULL`),wZ},orderBy:RZ("orderBy()"),limit:RZ("limit()"),offset:RZ("offset()"),take:RZ("take()")};return JZ(wZ),zZ.length?` AND ${zZ.join(" AND ")}`:""},iZ=()=>{let UZ=(RZ)=>{let wZ=RZ?.[d];return wZ?Y.modelToTable[wZ]:void 0},zZ=(RZ)=>{let wZ=RZ?.[d],WZ=typeof wZ==="string"?wZ:wZ?.model;return WZ?Y.modelToTable[WZ]:void 0},IZ=(RZ)=>{let wZ=RZ?.[d];return wZ?.target?Y.modelToTable[wZ.target]:void 0};return UZ(e?.hasOne)||UZ(e?.hasMany)||UZ(e?.belongsTo)||zZ(e?.belongsToMany)||IZ(e?.hasOneThrough)||IZ(e?.hasManyThrough)||UZ(e?.morphOne)||UZ(e?.morphMany)||UZ(e?.morphToMany)||UZ(e?.morphedByMany)},dZ=iZ()??(Y.modelToTable[d]||Y.tableToModel[d]?Y.modelToTable[d]??d:d),GZ=String(dZ);if(!dZ||!iZ()&&!Y.modelToTable[d]&&!Y.tableToModel[d]){let UZ=p(f);if(UZ.length>0&&!UZ.includes(d)){let zZ=` Available relationships: ${UZ.join(", ")}`;throw Error(`[query-builder] Relationship '${d}' not found on table '${f}'.${zZ}`)}}if(b.relations.detectCycles!==!1){let UZ=`${f}->${GZ}`;if(S.has(UZ))throw Error(`[query-builder] Circular relationship detected: ${UZ}. This would cause an infinite loop.`);S.add(UZ)}if(!GZ||GZ===f)return f;let T9=e?.hasOneThrough?.[d]||e?.hasManyThrough?.[d];if(T9){let{through:UZ,target:zZ}=T9,IZ=Y.modelToTable[UZ]||UZ,RZ=Y.modelToTable[zZ]||zZ,wZ=Y.primaryKeys[f]??"id",WZ=Y.primaryKeys[IZ]??"id",lZ=`${BZ(f)}_id`,_8=`${BZ(IZ)}_id`;return T(`LEFT JOIN ${IZ} ON ${IZ}.${lZ} = ${f}.${wZ} LEFT JOIN ${RZ} ON ${RZ}.${_8} = ${IZ}.${WZ}`),c.add(IZ),c.add(RZ),RZ}if(Boolean(e?.belongsToMany?.[d])){let UZ=e8(Y,f,d,{singularize:BZ,models:Y.models}),zZ=UZ?.pivotTable??[BZ(f),BZ(GZ)].sort().join("_"),IZ=Y.primaryKeys[f]??"id",RZ=Y.primaryKeys[GZ]??"id",wZ=UZ?.fkParent??`${BZ(f)}_id`,WZ=UZ?.fkRelated??`${BZ(GZ)}_id`;return T(`LEFT JOIN ${zZ} ON ${zZ}.${wZ} = ${f}.${IZ} LEFT JOIN ${GZ} ON ${GZ}.${RZ} = ${zZ}.${WZ}${cZ(GZ)}`),c.add(zZ),c.add(GZ),GZ}if(Boolean(e?.morphToMany?.[d])){let UZ=d,zZ=`${BZ(GZ)}_${UZ}`,IZ=Y.primaryKeys[f]??"id",RZ=Y.primaryKeys[GZ]??"id",wZ=`${UZ}_type`,WZ=`${UZ}_id`,lZ=`${BZ(GZ)}_id`,_8=w8(Y.tableToModel[f]||f);return T(`LEFT JOIN ${zZ} ON ${zZ}.${WZ} = ${f}.${IZ} AND ${zZ}.${wZ} = ${_8} LEFT JOIN ${GZ} ON ${GZ}.${RZ} = ${zZ}.${lZ}`),c.add(zZ),c.add(GZ),GZ}if(Boolean(e?.morphedByMany?.[d])){let UZ=e.morphedByMany?.[d]||d,zZ=Y.modelToTable[UZ]||UZ,IZ=BZ(f),RZ=`${BZ(zZ)}_${IZ}`,wZ=Y.primaryKeys[f]??"id",WZ=Y.primaryKeys[zZ]??"id",lZ=`${IZ}_type`,_8=`${IZ}_id`,z9=`${BZ(zZ)}_id`,kJ=w8(Y.tableToModel[zZ]||zZ);return T(`LEFT JOIN ${RZ} ON ${RZ}.${z9} = ${f}.${wZ} LEFT JOIN ${zZ} ON ${zZ}.${WZ} = ${RZ}.${_8} AND ${RZ}.${lZ} = ${kJ}`),c.add(RZ),c.add(zZ),zZ}if(Boolean(e?.belongsTo?.[d])){let UZ=`${BZ(GZ)}_id`,zZ=Y.primaryKeys[GZ]??"id";return T(`LEFT JOIN ${GZ} ON ${f}.${UZ} = ${GZ}.${zZ}${cZ(GZ)}`),c.add(GZ),GZ}let SJ=Boolean(e?.morphOne?.[d]),NJ=Boolean(e?.morphMany?.[d]);if(SJ||NJ){let UZ=`${d}_type`,zZ=`${d}_id`,IZ=Y.primaryKeys[f]??"id",RZ=w8(Y.tableToModel[f]||f);return T(`LEFT JOIN ${GZ} ON ${GZ}.${zZ} = ${f}.${IZ} AND ${GZ}.${UZ} = ${RZ}`),c.add(GZ),GZ}let PJ=`${BZ(f)}_id`,TJ=Y.primaryKeys[f]??"id",qJ=`${NZ(GZ)}${cZ(GZ)}`;return T(`LEFT JOIN ${GZ} ON ${GZ}.${PJ} = ${f}.${TJ}${qJ}`),c.add(GZ),GZ};for(let f of V){let d=f.name.trim();if(f.callback)g.set(d,f.callback);let a=d.split("."),JZ=E,SZ=0;for(let e of a){if(!e||e.trim().length===0)continue;let NZ=e.trim(),cZ=g.get(NZ);JZ=u(JZ,NZ,SZ,cZ)||JZ,SZ++}q.add(d)}if(AZ.size>0){let f=[];for(let[d,a]of AZ.entries()){let JZ=$8(d);if(!JZ)continue;let SZ=a.map((e)=>`${JZ.pivotTable}.${e} AS pivot_${e}`);f.push(...SZ)}if(f.length>0){let d=f.join(", ");P9(d)}}return P=null,this},whereHas(j,V){if(!Y)return this;let D=String(_),E=Y.relations?.[D];if(!E)throw Error(`[query-builder] No relationships defined for table '${D}'`);let S=Object.entries(E).find(([a,JZ])=>JZ&&typeof JZ==="object"&&(j in JZ));if(!S)throw Error(`[query-builder] Relationship '${j}' not found on table '${D}'`);let[q,g]=S,p=g[j],u=typeof p==="string"?p:p?.model||p?.target||p,f=Y.modelToTable[u]||u,d;if(q==="hasMany"||q==="hasOne"){let a=Y.primaryKeys[D]??"id";d=e9(D,f,a,V)}else if(q==="belongsTo"){let a=Y.primaryKeys[f]??"id";d=Z$(D,f,a,V)}else if(q==="belongsToMany"){let a=Y.primaryKeys[D]??"id",JZ=Y.primaryKeys[f]??"id";d=$$(D,f,a,JZ,V,j)}else throw Error(`[query-builder] Unsupported relationship type '${q}' for whereHas`);return C("WHERE",`EXISTS (${d})`),this},whereDoesntHave(j,V){if(!Y)return this;let D=String(_),E=Y.relations?.[D];if(!E)throw Error(`[query-builder] No relationships defined for table '${D}'`);let S=Object.entries(E).find(([a,JZ])=>JZ&&typeof JZ==="object"&&(j in JZ));if(!S)throw Error(`[query-builder] Relationship '${j}' not found on table '${D}'`);let[q,g]=S,p=g[j],u=typeof p==="string"?p:p?.model||p?.target||p,f=Y.modelToTable[u]||u,d;if(q==="hasMany"||q==="hasOne"){let a=Y.primaryKeys[D]??"id";d=e9(D,f,a,V)}else if(q==="belongsTo"){let a=Y.primaryKeys[f]??"id";d=Z$(D,f,a,V)}else if(q==="belongsToMany"){let a=Y.primaryKeys[D]??"id",JZ=Y.primaryKeys[f]??"id";d=$$(D,f,a,JZ,V,j)}else throw Error(`[query-builder] Unsupported relationship type '${q}' for whereDoesntHave`);return C("WHERE",`NOT EXISTS (${d})`),this},has(j){if(!Y)return this;let V=String(_),D=Y.relations?.[V];if(!D)throw Error(`[query-builder] No relationships defined for table '${V}'`);let E=Object.entries(D).find(([d,a])=>a&&typeof a==="object"&&(j in a));if(!E)throw Error(`[query-builder] Relationship '${j}' not found on table '${V}'`);let[S,q]=E,g=q[j],p=typeof g==="string"?g:g?.model||g?.target||g,u=Y.modelToTable[p]||p,f;if(S==="hasMany"||S==="hasOne"){let d=Y.primaryKeys[V]??"id";f=e9(V,u,d)}else if(S==="belongsTo"){let d=Y.primaryKeys[u]??"id";f=Z$(V,u,d)}else if(S==="belongsToMany"){let d=Y.primaryKeys[V]??"id",a=Y.primaryKeys[u]??"id";f=$$(V,u,d,a,void 0,j)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for has`);return C("WHERE",`EXISTS (${f})`),this},doesntHave(j){if(!Y)return this;let V=String(_),D=Y.relations?.[V];if(!D)throw Error(`[query-builder] No relationships defined for table '${V}'`);let E=Object.entries(D).find(([d,a])=>a&&typeof a==="object"&&(j in a));if(!E)throw Error(`[query-builder] Relationship '${j}' not found on table '${V}'`);let[S,q]=E,g=q[j],p=typeof g==="string"?g:g?.model||g?.target||g,u=Y.modelToTable[p]||p,f;if(S==="hasMany"||S==="hasOne"){let d=Y.primaryKeys[V]??"id";f=e9(V,u,d)}else if(S==="belongsTo"){let d=Y.primaryKeys[u]??"id";f=Z$(V,u,d)}else if(S==="belongsToMany"){let d=Y.primaryKeys[V]??"id",a=Y.primaryKeys[u]??"id";f=$$(V,u,d,a,void 0,j)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for doesntHave`);return C("WHERE",`NOT EXISTS (${f})`),this},withCount(...j){if(!Y||!j||j.length===0)return this;let V=String(_);for(let D of j){let E=Y.relations?.[V];if(!E)continue;let S=Object.entries(E).find(([SZ,e])=>e&&typeof e==="object"&&(D in e));if(!S)continue;let[q,g]=S,p=g[D],u=typeof p==="string"?p:p?.model||p?.target||p,f=Y.modelToTable[u]||u,d=Y.primaryKeys[V]??"id",a;if(q==="hasMany"||q==="hasOne")a=wJ(V,f,d);else if(q==="belongsToMany")a=CJ(V,f,d,D);else continue;let JZ=`${D}_count`;P9(`${a} AS ${JZ}`)}return this},withSum(j,V){return Y$("SUM",j,V),this},withAvg(j,V){return Y$("AVG",j,V),this},withMax(j,V){return Y$("MAX",j,V),this},withMin(j,V){return Y$("MIN",j,V),this},applyPivotColumns(){return f0(),this},withPivot(j,...V){if(!Y)return this;let D=String(_),E=$8(j);if(!E)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${D}'`);let S=V&&V.length>0?V:E.hasConfig?E.pivotColumns:[];if(S.length===0)return this;if(AZ.set(j,S),E.hasConfig)mZ.add(j);return f0(),this},wherePivot(j,V,D,E){if(!Y)return this;let S=$8(j);if(!S)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(_)}'`);l(S.pivotTable,"wherePivot (pivot table)"),l(V,"wherePivot (column)"),F8(S);let q=E===void 0?"=":String(D),g=E===void 0?D:E,p=B.length+1,u=`${S.pivotTable}.${V} ${q} ${r(p)}`;if(B.push(g),w("AND",u),S.hasConfig)mZ.add(j);return this},wherePivotIn(j,V,D){if(!Y||!Array.isArray(D))return this;let E=$8(j);if(!E)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(_)}'`);l(E.pivotTable,"wherePivotIn (pivot table)"),l(V,"wherePivotIn (column)"),F8(E);let S=PZ(D.length,B.length+1),q=tZ(`${E.pivotTable}.${V}`,D,!1,S);if(B.push(...D),w("AND",q),E.hasConfig)mZ.add(j);return this},wherePivotNotIn(j,V,D){if(!Y||!Array.isArray(D)||D.length===0)return this;let E=$8(j);if(!E)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(_)}'`);l(E.pivotTable,"wherePivotNotIn (pivot table)"),l(V,"wherePivotNotIn (column)"),F8(E);let S=PZ(D.length,B.length+1),q=`${E.pivotTable}.${V} NOT IN (${S})`;if(B.push(...D),w("AND",q),E.hasConfig)mZ.add(j);return this},wherePivotNull(j,V){if(!Y)return this;let D=$8(j);if(!D)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(_)}'`);if(l(D.pivotTable,"wherePivotNull (pivot table)"),l(V,"wherePivotNull (column)"),F8(D),w("AND",`${D.pivotTable}.${V} IS NULL`),D.hasConfig)mZ.add(j);return this},wherePivotNotNull(j,V){if(!Y)return this;let D=$8(j);if(!D)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(_)}'`);if(l(D.pivotTable,"wherePivotNotNull (pivot table)"),l(V,"wherePivotNotNull (column)"),F8(D),w("AND",`${D.pivotTable}.${V} IS NOT NULL`),D.hasConfig)mZ.add(j);return this},where(j,V,D){if(typeof j==="string"&&V!==void 0){l(String(j),"where(column)"),qZ(V,"where(operator)");let E=String(V).toLowerCase();if(E==="in"||E==="not in"){let q=Array.isArray(D)?D:[D],g=PZ(q.length,B.length+1),p=tZ(M8(String(j)),q,E==="not in",g);return B.push(...q),w("AND",p),this}let S=B.length+1;return B.push(D),w("AND",`${M8(String(j))} ${String(V)} ${r(S)}`),this}if(Array.isArray(j)){let[E,S,q]=j,g=String(E);l(g,"where(column)");let p=qZ(S,"where(operator)");if(p==="in"||p==="not in"){let u=Array.isArray(q)?q:[q],f=PZ(u.length,B.length+1),d=tZ(M8(g),u,p==="not in",f);B.push(...u),w("AND",d)}else{let u=B.length+1;B.push(q),w("AND",`${M8(g)} ${p} ${r(u)}`)}return this}if(j&&typeof j==="object"&&!C8(j)){let E=j,S=Object.keys(E),q=[];for(let g of S){l(g,"where(column)");let p=E[g];if(Array.isArray(p)){let u=PZ(p.length,B.length+1);q.push(tZ(M8(g),p,!1,u)),B.push(...p)}else{let u=B.length+1;q.push(`${M8(g)} = ${r(u)}`),B.push(p)}}if(q.length>0)w("AND",q.length>1?`(${q.join(" AND ")})`:q[0]);return this}if(C8(j))return w("AND",j.raw),this;if(typeof j==="function")return m("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 l(String(j),"whereNull(column)"),w("AND",`${String(j)} IS NULL`),this},whereNotNull(j){return l(String(j),"whereNotNull(column)"),w("AND",`${String(j)} IS NOT NULL`),this},orWhereNull(j){return l(String(j),"orWhereNull(column)"),w("OR",`${String(j)} IS NULL`),this},orWhereNotNull(j){return l(String(j),"orWhereNotNull(column)"),w("OR",`${String(j)} IS NOT NULL`),this},whereBetween(j,V,D){l(String(j),"whereBetween(column)");let E=B.length+1;return B.push(V,D),w("AND",`${String(j)} BETWEEN ${r(E)} AND ${r(E+1)}`),this},orWhereBetween(j,V,D){l(String(j),"orWhereBetween(column)");let E=B.length+1;return B.push(V,D),w("OR",`${String(j)} BETWEEN ${r(E)} AND ${r(E+1)}`),this},whereExists(j){return w("AND",`EXISTS (${j.toSQL()})`),this},orWhereExists(j){return w("OR",`EXISTS (${j.toSQL()})`),this},whereGroup(j){return m("AND",j),this},orWhereGroup(j){return m("OR",j),this},__whereState(){return{body:Z9(I),params:[...B]}},whereJsonContains(j,V){l(String(j),"whereJsonContains(column)");let D=b.dialect,E=B.length+1;if(D==="postgres"){let q=typeof V==="number"||typeof V==="boolean"?`to_jsonb(${r(E)})`:r(E);if(b.sql?.jsonContainsMode==="function")w("AND",`jsonb_contains(${j}, ${q})`);else w("AND",`${j} @> ${q}`);B.push(V)}else if(YZ(D))w("AND",`JSON_CONTAINS(${j}, ${r(E)})`),B.push(JSON.stringify(V));else if(Array.isArray(V)){let S=V.map((q,g)=>`EXISTS (SELECT 1 FROM json_each(${j}) WHERE json_each.value = ${r(E+g)})`);w("AND",`(${S.join(" AND ")})`);for(let q of V)B.push(q)}else if(V!==null&&typeof V==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else w("AND",`EXISTS (SELECT 1 FROM json_each(${j}) WHERE json_each.value = ${r(E)})`),B.push(V);return this},whereJsonPath(j,V,D){if(qZ(V,"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 E=b.dialect,S=B.length+1;if(E==="postgres")w("AND",`${j} ${V} ${r(S)}`);else if(YZ(E))w("AND",`JSON_EXTRACT(${j}) ${V} ${r(S)}`);else w("AND",`json_extract(${j}) ${V} ${r(S)}`);return B.push(D),this},whereLike(j,V,D=!1){let E=r(B.length+1);return C("WHERE",`${D?String(j):`LOWER(${String(j)})`} LIKE ${D?E:`LOWER(${E})`}`),B.push(V),P=null,this},whereILike(j,V){let D=r(B.length+1);if(b.dialect==="postgres")C("WHERE",`${String(j)} ILIKE ${D}`);else C("WHERE",`LOWER(${String(j)}) LIKE LOWER(${D})`);return B.push(V),P=null,this},orWhereLike(j,V,D=!1){let E=r(B.length+1);return C("OR",`${D?String(j):`LOWER(${String(j)})`} LIKE ${D?E:`LOWER(${E})`}`),B.push(V),P=null,this},orWhereILike(j,V){let D=r(B.length+1);if(b.dialect==="postgres")C("OR",`${String(j)} ILIKE ${D}`);else C("OR",`LOWER(${String(j)}) LIKE LOWER(${D})`);return B.push(V),P=null,this},whereNotLike(j,V,D=!1){let E=r(B.length+1);return C("WHERE",`${D?String(j):`LOWER(${String(j)})`} NOT LIKE ${D?E:`LOWER(${E})`}`),B.push(V),P=null,this},whereNotILike(j,V){let D=r(B.length+1);if(b.dialect==="postgres")C("WHERE",`${String(j)} NOT ILIKE ${D}`);else C("WHERE",`LOWER(${String(j)}) NOT LIKE LOWER(${D})`);return B.push(V),P=null,this},orWhereNotLike(j,V,D=!1){let E=r(B.length+1);return C("OR",`${D?String(j):`LOWER(${String(j)})`} NOT LIKE ${D?E:`LOWER(${E})`}`),B.push(V),P=null,this},orWhereNotILike(j,V){let D=r(B.length+1);if(b.dialect==="postgres")C("OR",`${String(j)} NOT ILIKE ${D}`);else C("OR",`LOWER(${String(j)}) NOT LIKE LOWER(${D})`);return B.push(V),P=null,this},whereAny(j,V,D){if(j.length===0)return w("AND",`(${PX})`),this;let E=B.length+1,S=j.map((q,g)=>`${q} ${V} ${r(E+g)}`);for(let q=0;q<j.length;q++)B.push(D);return w("AND",`(${S.join(" OR ")})`),this},whereAll(j,V,D){if(j.length===0)return this;let E=B.length+1,S=j.map((q,g)=>`${q} ${V} ${r(E+g)}`);for(let q=0;q<j.length;q++)B.push(D);return w("AND",`(${S.join(" AND ")})`),this},whereNone(j,V,D){if(j.length===0)return this;let E=B.length+1,S=j.map((q,g)=>`${q} ${V} ${r(E+g)}`);for(let q=0;q<j.length;q++)B.push(D);return w("AND",`NOT (${S.join(" OR ")})`),this},whereNotBetween(j,V,D){l(String(j),"whereNotBetween(column)");let E=B.length+1;return B.push(V,D),w("AND",`${j} NOT BETWEEN ${r(E)} AND ${r(E+1)}`),this},whereDate(j,V,D){l(j,"whereDate(column)");let E=D instanceof Date?D.toISOString():typeof D==="string"?D:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof D}`)})(),S=B.length+1;return B.push(E),w("AND",`${j} ${V} ${r(S)}`),this},whereRaw(j){return w("AND",$9(j,"whereRaw(fragment)")),this},orWhereRaw(j){return w("OR",$9(j,"orWhereRaw(fragment)")),this},whereColumn(j,V,D){return l(j,"whereColumn(left)"),l(D,"whereColumn(right)"),w("AND",`${j} ${V} ${D}`),this},orWhereColumn(j,V,D){return l(j,"orWhereColumn(left)"),l(D,"orWhereColumn(right)"),w("OR",`${j} ${V} ${D}`),this},whereIn(j,V){if(l(String(j),"whereIn(column)"),Array.isArray(V)){let D=PZ(V.length,B.length+1),E=tZ(j,V,!1,D);B.push(...V),w("AND",E)}else w("AND",`${j} IN (${String(V.toSQL())})`);return this},orWhereIn(j,V){if(l(String(j),"orWhereIn(column)"),Array.isArray(V)){let D=PZ(V.length,B.length+1),E=tZ(j,V,!1,D);B.push(...V),w("OR",E)}else w("OR",`${j} IN (${String(V.toSQL())})`);return this},whereNotIn(j,V){if(l(String(j),"whereNotIn(column)"),Array.isArray(V)){let D=PZ(V.length,B.length+1),E=tZ(j,V,!0,D);B.push(...V),w("AND",E)}else w("AND",`${j} NOT IN (${String(V.toSQL())})`);return this},orWhereNotIn(j,V){if(l(String(j),"orWhereNotIn(column)"),Array.isArray(V)){let D=PZ(V.length,B.length+1),E=tZ(j,V,!0,D);B.push(...V),w("OR",E)}else w("OR",`${j} NOT IN (${String(V.toSQL())})`);return this},whereNested(j){let V=j.toSQL?String(j.toSQL()):String(j);return w("AND",`(${V})`),this},orWhereNested(j){let V=j.toSQL?String(j.toSQL()):String(j);return w("OR",`(${V})`),this},andWhere(j,V,D){return n(this,"AND","andWhere",j,V,D)},orWhere(j,V,D){return n(this,"OR","orWhere",j,V,D)},orderBy(j,V="asc"){let D=V==="asc"?"ASC":"DESC";return K=jZ.ORDER_BY.test(K)?`${K}, ${j} ${D}`:`${K} ORDER BY ${j} ${D}`,P=null,this},orderByDesc(j){return K=jZ.ORDER_BY.test(K)?`${K}, ${j} DESC`:`${K} ORDER BY ${j} DESC`,P=null,this},inRandomOrder(){let j=b.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return K=jZ.ORDER_BY.test(K)?`${K}, ${j}`:`${K} ORDER BY ${j}`,P=null,this},reorder(j,V="asc"){return K=K.replace(/ORDER BY[\s\S]*$/i,""),K+=` ORDER BY ${j} ${V==="asc"?"ASC":"DESC"}`,P=null,this},latest(j){let V=j??b.timestamps.defaultOrderColumn;return K=jZ.ORDER_BY.test(K)?`${K}, ${V} DESC`:`${K} ORDER BY ${V} DESC`,P=null,this},oldest(j){let V=j??b.timestamps.defaultOrderColumn;return K=jZ.ORDER_BY.test(K)?`${K}, ${V} ASC`:`${K} ORDER BY ${V} 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 K=jZ.LIMIT.test(K)?K.replace(jZ.LIMIT,` LIMIT ${j}`):`${K} 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 K=jZ.OFFSET.test(K)?K.replace(jZ.OFFSET,` OFFSET ${j}`):`${K} OFFSET ${j}`,P=null,this},join(j,V,D,E){return l(j,"join(table)"),J8(V,"join(onLeft)"),J8(E,"join(onRight)"),qZ(D,"join(operator)"),T(`JOIN ${j} ON ${V} ${D} ${E}`),c.add(j),this},joinSub(j,V,D,E,S){return l(V,"joinSub(alias)"),J8(D,"joinSub(onLeft)"),J8(S,"joinSub(onRight)"),qZ(E,"joinSub(operator)"),T(`JOIN (${String(j.toSQL())}) AS ${V} ON ${D} ${E} ${S}`),c.add(V),this},innerJoin(j,V,D,E){return l(j,"innerJoin(table)"),J8(V,"innerJoin(onLeft)"),J8(E,"innerJoin(onRight)"),qZ(D,"innerJoin(operator)"),T(`INNER JOIN ${j} ON ${V} ${D} ${E}`),c.add(j),this},leftJoin(j,V,D,E){return l(j,"leftJoin(table)"),J8(V,"leftJoin(onLeft)"),J8(E,"leftJoin(onRight)"),qZ(D,"leftJoin(operator)"),T(`LEFT JOIN ${j} ON ${V} ${D} ${E}`),c.add(j),this},leftJoinSub(j,V,D,E,S){return l(V,"leftJoinSub(alias)"),J8(D,"leftJoinSub(onLeft)"),J8(S,"leftJoinSub(onRight)"),qZ(E,"leftJoinSub(operator)"),T(`LEFT JOIN (${String(j.toSQL())}) AS ${V} ON ${D} ${E} ${S}`),c.add(V),this},rightJoin(j,V,D,E){return l(j,"rightJoin(table)"),J8(V,"rightJoin(onLeft)"),J8(E,"rightJoin(onRight)"),qZ(D,"rightJoin(operator)"),T(`RIGHT JOIN ${j} ON ${V} ${D} ${E}`),c.add(j),this},crossJoin(j){return l(j,"crossJoin(table)"),T(`CROSS JOIN ${j}`),c.add(j),this},crossJoinSub(j,V){return l(V,"crossJoinSub(alias)"),T(`CROSS JOIN (${String(j.toSQL())}) AS ${V}`),c.add(V),this},selectAllRelations(){if(!X)return this;let j=String(_),V=Object.keys(X[j]?.columns??{}),D=[];if(V.length>0)D.push(L`${L(j)}.*`);for(let E of c){let S=Object.keys(X[E]?.columns??{});for(let q of S){let g=b.aliasing.relationColumnAliasFormat==="camelCase"?`${E}_${q}`.replace(/_([a-z])/g,(p,u)=>u.toUpperCase()):b.aliasing.relationColumnAliasFormat==="table.dot.column"?`${E}.${q}`:`${E}_${q}`;D.push(L`${L(`${E}.${q}`)} AS ${L(g)}`)}}if(D.length>0){let E=V.length>0?`${j}.*`:"",S=[];for(let p of c){let u=Object.keys(X[p]?.columns??{});for(let f of u){let d=b.aliasing.relationColumnAliasFormat==="camelCase"?`${p}_${f}`.replace(/_([a-z])/g,(a,JZ)=>JZ.toUpperCase()):b.aliasing.relationColumnAliasFormat==="table.dot.column"?`${p}.${f}`:`${p}_${f}`;S.push(`${p}.${f} AS ${d}`)}}let q=[E,...S].filter(Boolean).join(", "),g=K.indexOf(" FROM ");if(g!==-1)K=`SELECT ${q}${K.substring(g)}`;else K=`SELECT ${q} FROM ${j}`;P=null}return this},groupBy(...j){if(j.length)K=jZ.GROUP_BY.test(K)?`${K}, ${j.join(", ")}`:`${K} GROUP BY ${j.join(", ")}`,P=null;return this},groupByRaw(j){let V=$9(j,"groupByRaw(fragment)");return K=jZ.GROUP_BY.test(K)?`${K}, ${V}`:`${K} GROUP BY ${V}`,P=null,this},having(j){let V=/\bHAVING\b/i.test(K)?"AND":"HAVING";if(Array.isArray(j)){let D=B.length+1;K=`${K} ${V} ${j[0]} ${j[1]} ${r(D)}`,B.push(j[2]),P=null}else if(j&&typeof j==="object"&&!("raw"in j)){let D=Object.keys(j),E=D.length;if(E){let S=B.length,q=Array.from({length:E});for(let g=0;g<E;g++){let p=D[g];q[g]=`${p} = ${r(S+g+1)}`,B.push(j[p])}K=`${K} ${V} ${q.join(" AND ")}`,P=null}}else if(j&&typeof j.raw<"u")K+=` ${V} ${j.raw}`,P=null;return this},havingRaw(j){let V=$9(j,"havingRaw(fragment)"),D=/\bHAVING\b/i.test(K)?"AND":"HAVING";return K+=` ${D} ${V}`,P=null,this},orderByRaw(j){let V=$9(j,"orderByRaw(fragment)");return K=jZ.ORDER_BY.test(K)?`${K}, ${V}`:`${K} ORDER BY ${V}`,P=null,this},$call(j){return j(this),this},union(j){return s("UNION",j),this},unionAll(j){return s("UNION ALL",j),this},intersect(j){return s("INTERSECT",j),this},intersectAll(j){return s("INTERSECT ALL",j),this},except(j){return s("EXCEPT",j),this},exceptAll(j){return s("EXCEPT ALL",j),this},forPage(j,V){let D=Math.max(1,Math.floor(j)),E=Math.max(1,Math.floor(V));return K+=` LIMIT ${E} OFFSET ${(D-1)*E}`,P=null,this},toSQL(){let j=c9(h());return{sql:j,toString:()=>j,execute:()=>k().execute(),values:()=>k().values(),raw:()=>k().raw()}},async value(j){let V=L`${k()} LIMIT 1`,D=await Q(V,"select",{signal:v,timeoutMs:i}),[E]=D;return E?.[j]},async pluck(j,V){let D=await Q(k(),"select",{signal:v,timeoutMs:i});if(V){let E={};for(let S of D){let q=String(S?.[V]);if(Object.prototype.hasOwnProperty.call(E,q))throw Error(`[query-builder] pluck(${j}, ${V}): duplicate key '${q}' \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.`);E[q]=S?.[j]}return E}return D.map((E)=>E?.[j])},async exists(){let j=L`SELECT EXISTS (${k()}) as e`,V=await Q(j,"select",{signal:v,timeoutMs:i}),[D]=V;return Boolean(D?.e)},async doesntExist(){return!await this.exists()},async paginate(j,V=1,D={}){if(!Number.isFinite(j)||j<=0||!Number.isInteger(j))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${j}`);if(!Number.isFinite(V)||V<1||!Number.isInteger(V))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${V}`);if(D.tx){let a=c9(h()),JZ=[...B],SZ=await D.tx.unsafe(`SELECT COUNT(*) as c FROM (${a}) as sub`,JZ),e=Number(SZ?.[0]?.c??0),NZ=Math.max(1,Math.ceil(e/j)),cZ=Math.max(1,Math.min(V,NZ)),iZ=(cZ-1)*j;return{data:await D.tx.unsafe(`${a} LIMIT ${j} OFFSET ${iZ}`,JZ),meta:{perPage:j,page:cZ,total:e,lastPage:NZ}}}let E=L`SELECT COUNT(*) as c FROM (${k()}) as sub`,S=await Q(E,"select",{signal:v,timeoutMs:i}),[q]=S,g=Number(q?.c??0),p=Math.max(1,Math.ceil(g/j)),u=Math.max(1,Math.min(V,p)),f=(u-1)*j;return{data:await Q(L`${k()} LIMIT ${j} OFFSET ${f}`,"select",{signal:v,timeoutMs:i}),meta:{perPage:j,page:u,total:g,lastPage:p}}},async simplePaginate(j,V=1){let D=Math.max(1,V),E=(D-1)*j,S=await Q(L`${k()} LIMIT ${j+1} OFFSET ${E}`,"select",{signal:v,timeoutMs:i}),q=S.length>j;return{data:q?S.slice(0,j):S,meta:{perPage:j,page:D,hasMore:q}}},async cursorPaginate(j,V,D="id",E="asc"){if(!Number.isInteger(j)||j<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${j}`);let S=(Array.isArray(D)?D:[D]).map(String);for(let dZ of S)l(dZ,"cursorPaginate(column)");let q=E==="asc"?">":"<",g=E==="asc"?"ASC":"DESC",p=[...B],u="";if(V!==void 0&&V!==null)if(Array.isArray(D)){let dZ=V.map((GZ)=>{return p.push(GZ),r(p.length)});u=`(${S.join(", ")}) ${q} (${dZ.join(", ")})`}else p.push(V),u=`${S[0]} ${q} ${r(p.length)}`;let f=c9(u?h({conn:"AND",sql:u}):h()),d=S.map((dZ)=>`${dZ} ${g}`).join(", ");if(V6(f))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${d} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let a=p.length>0?$.unsafe(`${f} ORDER BY ${d} LIMIT ${j+1}`,p):$.unsafe(`${f} ORDER BY ${d} LIMIT ${j+1}`),JZ=await Q(a,"select",{signal:v,timeoutMs:i}),SZ=JZ.length>j,e=JZ.slice(0,j),NZ=e[e.length-1],cZ=SZ&&NZ?Array.isArray(D)?D.map((dZ)=>NZ[dZ]):NZ[D]:null,iZ=e.length?Array.isArray(D)?D.map((dZ)=>e[0]?.[dZ]):e[0]?.[D]:null;return{data:e,meta:{perPage:j,nextCursor:cZ??null,prevCursor:iZ}}},async chunk(j,V){let D=1;while(!0){let{data:E,meta:S}=await this.paginate(j,D);if(E.length===0)break;if(await V(E),D>=S.lastPage)break;D+=1}},async chunkById(j,V="id",D){let E;while(!0){let{data:S,meta:q}=await this.cursorPaginate(j,E,V,"asc");if(S.length===0)break;if(D)await D(S);if(E=q.nextCursor,!E)break}},async eachById(j,V="id",D){await this.chunkById(j,V,async(E)=>{for(let S of E)await D?.(S)})},withTimeout(j){return i=Math.max(1,Math.floor(j)),this},abort(j){return v=j,this},withTrashed(){return t=!0,o=!1,this},onlyTrashed(){t=!0,o=!0;let j=b.softDeletes?.column||"deleted_at",V=(S,q)=>{let g=S.toUpperCase(),p=0;for(let u=0;u<S.length;u++){let f=S[u];if(f==="(")p++;else if(f===")")p--;else if(p===0&&g.substring(u,u+5)==="WHERE"&&(u===0||/\s/.test(S[u-1]??""))&&/\s/.test(S[u+5]??""))return`${S.substring(0,u)}WHERE ${q} AND ${S.substring(u+6)}`}return`${S} WHERE ${q}`},D=`${_}.${j} IS NOT NULL`;K=V(K,D);let E=String(k());return P=L([V(E,D)]),this},scope(j,V){let D=String(_),S=Y?.scopes?.[D]?.[j];if(S)return S(this,V);return this},when(j,V,D){if(j)return V(this);if(D)return D(this);return this},tap(j){return j(this),this},dump(){return console.log(String(k())),this},dd(){throw console.log(String(k())),Error("Dump and Die")},cache(j=60000){return x8=j,KZ=!0,this},async explain(){let j=L`EXPLAIN ${k()}`;return await Q(j,"select",{signal:v,timeoutMs:i})},simple(){return k().simple()},toText(){return h()},async get(){let j=G(),V=j&&(j.onQueryStart||j.onQueryEnd||j.onQueryError||j.startSpan||m9(j));if(!b.softDeletes?.enabled&&!KZ&&!i&&!v&&!V){let g=$._prepareStatement;if(g){let p=g(h());return s8(B.length>0?p.all(...B):p.all())}}let D=h();if(P=B.length>0?$.unsafe(D,B):$.unsafe(D),!b.softDeletes?.enabled&&!KZ&&!i&&!v&&!V){let g=k()._stmt,p=k()._params;if(g)return s8(p&&p.length>0?g.all(...p):g.all());return s8(await k().execute())}if(!b.softDeletes?.enabled&&!KZ&&!i&&!v)return s8(await Q(k(),"select"));let E=k();if(b.softDeletes?.enabled&&b.softDeletes.defaultFilter&&!t){let g=b.softDeletes.column,p=String(_);if((X?Boolean(X[p]?.columns?.[g]):!0)&&!jZ.DELETED_AT.test(h()))C("WHERE",`${String(g)} IS ${o?"NOT ":""}NULL`),E=k()}let S=KZ?`${String(E)}\x00${JSON.stringify(B)}`:"";if(KZ){let g=Z7.get(S);if(g)return g}let q=await Q(E,"select",{signal:v,timeoutMs:i});if(KZ)Z7.set(S,q,x8);return s8(q)},async executeTakeFirst(){let j=await Q(k(),"select",{signal:v,timeoutMs:i});return l8(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=G(),V=j&&(j.onQueryStart||j.onQueryEnd||j.onQueryError||j.startSpan||m9(j));if(!b.softDeletes?.enabled&&!KZ&&!i&&!v&&!V){let S=$._prepareStatement;if(S){let q=h(),g=q.includes(" LIMIT ")?q:`${q} LIMIT 1`,p=S(g),u=B.length>0?p.all(...B):p.all();return l8(u[0])}}let D=await Q(L`${k()} LIMIT 1`,"select",{signal:v,timeoutMs:i}),[E]=D;return l8(E)},async firstOrFail(){let j=await this.first();if(!j)throw Error("Record not found");return j},async find(j){let V=Y?.primaryKeys[String(_)]??"id",D=await Q(L`${k()} WHERE ${L(V)} = ${j} LIMIT 1`,"select",{signal:v,timeoutMs:i}),[E]=D;return E},async findOrFail(j){let V=await this.find(j);if(!V)throw Error("Record not found");return V},async findMany(j){let V=Y?.primaryKeys[String(_)]??"id";return await Q(L`${k()} WHERE ${L(String(V))} IN ${L(j)}`,"select",{signal:v,timeoutMs:i})},async*lazy(){let j,V=Y?.primaryKeys[String(_)]??"id";while(!0){let E=await(j==null?L`${k()} ORDER BY ${L(String(V))} ASC LIMIT 100`:L`${k()} WHERE ${L(String(V))} > ${j} ORDER BY ${L(String(V))} ASC LIMIT 100`).execute();if(E.length===0)break;for(let S of E)yield S;if(j=E[E.length-1]?.[V],j==null)break}},async*lazyById(){let j=Y?.primaryKeys[String(_)]??"id",V;while(!0){let E=await(V==null?L`${k()} ORDER BY ${L(String(j))} ASC LIMIT 100`:L`${k()} WHERE ${L(String(j))} > ${V} ORDER BY ${L(String(j))} ASC LIMIT 100`).execute();if(E.length===0)break;for(let S of E)yield S;if(V=E[E.length-1]?.[j],V==null)break}},pipe(j){return j(this)},async count(){let j=h(),V=j.indexOf(" FROM "),D=/ GROUP BY /i.test(j),E;if(D)E=`SELECT COUNT(*) as c FROM (${j}) AS _bqb_count_sub`;else if(V!==-1)E=`SELECT COUNT(*) as c${j.substring(V)}`;else E=`SELECT COUNT(*) as c FROM ${_}`;let S=G(),q=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||m9(S));if(!b.softDeletes?.enabled&&!KZ&&!i&&!v&&!q){let f=$._prepareStatement;if(f){let d=f(E),a=B.length>0?d.all(...B):d.all();return Number(a[0]?.c??0)}}let g=B.length>0?$.unsafe(E,B):$.unsafe(E),p=await Q(g,"select",{signal:v,timeoutMs:i}),[u]=p;return Number(u?.c??0)},async avg(j){let V=h(),D=V.indexOf(" FROM "),E=D!==-1?`SELECT AVG(${j}) as a${V.substring(D)}`:`SELECT AVG(${j}) as a FROM ${_}`,S=G(),q=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||m9(S));if(!b.softDeletes?.enabled&&!KZ&&!i&&!v&&!q){let f=$._prepareStatement;if(f){let d=f(E),a=B.length>0?d.all(...B):d.all();return Number(a[0]?.a??0)}}let g=B.length>0?$.unsafe(E,B):$.unsafe(E),p=await Q(g,"select",{signal:v,timeoutMs:i}),[u]=p;return Number(u?.a??0)},async sum(j){let V=h(),D=V.indexOf(" FROM "),E=D!==-1?`SELECT SUM(${j}) as s${V.substring(D)}`:`SELECT SUM(${j}) as s FROM ${_}`,S=B.length>0?$.unsafe(E,B):$.unsafe(E),q=await Q(S,"select",{signal:v,timeoutMs:i}),[g]=q;return Number(g?.s??0)},async max(j){let V=h(),D=V.indexOf(" FROM "),E=D!==-1?`SELECT MAX(${j}) as m${V.substring(D)}`:`SELECT MAX(${j}) as m FROM ${_}`,S=B.length>0?$.unsafe(E,B):$.unsafe(E),q=await Q(S,"select",{signal:v,timeoutMs:i}),[g]=q;return g?.m},async min(j){let V=h(),D=V.indexOf(" FROM "),E=D!==-1?`SELECT MIN(${j}) as m${V.substring(D)}`:`SELECT MIN(${j}) as m FROM ${_}`,S=B.length>0?$.unsafe(E,B):$.unsafe(E),q=await Q(S,"select",{signal:v,timeoutMs:i}),[g]=q;return g?.m},lockForUpdate(){return K+=" FOR UPDATE",P=null,this},sharedLock(){let j=b.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return K+=` ${j}`,P=null,this},withCTE(j,V){return l(j,"withCTE(name)"),K=`WITH ${j} AS (${String(V.toSQL())}) ${K}`,P=null,this},withRecursive(j,V){return l(j,"withRecursive(name)"),K=`WITH RECURSIVE ${j} AS (${String(V.toSQL())}) ${K}`,P=null,this},execute(){return Q(k(),"select",{signal:v,timeoutMs:i})},values(){return k().values()},toParams(){return[...B]},__rawState(){return{sql:c9(h()),params:[...B]}},raw(){return k().raw()},get rows(){return},get row(){return},cancel(){try{k().cancel()}catch{}}},{get(j,V,D){let E=Reflect.get(j,V,D);if(E!==void 0)return E;if(typeof V==="string"&&(V.startsWith("where")||V.startsWith("orWhere")||V.startsWith("andWhere"))){let S=V.startsWith("orWhere"),q=V.startsWith("andWhere"),g=`${String(_)}|${V}`,p=U.get(g);if(p===void 0){let f=V.replace(/^(?:or|and)?where/i,"");if(!f)U.set(g,""),p="";else{let d=f.charAt(0).toLowerCase()+f.slice(1),a=f.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),JZ=X?Object.keys(X[String(_)]?.columns??{}):[];p=[a,d,d.toLowerCase()].find((SZ)=>JZ.includes(SZ))??a,U.set(g,p)}}if(p==="")return()=>D;let u=p;return(f)=>{if(Array.isArray(f)){let d=PZ(f.length,B.length+1);C(S?"OR":q?"AND":"WHERE",`${u} IN (${d})`),B.push(...f)}else{let d=r(B.length+1);C(S?"OR":q?"AND":"WHERE",`${u} = ${d}`),B.push(f)}return D}}return Reflect.get(j,V,D)}})}return{configure(_){return BX(_),this},id(_){if(!jZ.IDENTIFIER.test(_))throw Error(`[query-builder] Invalid identifier: '${_}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(String(_))},ids(..._){for(let F of _)if(!jZ.IDENTIFIER.test(F))throw Error(`[query-builder] Invalid identifier: '${F}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(_)},select(_,...F){return N(_,F)},selectFrom(_){return N(_)},selectFromSub(_,F){function L(C){return()=>{throw Error(`[query-builder] selectFromSub(...).${C}() is not supported. Apply ${C}() 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.")}}l(String(F),"selectFromSub(alias)");let K=typeof _.__rawState==="function"?_.__rawState():null,I=_.toSQL(),B=K?.sql??(typeof I==="string"?I:I?.sql??String(I)),x=K?.params??(Array.isArray(I?.values)?I.values:[]),P=`SELECT * FROM (${B}) AS ${String(F)}`,k=(C,y,M,h)=>{let m=[...C],n=(T,c,i)=>{l(T,"selectFromSub where(column)");let v=qZ(c,"selectFromSub where(operator)");if(v==="in"||v==="not in"){let o=Array.isArray(i)?i:[i],KZ=PZ(o.length,m.length+1);return m.push(...o),`${T} ${v.toUpperCase()} (${KZ})`}let t=r(m.length+1);return m.push(i),`${T} ${v} ${t}`},s;if(typeof y==="string"&&M!==void 0)s=n(y,M,h);else if(Array.isArray(y)&&y.length===3)s=n(y[0],y[1],y[2]);else if(y&&typeof y==="object"){let T=Object.entries(y).map(([c,i])=>n(c,"=",i));s=T.length>1?`(${T.join(" AND ")})`:T[0]}else return{clause:null,params:C};return{clause:s,params:m}};function w(C,y,M,h=""){let m=Z9(y),n=m?`${C} WHERE ${m}${h}`:`${C}${h}`,s=()=>M.length>0?$.unsafe(n,M):$.unsafe(n),T=(v,t,o,KZ)=>{let AZ=k(M,t,o,KZ);return AZ.clause===null?w(C,y,M,h):w(C,[...y,{conn:v,sql:AZ.clause}],AZ.params,h)},c=(v,t)=>{let o=[],KZ=[...M],AZ=(BZ)=>($8,l8,s8)=>{let F8=k(KZ,$8,l8,s8);if(F8.clause!==null)o.push({conn:BZ,sql:F8.clause}),KZ=F8.params;return mZ},mZ={where:AZ("AND"),andWhere:AZ("AND"),orWhere:AZ("OR")};t(mZ);let x8=Z9(o);if(!x8)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return w(C,[...y,{conn:v,sql:`(${x8})`}],KZ,h)},i={distinct(){return w(C.replace(/^SELECT\s+/i,"SELECT DISTINCT "),y,M,h)},distinctOn(...v){let t=v.map(String).join(", ");return w(C.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${t}) `),y,M,h)},selectRaw(v){let t=$9(v,"selectFromSub.selectRaw(fragment)"),o=C.indexOf(" FROM "),KZ=o!==-1?`${C.slice(0,o)}, ${t}${C.slice(o)}`:`${C}, ${t}`;return w(KZ,y,M,h)},$call(v){return v(this)??this},where(v,t,o){return T("AND",v,t,o)},andWhere(v,t,o){return T("AND",v,t,o)},orWhere(v,t,o){return T("OR",v,t,o)},whereGroup(v){return c("AND",v)},orWhereGroup(v){return c("OR",v)},orderBy(v,t="asc"){l(String(v),"selectFromSub.orderBy(column)");let o=t==="asc"?"ASC":"DESC",KZ=jZ.ORDER_BY.test(h)?`${h}, ${v} ${o}`:`${h} ORDER BY ${v} ${o}`;return w(C,y,M,KZ)},limit(v){if(!Number.isInteger(v)||v<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${v}`);let t=jZ.LIMIT.test(h)?h.replace(jZ.LIMIT,` LIMIT ${v}`):`${h} LIMIT ${v}`;return w(C,y,M,t)},offset(v){if(!Number.isInteger(v)||v<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${v}`);let t=jZ.OFFSET.test(h)?h.replace(jZ.OFFSET,` OFFSET ${v}`):`${h} OFFSET ${v}`;return w(C,y,M,t)},toSQL(){return O(s(),n)},async execute(){return Q(s(),"select")},async executeTakeFirst(){let v=await Q(s(),"select");return Array.isArray(v)?v[0]:v},async executeTakeFirstOrThrow(){let v=await Q(s(),"select"),t=Array.isArray(v)?v[0]:v;if(!t)throw Error("Record not found");return t},async get(){return Q(s(),"select")},async first(){let v=await Q(s(),"select");return Array.isArray(v)?v[0]:v},async firstOrFail(){let v=await Q(s(),"select"),t=Array.isArray(v)?v[0]:v;if(!t)throw Error("No rows found");return t},async count(){let v=M.length>0?$.unsafe(`SELECT COUNT(*) as c FROM (${n}) as sub`,M):$.unsafe(`SELECT COUNT(*) as c FROM (${n}) as sub`),t=await Q(v,"select");return Number(t?.[0]?.c??0)},async exists(){let v=M.length>0?$.unsafe(`SELECT EXISTS(${n}) as e`,M):$.unsafe(`SELECT EXISTS(${n}) as e`),t=await Q(v,"select");return Boolean(t?.[0]?.e)},async doesntExist(){return!await i.exists()},values(){return s().values()},raw(){return s().raw()},cancel(){try{s().cancel()}catch{}},whereRaw:L("whereRaw"),whereColumn:L("whereColumn"),orWhereColumn:L("orWhereColumn"),whereIn:L("whereIn"),orWhereIn:L("orWhereIn"),whereNotIn:L("whereNotIn"),orWhereNotIn:L("orWhereNotIn"),whereLike:L("whereLike"),whereILike:L("whereILike"),orWhereLike:L("orWhereLike"),orWhereILike:L("orWhereILike"),whereNotLike:L("whereNotLike"),whereNotILike:L("whereNotILike"),orWhereNotLike:L("orWhereNotLike"),orWhereNotILike:L("orWhereNotILike"),whereAny:L("whereAny"),whereAll:L("whereAll"),whereNone:L("whereNone"),whereNested:L("whereNested"),orWhereNested:L("orWhereNested"),whereDate:L("whereDate"),whereBetween:L("whereBetween"),whereNotBetween:L("whereNotBetween"),whereJsonContains:L("whereJsonContains"),whereJsonPath:L("whereJsonPath"),whereNull:L("whereNull"),orWhereNull:L("orWhereNull"),whereNotNull:L("whereNotNull"),orWhereNotNull:L("orWhereNotNull"),whereExists:L("whereExists"),orWhereExists:L("orWhereExists"),orWhereBetween:L("orWhereBetween"),orWhereRaw:L("orWhereRaw"),whereJsonDoesntContain:L("whereJsonDoesntContain"),whereJsonContainsKey:L("whereJsonContainsKey"),whereJsonDoesntContainKey:L("whereJsonDoesntContainKey"),whereJsonLength:L("whereJsonLength"),join:L("join"),joinSub:L("joinSub"),innerJoin:L("innerJoin"),leftJoin:L("leftJoin"),leftJoinSub:L("leftJoinSub"),rightJoin:L("rightJoin"),crossJoin:L("crossJoin"),crossJoinSub:L("crossJoinSub"),groupBy:L("groupBy"),groupByRaw:L("groupByRaw"),having:L("having"),havingRaw:L("havingRaw"),addSelect:L("addSelect"),select:L("select"),selectAll:L("selectAll"),orderByDesc:L("orderByDesc"),inRandomOrder:L("inRandomOrder"),reorder:L("reorder"),orderByRaw:L("orderByRaw"),union:L("union"),unionAll:L("unionAll"),forPage:L("forPage"),selectAllRelations:L("selectAllRelations"),with:L("with"),value:L("value"),pluck:L("pluck"),cursorPaginate:L("cursorPaginate"),paginate:L("paginate"),simplePaginate:L("simplePaginate"),chunk:L("chunk"),chunkById:L("chunkById"),eachById:L("eachById"),avg:L("avg"),sum:L("sum"),max:L("max"),min:L("min"),find:L("find"),findOrFail:L("findOrFail"),findMany:L("findMany"),latest:L("latest"),oldest:L("oldest"),lazy:L("lazy"),lazyById:L("lazyById"),pipe:(v)=>v(i),when:L("when"),tap:()=>i,dump:()=>i,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>s().simple(),toText:()=>n,toParams:()=>[...M],withTimeout:()=>i,abort:()=>i,lockForUpdate:()=>i,sharedLock:()=>i,withCTE:()=>i,withRecursive:()=>i,cache:()=>i,clone:()=>i,withTrashed:()=>i,onlyTrashed:()=>i,scope:()=>i,get rows(){return[]},get row(){return}};return i}return w(P,[],x)},insertInto(_){let F,L="",K=[],I=[],B=!1,x=()=>k?[]:{changes:0,lastInsertRowid:0},P=()=>{let M=async()=>{return},h=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>P(),andWhere:()=>P(),orWhere:()=>P(),orderBy:()=>P(),limit:()=>P(),offset:()=>P(),toSQL:()=>O(null,""),execute:async()=>[],get:async()=>[],first:M,executeTakeFirst:M,firstOrFail:h,executeTakeFirstOrThrow:h}},k=b.dialect==="postgres",w=(M)=>{let m=M.length>0&&!M.includes("*")?M.map((T)=>C(T)).join(", "):"*",n=async()=>{let T=await Q($.unsafe(L,K),"insert"),c=Number(T?.lastInsertRowid??0),i=Math.max(1,Number(T?.affectedRows??1)),v=I.filter((KZ)=>KZ!==void 0&&KZ!==null),t=c>0?$.unsafe(`SELECT ${m} FROM ${C(String(_))} WHERE ${C("id")} >= ? AND ${C("id")} < ? ORDER BY ${C("id")} ASC`,[c,c+i]):v.length>0?$.unsafe(`SELECT ${m} FROM ${C(String(_))} WHERE ${C("id")} IN (${v.map(()=>"?").join(", ")}) ORDER BY ${C("id")} ASC`,v):null;if(!t)return[];let o=await t.execute();return Array.isArray(o)?o:[]},s=async()=>(await n())[0];return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>O($.unsafe(L,K),L),execute:n,get:n,first:s,executeTakeFirst:s,async firstOrFail(){let T=await s();if(!T)throw Error("Insert with RETURNING returned no rows");return T},async executeTakeFirstOrThrow(){let T=await s();if(!T)throw Error("Insert with RETURNING returned no rows");return T}}},C=k?(M)=>`"${String(M).replace(/"/g,'""')}"`:YZ(b.dialect)?(M)=>`\`${String(M).replace(/`/g,"``")}\``:(M)=>`"${String(M).replace(/"/g,'""')}"`,y=k?(M)=>`$${M+1}`:(M)=>"?";return{values(M){let h=Array.isArray(M)?M:[M],m=h.length;if(I=h.map((v)=>v?.id),m===0)return B=!0,F=null,L="",K.length=0,this;B=!1;let n=h[0],s=Object.keys(n),T=s.length,c=m*T;K.length=c;let i=k?s.map((v)=>C(v)).join(","):s.join(",");if(m===1)if(!k){let v=C(s[0]),t="?";K[0]=n[s[0]];for(let o=1;o<T;o++)v+=`,${C(s[o])}`,t+=",?",K[o]=n[s[o]];L=`INSERT INTO ${C(_)}(${v})VALUES(${t})`}else{L=`INSERT INTO ${C(_)}(${i})VALUES(`;for(let v=0;v<T;v++){if(v>0)L+=",";L+=y(v),K[v]=n[s[v]]}L+=")"}else{let v=s.map((o)=>C(o)).join(",");L=`INSERT INTO ${C(_)}(${v})VALUES`;let t=0;for(let o=0;o<m;o++){let KZ=h[o];if(o===0)L+="(";else L+="),(";for(let AZ=0;AZ<T;AZ++){if(AZ>0)L+=",";L+=y(t),K[t++]=KZ[s[AZ]]}}L+=")"}if(!$._prepareStatement)F=$.unsafe(L,K);return this},returning(...M){if(B)return P();if(YZ(b.dialect))return w(M);let h=`${L} RETURNING ${M.join(", ")}`,m=$.unsafe(h,K),n=async()=>{let s=await Q(m,"insert");return Array.isArray(s)?s[0]:s};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>O(m,h),execute:()=>Q(m,"insert"),get:()=>Q(m,"insert"),first:n,executeTakeFirst:n,async firstOrFail(){let s=await n();if(!s)throw Error("Insert with RETURNING returned no rows");return s},async executeTakeFirstOrThrow(){let s=await n();if(!s)throw Error("Insert with RETURNING returned no rows");return s}}},toSQL(){if(B)return O(null,"");if(!F)F=$.unsafe(L,K);return O(F,L)},execute(){if(B)return Promise.resolve(x());let M=G();if(!(M&&(M.onQueryStart||M.onQueryEnd||M.onQueryError||M.startSpan||M.beforeCreate||M.afterCreate||m9(M)))){let m=$._prepareStatement;if(m){let n=m(L);return K.length>0?n.run(...K):n.run()}}if(!F)F=$.unsafe(L,K);return Q(F,"insert")},async executeTakeFirst(){if(B)return x();if(!F)F=$.unsafe(L,K);return await Q(F,"insert")},async executeTakeFirstOrThrow(){if(B)throw Error("Insert failed");if(!F)F=$.unsafe(L,K);let M=await Q(F,"insert");if(!M)throw Error("Insert failed");return M},returningAll(){if(B)return P();let M=`${L} RETURNING *`,h=$.unsafe(M,K),m=async()=>{let n=await Q(h,"insert");return Array.isArray(n)?n[0]:n};return{toSQL:()=>O(h,M),execute:()=>Q(h,"insert"),get:()=>Q(h,"insert"),first:m,executeTakeFirst:m,async firstOrFail(){let n=await m();if(!n)throw Error("Insert with RETURNING returned no rows");return n},async executeTakeFirstOrThrow(){let n=await m();if(!n)throw Error("Insert with RETURNING returned no rows");return n}}}}},updateTable(_){let F,L=[],K=(B)=>{let x=String(B);if(YZ(b.dialect))return`\`${x.replace(/`/g,"``")}\``;return`"${x.replace(/"/g,'""')}"`},I=`UPDATE ${K(String(_))}`;return{set(B){let x=Object.keys(B),P=x.length,k=Array.from({length:P});for(let w=0;w<P;w++){let C=x[w],y=B[C];if(C8(y))k[w]=`${K(C)} = ${y.raw}`;else if(r$(y)){let M=a$(y,L.length+1);k[w]=`${K(C)} = ${M.text}`,L.push(...M.parameters)}else k[w]=`${K(C)} = ${r(L.length+1)}`,L.push(y)}return I=`${I} SET ${k.join(", ")}`,F=$.unsafe(I,L),this},where(B,x,P){let k=()=>jZ.WHERE.test(I)?"AND":"WHERE";if(x!==void 0&&(typeof B==="string"||C8(B)||r$(B))){let w=qZ(x,"updateTable.where"),C;if(typeof B==="string")C=K(B);else if(C8(B))C=B.raw;else{let M=a$(B,L.length+1);C=M.text,L.push(...M.parameters)}if(w.toLowerCase()==="in"||w.toLowerCase()==="not in"){let M=Array.isArray(P)?P:[P],h=PZ(M.length,L.length+1);return I=`${I} ${k()} ${C} ${w.toUpperCase()} (${h})`,L.push(...M),F=$.unsafe(I,L),this}let y=L.length+1;return I=`${I} ${k()} ${C} ${w} ${r(y)}`,L.push(P),F=$.unsafe(I,L),this}if(Array.isArray(B)){let[w,C,y]=B,M=qZ(C,"updateTable.where");if(M.toLowerCase()==="in"||M.toLowerCase()==="not in"){let m=Array.isArray(y)?y:[y],n=PZ(m.length,L.length+1);return I=`${I} ${k()} ${K(String(w))} ${M.toUpperCase()} (${n})`,L.push(...m),F=$.unsafe(I,L),this}let h=L.length+1;return I=`${I} ${k()} ${K(String(w))} ${M} ${r(h)}`,L.push(y),F=$.unsafe(I,L),this}if(C8(B))return I=`${I} ${k()} ${B.raw}`,F=$.unsafe(I,L),this;if(r$(B)){let w=a$(B,L.length+1);return I=`${I} ${k()} ${w.text}`,L.push(...w.parameters),F=$.unsafe(I,L),this}if(B&&typeof B==="object"){let w=Object.keys(B);if(w.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 C=w.length,y=L.length,M=Array.from({length:C});for(let h=0;h<C;h++)M[h]=`${K(w[h])} = ${r(y+h+1)}`,L.push(B[w[h]]);return I=`${I} ${k()} ${M.join(" AND ")}`,F=$.unsafe(I,L),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${B===null?"null":typeof B}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(B){let x=jZ.WHERE.test(I)?"AND":"WHERE";return I=`${I} ${x} ${K(String(B))} IS NULL`,F=$.unsafe(I,L),this},whereNotNull(B){let x=jZ.WHERE.test(I)?"AND":"WHERE";return I=`${I} ${x} ${K(String(B))} IS NOT NULL`,F=$.unsafe(I,L),this},returning(...B){let x=this,P=()=>`${I} RETURNING ${B.join(", ")}`,k=()=>L.length>0?$.unsafe(P(),L):$.unsafe(P()),w=async()=>{let M=await Q(k(),"update");return Array.isArray(M)?M[0]:M},C=(M)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${M}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},y={where:(...M)=>{return x.where(...M),y},andWhere:(...M)=>{return x.where(...M),y},whereNull:(...M)=>{return x.whereNull(...M),y},whereNotNull:(...M)=>{return x.whereNotNull(...M),y},orWhere:C("orWhere"),orderBy:C("orderBy"),limit:C("limit"),offset:C("offset"),toSQL:()=>O(k(),P()),execute:()=>Q(k(),"update"),get:()=>Q(k(),"update"),first:w,executeTakeFirst:w,async firstOrFail(){let M=await w();if(!M)throw Error("Update with RETURNING returned no rows");return M},async executeTakeFirstOrThrow(){let M=await w();if(!M)throw Error("Update with RETURNING returned no rows");return M}};return y},toSQL(){if(!F)F=L.length>0?$.unsafe(I,L):$.unsafe(I);return O(F,I)},async execute(){let B=await Q(F,"update");return R(B)},async executeTakeFirst(){return{numUpdatedRows:R(await Q(F,"update"))}},async executeTakeFirstOrThrow(){let B=R(await Q(F,"update"));if(B===0)throw Error("No rows updated");return{numUpdatedRows:B}},returningAll(){let B=()=>`${I} RETURNING *`,x=()=>L.length>0?$.unsafe(B(),L):$.unsafe(B());return{toSQL:()=>O(x(),B()),execute:()=>Q(x(),"update"),async executeTakeFirst(){let P=await Q(x(),"update");return Array.isArray(P)?P[0]:P},async executeTakeFirstOrThrow(){let P=await Q(x(),"update"),k=Array.isArray(P)?P[0]:P;if(!k)throw Error("Update with RETURNING failed");return k}}}}},deleteFrom(_){let F=(w)=>{let C=String(w);if(YZ(b.dialect))return`\`${C.replace(/`/g,"``")}\``;return`"${C.replace(/"/g,'""')}"`},K=`DELETE FROM ${F(String(_))}`,I=null,B=[],x=null,P=()=>jZ.WHERE.test(K)?"AND":"WHERE",k=()=>{if(I===null)I=B.length>0?$.unsafe(K,B):$.unsafe(K);return I};return{where(w,C,y){if(x=w,typeof w==="string"&&C!==void 0){let M=qZ(C,"deleteFrom.where");if(M.toLowerCase()==="in"||M.toLowerCase()==="not in"){let m=Array.isArray(y)?y:[y],n=PZ(m.length,B.length+1);return K+=` ${P()} ${F(w)} ${M.toUpperCase()} (${n})`,B.push(...m),I=null,this}let h=B.length+1;return K+=` ${P()} ${F(w)} ${M} ${r(h)}`,B.push(y),I=null,this}if(Array.isArray(w)){let[M,h,m]=w,n=qZ(h,"deleteFrom.where");if(n.toLowerCase()==="in"||n.toLowerCase()==="not in"){let T=Array.isArray(m)?m:[m],c=PZ(T.length,B.length+1);return K+=` ${P()} ${F(String(M))} ${n.toUpperCase()} (${c})`,B.push(...T),I=null,this}let s=B.length+1;return K+=` ${P()} ${F(String(M))} ${n} ${r(s)}`,B.push(m),I=null,this}if(C8(w))return K+=` ${P()} ${w.raw}`,I=null,this;if(r$(w)){let M=a$(w,B.length+1);return K+=` ${P()} ${M.text}`,B.push(...M.parameters),I=null,this}if(w&&typeof w==="object"){let M=Object.keys(w);if(M.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 h=[];for(let m of M){let n=B.length+1;h.push(`${F(m)} = ${r(n)}`),B.push(w[m])}return K+=` ${P()} ${h.join(" AND ")}`,I=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${w===null?"null":typeof w}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(w){return K+=` ${P()} ${F(String(w))} IS NULL`,I=null,this},whereNotNull(w){return K+=` ${P()} ${F(String(w))} IS NOT NULL`,I=null,this},returning(...w){let C=this,y=()=>`${K} RETURNING ${w.join(", ")}`,M=()=>B.length>0?$.unsafe(y(),B):$.unsafe(y()),h=async()=>{await G()?.beforeDelete?.({table:String(_),where:x});let T=await Q(M(),"delete");try{await G()?.afterDelete?.({table:String(_),where:x,result:T})}catch{}return T},m=async()=>{let T=await h();return Array.isArray(T)?T[0]:T},n=(T)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${T}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},s={where:(...T)=>{return C.where(...T),s},andWhere:(...T)=>{return C.where(...T),s},whereNull:(...T)=>{return C.whereNull(...T),s},whereNotNull:(...T)=>{return C.whereNotNull(...T),s},orWhere:n("orWhere"),orderBy:n("orderBy"),limit:n("limit"),offset:n("offset"),toSQL:()=>O(M(),y()),execute:()=>h(),get:()=>h(),first:m,executeTakeFirst:m,async firstOrFail(){let T=await m();if(!T)throw Error("Delete with RETURNING returned no rows");return T},async executeTakeFirstOrThrow(){let T=await m();if(!T)throw Error("Delete with RETURNING returned no rows");return T}};return s},toSQL(){return O(k(),K)},async execute(){try{await G()?.beforeDelete?.({table:String(_),where:x})}catch(C){throw C}let w=R(await Q(k(),"delete"));try{await G()?.afterDelete?.({table:String(_),where:x,result:w})}catch{}return w},async executeTakeFirst(){return{numDeletedRows:R(await Q(k(),"delete"))}},async executeTakeFirstOrThrow(){let w=R(await Q(k(),"delete"));if(w===0)throw Error("No rows deleted");return{numDeletedRows:w}},returningAll(){let w=()=>`${K} RETURNING *`,C=()=>B.length>0?$.unsafe(w(),B):$.unsafe(w());return{toSQL:()=>O(C(),w()),execute:()=>Q(C(),"delete"),async executeTakeFirst(){let y=await Q(C(),"delete");return Array.isArray(y)?y[0]:y},async executeTakeFirstOrThrow(){let y=await Q(C(),"delete"),M=Array.isArray(y)?y[0]:y;if(!M)throw Error("Delete with RETURNING failed");return M}}}}},table(_){let F=this;return{insert(L){return F.insertInto(_).values(L)},update(L){return F.updateTable(_).set(L)},delete(){return F.deleteFrom(_)},select(...L){if(L.length===0)return F.selectFrom(_);return F.select(_,...L)}}},sql:$,raw(_,...F){return $(_,...F)},simple(_,...F){return $(_,...F).simple()},async advisoryLock(_){if(b.dialect==="postgres"){let F=J(_),L=$`SELECT pg_advisory_lock(${F})`;await Q(L,"raw");return}if(YZ(b.dialect)){let F=`bqb:${String(_)}`,L=$`SELECT GET_LOCK(${F}, -1) AS ok`;await Q(L,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(_){if(b.dialect==="postgres"){let F=J(_),L=$`SELECT pg_try_advisory_lock(${F}) as ok`,K=await Q(L,"raw");return Boolean(K?.[0]?.ok)}if(YZ(b.dialect)){let F=`bqb:${String(_)}`,L=$`SELECT GET_LOCK(${F}, 0) AS ok`,K=await Q(L,"raw");return Number(K?.[0]?.ok)===1}return!1},async advisoryUnlock(_){if(b.dialect==="postgres"){let F=J(_),L=$`SELECT pg_advisory_unlock(${F}) as ok`,K=await Q(L,"raw");return Boolean(K?.[0]?.ok)}if(YZ(b.dialect)){let F=`bqb:${String(_)}`,L=$`SELECT RELEASE_LOCK(${F}) AS ok`,K=await Q(L,"raw");return Number(K?.[0]?.ok)===1}return!1},unsafe(_,F){return $.unsafe(_,F)},file(_,F){return $.file(_,F)},async reserve(){let _=await ZZ.reserve(),F=XZ({sql:_,meta:Y,schema:X,hooks:Z?.hooks});return F.release=()=>_.release(),F},async close(_){await ZZ.close(_)},async listen(_,F){},async unlisten(_){},async notify(_,F){},async copyTo(_,F){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(_,F,L){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let _=$`SELECT 1`;return await Q(_,"select"),!0}catch{return!1}},async waitForReady(_){let F=Math.max(1,_?.attempts??10),L=Math.max(10,_?.delayMs??100);for(let K=0;K<F;K++){if(await this.ping())return;await new Promise((I)=>setTimeout(I,L))}throw Error("Database not ready after waiting")},async transaction(_,F){let K={...Z?.txDefaults,...F},I=Z?.sql??ZZ,B=Z?.inTransaction===!0,x=B&&typeof I?.savepoint==="function"?"savepoint":"begin",P=async(C)=>{K.logger?.({type:"start",attempt:C});let y=Date.now();return await I[x](async(M)=>{let h=XZ({sql:M,meta:Y,schema:X,hooks:Z?.hooks,inTransaction:!0});if(K?.isolation&&!B){let s=K.isolation,T=s==="read committed"?"READ COMMITTED":s==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(b.dialect==="postgres")await M.unsafe(`SET TRANSACTION ISOLATION LEVEL ${T}`);else if(YZ(b.dialect))await M.unsafe(`SET TRANSACTION ISOLATION LEVEL ${T}`);else if(s!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${s}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(K?.readOnly)if(b.dialect==="postgres")await M.unsafe("SET TRANSACTION READ ONLY");else if(YZ(b.dialect))await M.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let m=await _(h),n=Date.now()-y;return K.logger?.({type:"commit",attempt:C,durationMs:n}),m})},k=Math.max(0,K?.retries??0),w=0;for(;;)try{let C=await P(w+1);return K?.afterCommit?.(),C}catch(C){let y=B6(C)||R6(C,K.sqlStates);if(w<k&&y){w++,K?.onRetry?.(w,C);let M=I6(w,K.backoff);if(M>0)await O6(M);continue}try{K.onRollback?.(C)}catch{}try{K.afterRollback?.()}catch{}throw C}},async savepoint(_){if(Z?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let F=$;if(!F||typeof F.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await F.savepoint(async(L)=>{let K=XZ({sql:L,meta:Y,schema:X,hooks:Z?.hooks,inTransaction:!0});return await _(K)})},async beginDistributed(_,F){return await(Z?.sql??ZZ).beginDistributed(_,async(I)=>{let B=XZ({sql:I,meta:Y,schema:X,hooks:Z?.hooks});return await F(B)})},async commitDistributed(_){await ZZ.commitDistributed(_)},async rollbackDistributed(_){await ZZ.rollbackDistributed(_)},setTransactionDefaults(_){Z={...Z,txDefaults:{...Z?.txDefaults,..._}}},transactional(_,F){return(...L)=>{return this.transaction((K)=>_(K,...L),F)}},async insertOrIgnore(_,F){let L=Array.isArray(F)?F:[F];if(!L.length)return;let{colsSql:K,valuesSql:I,params:B}=t$(L),x=oZ(String(_)),P=YZ(b.dialect)?`INSERT IGNORE INTO ${x} (${K}) VALUES ${I}`:`INSERT INTO ${x} (${K}) VALUES ${I} ON CONFLICT DO NOTHING`;return $.unsafe(P,B).execute()},async insertGetId(_,F,L="id"){let{colsSql:K,valuesSql:I,params:B}=t$([F]),x=oZ(String(_));if(YZ(b.dialect)){await $.unsafe(`INSERT INTO ${x} (${K}) VALUES ${I}`,B).execute();let[k]=await $.unsafe("SELECT LAST_INSERT_ID() as id").execute();return k?.id}if(b.dialect==="sqlite"){let k=await $.unsafe(`INSERT INTO ${x} (${K}) VALUES ${I}`,B).execute();if(k?.lastInsertRowid!=null)return k.lastInsertRowid;let[w]=await $.unsafe("SELECT last_insert_rowid() as id").execute();return w?.id}let[P]=await $.unsafe(`INSERT INTO ${x} (${K}) VALUES ${I} RETURNING ${oZ(String(L))} as id`,B).execute();return P?.id},async updateOrInsert(_,F,L){let K=oZ(String(_)),I=Object.keys(F),B=1,x=I.map((M)=>`${oZ(M)} = ${r(B++)}`).join(" AND "),P=I.map((M)=>F[M]);if((await $.unsafe(`SELECT 1 FROM ${K} WHERE ${x} LIMIT 1`,P).execute()).length){let M=Object.keys(L),h=1,m=M.map((T)=>`${oZ(T)} = ${r(h++)}`).join(", "),n=I.map((T)=>`${oZ(T)} = ${r(h++)}`).join(" AND "),s=[...M.map((T)=>L[T]),...I.map((T)=>F[T])];return await $.unsafe(`UPDATE ${K} SET ${m} WHERE ${n}`,s).execute(),!0}let{colsSql:w,valuesSql:C,params:y}=t$([{...F,...L}]);return await $.unsafe(`INSERT INTO ${K} (${w}) VALUES ${C}`,y).execute(),!0},async upsert(_,F,L,K){let I=L.map((m)=>String(m)),B=(K??[]).map((m)=>String(m)),x=F;if(!x.length)return;let{colsSql:P,valuesSql:k,params:w}=t$(x),C=oZ(String(_)),y=`INSERT INTO ${C} (${P}) VALUES ${k}`;if(YZ(b.dialect)){if(B.length===0)return $.unsafe(`INSERT IGNORE INTO ${C} (${P}) VALUES ${k}`,w).execute();let m=B.map((n)=>`${oZ(n)} = VALUES(${oZ(n)})`).join(", ");return $.unsafe(`${y} ON DUPLICATE KEY UPDATE ${m}`,w).execute()}let M=I.map(oZ).join(", ");if(B.length===0)return $.unsafe(`${y} ON CONFLICT (${M}) DO NOTHING`,w).execute();let h=B.map((m)=>`${oZ(m)} = EXCLUDED.${oZ(m)}`).join(", ");return $.unsafe(`${y} ON CONFLICT (${M}) DO UPDATE SET ${h}`,w).execute()},async save(_,F){let L=Y?.primaryKeys[String(_)]??"id",K=F[L];if(K!=null)if(await this.selectFrom(_).find(K)){await this.updateTable(_).set(F).where({[L]:K}).execute();let B=await this.selectFrom(_).find(K);if(!B)throw Error("save() failed to retrieve updated row");return B}else return await this.create(_,F);return await this.create(_,F)},async remove(_,F){return await this.deleteFrom(_).where({id:F}).execute()},async find(_,F){return await this.selectFrom(_).find(F)},async findOrFail(_,F){return await this.selectFrom(_).findOrFail(F)},async findMany(_,F){return await this.selectFrom(_).findMany(F)},async latest(_,F){return await this.selectFrom(_).latest(F).first()},async oldest(_,F){return await this.selectFrom(_).oldest(F).first()},skip(_,F){return this.selectFrom(_).offset(F)},async rawQuery(_){let F=Date.now();try{G()?.onQueryStart?.({sql:_,kind:"raw"});let L=await $.unsafe(_);return G()?.onQueryEnd?.({sql:_,durationMs:Date.now()-F,kind:"raw"}),L}catch(L){throw G()?.onQueryError?.({sql:_,error:L,durationMs:Date.now()-F,kind:"raw"}),L}},async create(_,F){let L=Y?.primaryKeys[String(_)]??"id";try{await G()?.beforeCreate?.({table:String(_),data:F})}catch(K){throw K}if(b.dialect==="postgres"){let K=$`INSERT INTO ${$(String(_))} ${$(F)} RETURNING ${$(String(L))} as id`,[I]=await K.execute();if(!I?.id)throw console.error(`create() failed to get insert ID for table ${String(_)}`),console.error("Inserted values:",F),Error(`create() failed to get insert ID for table ${String(_)}`);let B=await this.selectFrom(_).find(I.id);if(!B)throw console.error(`create() failed to retrieve inserted row for table ${String(_)} with id ${I.id}`),console.error("Inserted values:",F),Error(`create() failed to retrieve inserted row for table ${String(_)} with id ${I.id}`);try{await G()?.afterCreate?.({table:String(_),data:F,result:B})}catch{}return B}else{let K=await this.insertGetId(_,F,L);if(K==null)throw Error(`create() failed to get insert ID for table ${String(_)}`);let I=await this.selectFrom(_).find(K);if(!I)throw console.error(`create() failed to retrieve inserted row for table ${String(_)} with id ${K}`),console.error("Inserted values:",F),Error(`create() failed to retrieve inserted row for table ${String(_)} with id ${K}`);try{await G()?.afterCreate?.({table:String(_),data:F,result:I})}catch{}return I}},async createMany(_,F){if(!F?.length)return;let L=F[0],K=Object.keys(L),I=K.length,B=F.length,x=Array.from({length:B*I}),P=YZ(b.dialect)?(C)=>`\`${String(C).replace(/`/g,"``")}\``:(C)=>`"${String(C).replace(/"/g,'""')}"`,k=`INSERT INTO ${P(String(_))}(${K.map(P).join(",")})VALUES`,w=0;for(let C=0;C<B;C++){if(C>0)k+=",";k+="(";let y=F[C];for(let M=0;M<I;M++){if(M>0)k+=",";k+=r(w+1),x[w++]=y[K[M]]}k+=")"}return $.unsafe(k,x).execute()},async insertMany(_,F){if(!F?.length)return;let L=F[0],K=Object.keys(L),I=K.length,B=F.length,x=B*I,P=Array(x),k=b.dialect==="postgres",w;if(!k){let M=Array(I);for(let h=0;h<I;h++)M[h]="?";w=`(${M.join(",")})`}else w="";let C=Array(B+2);C[0]=`INSERT INTO ${_}(${K.join(",")})VALUES`;let y=0;if(!k){for(let M=0;M<B;M++){let h=F[M];C[M+1]=w;for(let m=0;m<I;m++)P[y++]=h[K[m]]}return $.unsafe(C[0]+C.slice(1,B+1).join(","),P).execute()}for(let M=0;M<B;M++){let h=F[M],m=Array(I);for(let n=0;n<I;n++)m[n]=`$${y+1}`,P[y++]=h[K[n]];C[M+1]=`(${m.join(",")})`}return $.unsafe(C[0]+C.slice(1,B+1).join(","),P).execute()},async updateMany(_,F,L){let K=Object.keys(L),I=K.length;if(I===0)return 0;let B=[],x=Array.from({length:I});for(let k=0;k<I;k++)x[k]=`${K[k]}=${r(k+1)}`,B.push(L[K[k]]);let P=`UPDATE ${_} SET ${x.join(",")}`;if(Array.isArray(F))P+=` WHERE ${F[0]}${F[1]}${r(B.length+1)}`,B.push(F[2]);else if(F&&typeof F==="object"&&!("raw"in F)){let k=Object.keys(F),w=k.length;if(w>0){let C=B.length,y=Array.from({length:w});for(let M=0;M<w;M++)y[M]=`${k[M]}=${r(C+M+1)}`,B.push(F[k[M]]);P+=` WHERE ${y.join(" AND ")}`}}return $.unsafe(P,B).execute()},async deleteMany(_,F){if(!Array.isArray(F)||F.length===0)return 0;let L=Y?.primaryKeys[String(_)]??"id",K=F.length;if(b.dialect==="postgres"){let B=Array(K);for(let x=0;x<K;x++)B[x]=`$${x+1}`;return $.unsafe(`DELETE FROM ${_} WHERE ${L} IN (${B.join(",")})`,F).execute()}let I=Array(K);for(let B=0;B<K;B++)I[B]="?";return $.unsafe(`DELETE FROM ${_} WHERE ${L} IN (${I.join(",")})`,F).execute()},async firstOrCreate(_,F,L){let K=await this.selectFrom(_).where(F).first();if(K)return K;return await this.create(_,{...F,...L})},async updateOrCreate(_,F,L){let K=await this.selectFrom(_).where(F).first();if(K){await this.updateTable(_).set(L).where(F).execute();let I=Y?.primaryKeys[String(_)]??"id",B=K[I],x=B!=null?await this.selectFrom(_).find(B):await this.selectFrom(_).where(F).first();if(!x)throw Error("updateOrCreate() failed to retrieve updated row");return x}return await this.create(_,{...F,...L})},async count(_,F){let L=F?$(String(F)):$`*`,K=$`SELECT COUNT(${L}) as c FROM ${$(String(_))}`,[I]=await K.execute();return Number(I?.c??0)},async sum(_,F){let L=$`SELECT SUM(${$(String(F))}) as s FROM ${$(String(_))}`,[K]=await L.execute();return Number(K?.s??0)},async avg(_,F){let L=$`SELECT AVG(${$(String(F))}) as a FROM ${$(String(_))}`,[K]=await L.execute();return Number(K?.a??0)},async min(_,F){let L=$`SELECT MIN(${$(String(F))}) as m FROM ${$(String(_))}`,[K]=await L.execute();return K?.m},async max(_,F){let L=$`SELECT MAX(${$(String(F))}) as m FROM ${$(String(_))}`,[K]=await L.execute();return K?.m},getRelationships(_){if(!Y?.relations)return{};let F=Y.relations[_];if(!F)return{};let L={};for(let[K,I]of Object.entries(F))if(I&&typeof I==="object"&&Object.keys(I).length>0)L[K]=I;return L},hasRelationship(_,F){if(!Y?.relations)return!1;let L=Y.relations[_];if(!L)return!1;return Object.values(L).some((K)=>K&&typeof K==="object"&&(F in K))},getRelationshipType(_,F){if(!Y?.relations)return null;let L=Y.relations[_];if(!L)return null;for(let[K,I]of Object.entries(L))if(I&&typeof I==="object"&&F in I)return K;return null},getRelationshipTarget(_,F){if(!Y?.relations)return null;let L=Y.relations[_];if(!L)return null;for(let[K,I]of Object.entries(L))if(I&&typeof I==="object"&&F in I){let B=I[F];if(typeof B==="string")return Y.modelToTable[B]||B;else if(B&&typeof B==="object"){if("model"in B)return Y.modelToTable[B.model]||B.model;if("target"in B)return Y.modelToTable[B.target]||B.target}}return null}}}function vX(){Z7.clear()}function yX(Z){Z7.setMaxSize(Z)}async function M6(){console.log("-- Clearing query cache..."),vX(),console.log("-- \u2713 Query cache cleared")}async function w6(){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 C6(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");yX($),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 $7 from"process";import{createInterface as S6}from"readline";async function hX(){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=XZ(),$=S6({input:$7.stdin,output:$7.stdout,prompt:"qb> "}),Y="",X=!1,J=`
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
113
  Available Commands:
114
114
  .help Show this help message
115
115
  .exit Exit the console
@@ -128,7 +128,7 @@ Tips:
128
128
  - Use 'await' for async operations
129
129
  - Multi-line input: end with \\ to continue on next line
130
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(),$7.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(`
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
132
  SELECT name FROM sqlite_master
133
133
  WHERE type = 'table'
134
134
  AND name NOT LIKE 'sqlite_%'
@@ -138,11 +138,11 @@ Tips:
138
138
  `;return}if(z)await G(z)};$.on("line",async(H)=>{await U(H),$.prompt()}),$.on("SIGINT",()=>{if(X)console.log(`
139
139
  -- Multi-line input cancelled`),Y="",X=!1,$.prompt();else console.log(`
140
140
  -- Type .exit to quit`),$.prompt()}),$.on("close",()=>{console.log(`
141
- Goodbye!`),$7.exit(0)}),$.prompt()}async function N6(){return hX()}TZ();import{existsSync as P6,readFileSync as T6,writeFileSync as u9}from"fs";async function q6(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=XZ().selectFrom(Z);if(J)U=U.limit(J);let H=await U.execute();if(console.log(`-- Retrieved ${H.length} rows`),Y==="json")u9(X,JSON.stringify(H,null,2)),console.log(`-- \u2713 Exported to JSON: ${X}`);else if(Y==="csv"){if(H.length===0){u9(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((R)=>{let O=W[R];if(O===null||O===void 0)return"";let N=String(O);if(N.includes(",")||N.includes('"')||N.includes(`
142
- `))return`"${N.replace(/"/g,'""')}"`;return N});A.push(Q.join(","))}u9(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((R)=>{let O=A[R];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(", ")});`)}u9(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 k6(Z,$,Y={}){if(!P6($))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=XZ();if(J)await G.deleteFrom(Z).execute(),console.log("-- Table truncated");let U=T6($,"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((R)=>R.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((R)=>R.trim());for(let R=1;R<W.length;R++){let O=W[R].split(",").map((_)=>_.trim()),N={};for(let _=0;_<Q.length;_++){let F=O[_];if(F.startsWith('"')&&F.endsWith('"'))F=F.slice(1,-1).replace(/""/g,'"');if(F==="")F=null;else if(!Number.isNaN(Number(F)))F=Number(F);N[Q[_]]=F}H.push(N)}}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 x6(Z={}){let $=b.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=XZ(),G=[];if($==="sqlite")G=(await J.unsafe(`
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
146
  SELECT name FROM sqlite_master
147
147
  WHERE type = 'table'
148
148
  AND name NOT LIKE 'sqlite_%'
@@ -159,8 +159,8 @@ Goodbye!`),$7.exit(0)}),$.prompt()}async function N6(){return hX()}TZ();import{e
159
159
  WHERE table_schema = DATABASE()
160
160
  AND table_type = 'BASE TABLE'
161
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((R)=>{let O=A[R];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("")}u9(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}}TZ();async function bX(){let Z=b.dialect||"postgres",$=b.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${Z}`),console.log(`-- Database: ${$}`),console.log();try{let Y=XZ(),X=[],J=[];if(Z==="postgres")J=(await Y.unsafe(`
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
164
  SELECT table_name
165
165
  FROM information_schema.tables
166
166
  WHERE table_schema = 'public'
@@ -182,38 +182,38 @@ Goodbye!`),$7.exit(0)}),$.prompt()}async function N6(){return hX()}TZ();import{e
182
182
  SELECT COUNT(*) as count
183
183
  FROM information_schema.columns
184
184
  WHERE table_name = $1
185
- `,[U]);A=Number(Q[0]?.count||0);let R=await Y.unsafe(`
185
+ `,[U]);A=Number(Q[0]?.count||0);let L=await Y.unsafe(`
186
186
  SELECT COUNT(*) as count
187
187
  FROM pg_indexes
188
188
  WHERE tablename = $1
189
- `,[U]);W=Number(R[0]?.count||0)}else if(YZ(Z)){let Q=await Y.unsafe(`
189
+ `,[U]);W=Number(L[0]?.count||0)}else if(YZ(Z)){let Q=await Y.unsafe(`
190
190
  SELECT COUNT(*) as count
191
191
  FROM information_schema.columns
192
192
  WHERE table_name = ?
193
193
  AND table_schema = DATABASE()
194
- `,[U]);A=Number(Q[0]?.count||0);let R=await Y.unsafe(`
194
+ `,[U]);A=Number(Q[0]?.count||0);let L=await Y.unsafe(`
195
195
  SELECT COUNT(*) as count
196
196
  FROM information_schema.statistics
197
197
  WHERE table_name = ?
198
198
  AND table_schema = DATABASE()
199
- `,[U]);W=Number(R[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),R=(A.columns||0).toString().padStart(10),O=(A.indexes||0).toString().padStart(10);console.log(`${W}${Q}${R}${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 v6(){return bX()}TZ();b8();async function fX(Z={}){let $=p$(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 ZZ`VACUUM FULL ANALYZE ${ZZ(X)}`;else await ZZ`VACUUM ANALYZE ${ZZ(X)}`}else{if(Z.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(Y)await ZZ`VACUUM FULL`,await ZZ`ANALYZE`;else await ZZ`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 ZZ`OPTIMIZE TABLE ${ZZ(X)}`,await ZZ`ANALYZE TABLE ${ZZ(X)}`}else{let X=c$(),J=await ZZ`
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
200
  SELECT table_name
201
201
  FROM information_schema.tables
202
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 ZZ`OPTIMIZE TABLE ${ZZ(U)}`,await ZZ`ANALYZE TABLE ${ZZ(U)}`}}console.log("\u2713 MySQL optimization complete")}else if($==="sqlite"){if(Z.verbose)console.log("Running VACUUM on SQLite database...");if(await ZZ`VACUUM`,Z.tables&&Z.tables.length>0)for(let X of Z.tables){if(Z.verbose)console.log(`Analyzing table: ${X}`);await ZZ`ANALYZE ${ZZ(X)}`}else await ZZ`ANALYZE`;if(Y){if(Z.verbose)console.log("Running aggressive SQLite optimizations...");await ZZ`PRAGMA optimize`,await ZZ`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}}TZ();b8();async function gX(Z={}){let $=p$(Z.dialect);if(Z.verbose)console.log(`Wiping all tables from ${$} database...`);try{let Y=[];if($==="postgres")Y=(await ZZ`
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
204
  SELECT tablename
205
205
  FROM pg_tables
206
206
  WHERE schemaname = 'public'
207
- `).map((J)=>J.tablename);else if(YZ($)){let X=c$();Y=(await ZZ`
207
+ `).map((J)=>J.tablename);else if(YZ($)){let X=s$();Y=(await $Z`
208
208
  SELECT table_name
209
209
  FROM information_schema.tables
210
210
  WHERE table_schema = ${X}
211
- `).map((G)=>G.table_name||G.TABLE_NAME)}else if($==="sqlite")Y=(await ZZ`
211
+ `).map((G)=>G.table_name||G.TABLE_NAME)}else if($==="sqlite")Y=(await $Z`
212
212
  SELECT name
213
213
  FROM sqlite_master
214
214
  WHERE type = 'table'
215
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 ZZ`DROP TABLE IF EXISTS ${ZZ(X)} CASCADE`}else if(YZ($)){await ZZ`SET FOREIGN_KEY_CHECKS = 0`;for(let X of Y){if(Z.verbose)console.log(`Dropping table: ${X}`);await ZZ`DROP TABLE IF EXISTS ${ZZ(X)}`}await ZZ`SET FOREIGN_KEY_CHECKS = 1`}else if($==="sqlite"){await ZZ`PRAGMA foreign_keys = OFF`;for(let X of Y){if(Z.verbose)console.log(`Dropping table: ${X}`);await ZZ`DROP TABLE IF EXISTS ${ZZ(X)}`}await ZZ`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${Y.length} tables`)}catch(Y){throw console.error("Error wiping database:",Y.message),Y}}async function y6(Z){let X=await(XZ().raw([Z]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(X,null,2)),X}async function h6(Z,$={}){let Y=XZ(),X=$.params?JSON.parse($.params):void 0,J=await Y.file(Z,X);return console.log(JSON.stringify(J)),J}TZ();async function pX(Z,$={}){let Y=b.dialect||"postgres",X=$.verbose??!0;if(X)console.log(`-- Inspecting table: ${Z}`),console.log(`-- Dialect: ${Y}`),console.log();try{let J=XZ(),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(`
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
217
  SELECT
218
218
  c.column_name,
219
219
  c.data_type,
@@ -255,7 +255,7 @@ Goodbye!`),$7.exit(0)}),$.prompt()}async function N6(){return hX()}TZ();import{e
255
255
  JOIN pg_class c ON c.relname = i.indexname
256
256
  JOIN pg_index ix ON ix.indexrelid = c.oid
257
257
  WHERE i.tablename = $1
258
- `,[Z]);for(let Q of W){let R=Q.indexdef?.match(/\(([^)]+)\)/),N=(R?R[1]:"").split(",").map((_)=>_.trim());U.push({name:Q.name,columns:N,unique:Q.is_unique})}}else if(YZ(Y)){let A=await J.unsafe(`
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
259
  SELECT
260
260
  COLUMN_NAME as column_name,
261
261
  DATA_TYPE as data_type,
@@ -266,9 +266,9 @@ Goodbye!`),$7.exit(0)}),$.prompt()}async function N6(){return hX()}TZ();import{e
266
266
  WHERE TABLE_NAME = ?
267
267
  AND TABLE_SCHEMA = DATABASE()
268
268
  ORDER BY ORDINAL_POSITION
269
- `,[Z]);for(let R of A)G.push({name:R.column_name,type:R.data_type,nullable:R.is_nullable==="YES",default:R.column_default,isPrimaryKey:R.column_key==="PRI",isForeignKey:R.column_key==="MUL"});let W=await J.unsafe(`
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
270
  SHOW INDEXES FROM ${Z}
271
- `),Q=new Map;for(let R of W){let O=R.Key_name;if(!Q.has(O))Q.set(O,{columns:[],unique:R.Non_unique===0});Q.get(O).columns.push(R.Column_name)}for(let[R,O]of Q)U.push({name:R,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 R=await J.unsafe(`PRAGMA index_info(${Q.name})`);U.push({name:Q.name,columns:R.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((N)=>N.name.length),10),W=Math.max(...G.map((N)=>N.type.length),10),Q=A+2,R=W+2,O=`${"Name".padEnd(Q)+"Type".padEnd(R)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(O),console.log("-".repeat(O.length));for(let N of G){let _=N.name.padEnd(Q),F=N.type.padEnd(R),L=(N.nullable?"YES":"NO").padEnd(10),K=String(N.default||"").padEnd(20),I=[N.isPrimaryKey?"PK":"",N.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${_}${F}${L}${K}${I}`)}if(console.log(),U.length>0){console.log("Indexes:"),console.log();for(let N of U){let _=N.unique?" (UNIQUE)":"";console.log(` - ${N.name}${_}: [${N.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 b6(Z,$={}){return pX(Z,$)}async function f6(Z,$={}){let Y=await W8({modelsDir:Z}),X=Y7(Y);return console.log(JSON.stringify(X,null,2)),{models:Y,schema:X}}TZ();function dX(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 g6(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 p6(Z){return Z.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join("")}function z0(Z){return p6(g6(Z))}async function mX(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 d6(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,
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
272
  (SELECT COUNT(*) FROM information_schema.table_constraints tc
273
273
  JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
274
274
  WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
@@ -277,7 +277,7 @@ Goodbye!`),$7.exit(0)}),$.prompt()}async function N6(){return hX()}TZ();import{e
277
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
278
  FROM information_schema.columns
279
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 cX(Z,$){let Y=z0(Z),X=$.find((G)=>G.isPrimaryKey)?.name??"id",J=$.map((G)=>{let U=[`type: '${dX(G.sqlType)}'`];if(!G.nullable&&!G.isPrimaryKey)U.push("required: true");return` ${G.name}: { ${U.join(", ")} },`}).join(`
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
281
  `);return`export const ${Y} = defineModel({
282
282
  name: '${Y}',
283
283
  table: '${Z}',
@@ -286,12 +286,12 @@ Goodbye!`),$7.exit(0)}),$.prompt()}async function N6(){return hX()}TZ();import{e
286
286
  ${J}
287
287
  },
288
288
  })
289
- `}async function H0(Z={}){let $=b.dialect||"postgres",Y=XZ(),X=Z.tables?.length?Z.tables:await mX(Y,$),J=[];for(let G of X){let U=await d6(Y,$,G);if(!U.length)continue;J.push({table:G,modelName:z0(G),primaryKey:U.find((H)=>H.isPrimaryKey)?.name??"id",columns:U,source:cX(G,U)})}return J}function A0(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 m6(Z,$,Y){return A0(String($||Z||""),"mysql",{enumValues:Y})}function c6(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 D9(Z){let $=String(Z??"").toLowerCase().trim();if($==="cascade"||$==="restrict"||$==="set null")return $;return}async function u6(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:D9(Q.on_delete),onUpdate:D9(Q.on_update)});let z=[],A=new Set;for(let Q of X){let R=String(Q.origin??""),O=String(Q.name??"");if(R==="pk"||O.startsWith("sqlite_autoindex_"))continue;let _=(await Z.unsafe(`PRAGMA index_info(${JSON.stringify(O)})`)).map((L)=>String(L.name)).filter(Boolean);if(_.length===0)continue;let F=Number(Q.unique)===1;if(F&&_.length===1)A.add(_[0]);z.push({name:O,columns:_,type:F?"unique":"index"})}let W=Y.map((Q)=>{let R=String(Q.name),O=n6(U,R),N=Number(Q.pk)>0,_=Q.dflt_value,F=_!==null&&_!==void 0;return{name:R,type:A0(String(Q.type??""),"sqlite",{enumValues:O}),isPrimaryKey:N,isUnique:A.has(R),isNullable:N?!1:Number(Q.notnull)===0,hasDefault:F,defaultValue:F?W0(_):void 0,enumValues:O,references:H.get(R)}});return{table:$,columns:W,indexes:z}}function n6(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 W0(Z){if(typeof Z==="number"||typeof Z==="boolean")return Z;return String(Z)}async function uX(Z){let $=await Z.unsafe(`SELECT t.typname AS type_name, e.enumlabel AS label
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
290
  FROM pg_type t
291
291
  JOIN pg_enum e ON e.enumtypid = t.oid
292
292
  JOIN pg_namespace n ON n.oid = t.typnamespace
293
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 i6(Z,$,Y){let X=Y.get($),J=A0(String(Z||$||""),"postgres",{enumValues:X});return X?{type:J,enumValues:X,enumTypeName:$}:{type:J}}async function l6(Z,$,Y){let X=Y??await uX(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,
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
295
  (SELECT COUNT(*) FROM information_schema.table_constraints tc
296
296
  JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
297
297
  WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
@@ -311,7 +311,7 @@ ${J}
311
311
  JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name
312
312
  JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name
313
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 R of U){let O=String(R.constraint_name);z.set(O,(z.get(O)??0)+1)}for(let R of U){let O=String(R.column_name),N=H.get(O),_=String(R.constraint_name),F=z.get(_)===1?[...new Set([...N?.constraintNames??[],_])]:N?.constraintNames;H.set(O,N?{...N,constraintNames:F}:{table:String(R.ref_table),column:String(R.ref_column??"id"),onDelete:D9(R.delete_rule),onUpdate:D9(R.update_rule),constraintNames:F})}let{indexes:A,uniqueColumns:W}=nX($,G.map((R)=>({indexName:String(R.index_name),isUnique:R.is_unique===!0||R.is_unique==="t",isPrimary:R.is_primary===!0||R.is_primary==="t",column:String(R.column_name),where:R.where_clause?String(R.where_clause):void 0}))),Q=J.map((R)=>{let O=String(R.column_name),N=Number(R.is_pk)>0,_=R.column_default==null?null:String(R.column_default),F=_!=null&&/nextval\(/i.test(_),L=_!=null&&!F;return{name:O,...i6(String(R.data_type??""),R.udt_name==null?"":String(R.udt_name),X),isPrimaryKey:N,isUnique:W.has(O),isNullable:N?!1:String(R.is_nullable).toUpperCase()==="YES",hasDefault:L,defaultValue:L?W0(_):void 0,references:H.get(O)}});return{table:$,columns:Q,indexes:A}}async function s6(Z,$){let Y=await Z.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
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
315
  FROM information_schema.columns
316
316
  WHERE table_name = ? AND table_schema = DATABASE()
317
317
  ORDER BY ordinal_position`,[$]),X=await Z.unsafe(`SELECT index_name, non_unique, seq_in_index, column_name
@@ -322,7 +322,7 @@ ${J}
322
322
  FROM information_schema.key_column_usage kcu
323
323
  JOIN information_schema.referential_constraints rc
324
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),R=G.get(Q),O=String(W.constraint_name??W.CONSTRAINT_NAME),N=U.get(O)===1?[...new Set([...R?.constraintNames??[],O])]:R?.constraintNames;G.set(Q,R?{...R,constraintNames:N}:{table:String(W.ref_table??W.REF_TABLE),column:String(W.ref_column??W.REF_COLUMN??"id"),onDelete:D9(W.delete_rule??W.DELETE_RULE),onUpdate:D9(W.update_rule??W.UPDATE_RULE),constraintNames:N})}let{indexes:H,uniqueColumns:z}=nX($,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),R=String(W.column_type??W.COLUMN_TYPE??""),O=o6(R),_=String(W.column_key??W.COLUMN_KEY??"").toUpperCase()==="PRI",F=W.column_default??W.COLUMN_DEFAULT,L=F!=null;return{name:Q,type:m6(W.data_type??W.DATA_TYPE,R,O),isPrimaryKey:_,isUnique:z.has(Q),isNullable:_?!1:String(W.is_nullable??W.IS_NULLABLE).toUpperCase()==="YES",hasDefault:L,defaultValue:L?W0(F):void 0,enumValues:O,maxLength:c6(R),references:G.get(Q)}});return{table:$,columns:A,indexes:H}}function o6(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 nX(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 iX(Z,$={}){let Y=Z||b.dialect||"postgres",X=XZ(),G=(($.tables?.length)?$.tables:await mX(X,Y)).filter((z)=>z!=="migrations"),U=Y==="postgres"?await uX(X):void 0,H=[];for(let z of G){let A;if(Y==="sqlite")A=await u6(X,z);else if(Y==="postgres")A=await l6(X,z,U);else A=await s6(X,z);if(A.columns.length>0)H.push(A)}return{dialect:Y,tables:H}}import{existsSync as j0,mkdirSync as r6,writeFileSync as a6}from"fs";import{dirname as lX,join as Q0}from"path";import sX from"process";function t6(Z){let $=Z;while($!==lX($)){if(j0(Q0($,"package.json")))return $;$=lX($)}return sX.cwd()}async function e6(Z,$={}){let Y=t6(sX.cwd()),X=$.dir||Q0(Y,"app/Models");if(!j0(X))r6(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=Q0(X,U);if(j0(H))throw console.error(`-- Model already exists: ${H}`),Error(`Model already exists: ${H}`);let A=$.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
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
326
  updated_at: { validation: { rule: v.date() } },`:"",W=`import { v } from '@stacksjs/ts-validation'
327
327
  import { defineModel } from 'bun-query-builder'
328
328
 
@@ -342,22 +342,22 @@ ${A}
342
342
  })
343
343
 
344
344
  export default model
345
- `;a6(H,W),console.log(`-- \u2713 Created model: ${H}`),console.log(`-- Table: ${G}`)}async function ZU(Z,$={}){return _0(Z,$)}TZ();import{existsSync as tX,readFileSync as XU,unlinkSync as JU}from"fs";import{join as GU}from"path";import{existsSync as $U}from"fs";import{dirname as oX,isAbsolute as YU,join as aX}from"path";import rX from"process";function V0(Z=rX.cwd()){let $=Z;while($!==oX($)){if($U(aX($,"package.json")))return $;$=oX($)}return rX.cwd()}function S8(Z,$="database/migrations"){let Y=$||"database/migrations";return YU(Y)?Y:aX(Z??V0(),Y)}function UU(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 zU(Z,$=b.dialect){let Y=(G)=>YZ($)?`\`${G}\``:`"${G}"`,X=[],J=[];for(let G of UU(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 HU(Z={}){let $=Z.steps||1,Y=Z.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${$}`),console.log();try{let X=XZ(),J=[];try{J=await X.unsafe(`
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
347
  SELECT migration, executed_at
348
348
  FROM migrations
349
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=S8(void 0,b.migrationDir),H=!1;for(let z of G)try{let A=GU(U,z.migration);if(Y&&tX(A)){let Q=XU(A,"utf8"),{down:R,skipped:O}=zU(Q);for(let N of R)await X.unsafe(N),console.log(`-- \u21A9 ${N}`),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 = ${r(1)}`;if(await X.unsafe(W,[z.migration]),console.log(`-- \u2713 Removed migration record: ${z.migration}`),Z.deleteFiles&&tX(A))JU(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}}TZ();import{existsSync as AU,readdirSync as WU}from"fs";async function eX(){let Z=b.dialect||"postgres",$=K8(Z),Y=S8(void 0,b.migrationDir);if(console.log("-- Migration Status"),console.log(`-- Dialect: ${Z}`),console.log(`-- SQL directory: ${Y}`),console.log(),!AU(Y))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let J=WU(Y).filter((G)=>G.endsWith(".sql")).sort();if(J.length===0)return console.log("-- No migration files found"),[];try{let G=XZ(),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 jU(){return eX()}import{readdirSync as QU}from"fs";import{extname as K0,join as Z1}from"path";import _U from"process";async function $1(Z,$={}){let Y=$.dir||Z1(_U.cwd(),"app/Models");try{let X=QU(Y),J=X.find((W)=>{return W.replace(K0(W),"").toLowerCase()===Z.toLowerCase()});if(!J){console.error(`Model "${Z}" not found in ${Y}`),console.log(`Available models: ${X.filter((W)=>[".ts",".js"].includes(K0(W))).map((W)=>W.replace(K0(W),"")).join(", ")}`);return}let U=await import(Z1(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(`
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
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 R=Q.type||"string",O=Q.required?"(required)":"",N=Q.unique?"(unique)":"",_=Q.default!==void 0?`= ${JSON.stringify(Q.default)}`:"";console.log(` \u2022 ${W}: ${R} ${O} ${N} ${_}`.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 R=Q.type||"unknown",O=Q.model||Q.table||"unknown";console.log(` \u2022 ${W}: ${R} \u2192 ${O}`)}}if(z.scopes&&Object.keys(z.scopes).length>0){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
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
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,R=W.unique?"(unique)":"";console.log(` \u2022 ${W.name||"unnamed"}: [${Q}] ${R}`.trim())}}return console.log(),z}catch(X){throw console.error(`Error loading model "${Z}":`,X.message),X}}async function VU(){let $=await XZ().ping();return console.log($?"OK":"NOT READY"),$}b8();import{readdirSync as KU,readFileSync as Y1,statSync as LU}from"fs";import{extname as X1,join as FU}from"path";async function J1(Z,$={}){let Y=[];try{let X=LU(Z),J=[];if(X.isDirectory())J=KU(Z).filter((z)=>X1(z)===".sql").map((z)=>FU(Z,z));else if(X.isFile()&&X1(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=Y1(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 ZZ`EXPLAIN ${ZZ.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:Y1(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 BU}from"fs";import{join as RU}from"path";import OU from"process";async function G1(Z={}){let $=Z.dir||RU(OU.cwd(),"app/Models"),Y=Z.format||"mermaid";try{let X=await W8({modelsDir:$});if(!X||Object.keys(X).length===0)return console.error("No models found"),"";let J="";if(Y==="mermaid")J=DU(X);else if(Y==="dot")J=EU(X);else return console.error(`Unsupported format: ${Y}`),"";if(Z.output)BU(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 DU(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(","),R=Q?` "${Q}"`:"";$.push(` ${z} ${U}${R}`)}$.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 EU(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)":"",R=A.unique?" (UK)":"";U.push(`${z}: ${W}${Q}${R}`)}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 X7,mkdirSync as IU,readdirSync as MU,writeFileSync as wU}from"fs";import{dirname as U1,join as d8}from"path";import n9 from"process";function J7(Z){let $=Z;while($!==U1($)){if(X7(d8($,"package.json")))return $;$=U1($)}return n9.cwd()}async function z1(Z){if(!X7(Z))return console.log(`-- Seeders directory not found: ${Z}`),[];let Y=MU(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=d8(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 H1(Z={}){let $=J7(n9.cwd()),Y=Z.seedersDir||d8($,"database/seeders"),X=Z.verbose??!0;if(X)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${Y}`);let J=await z1(Y);if(J.length===0){console.log("-- No seeders found");return}if(X)console.log(`-- Found ${J.length} seeder(s)`);let G=XZ();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 CU(Z,$={}){let Y=J7(n9.cwd()),X=d8(Y,"database/seeders"),J=$.verbose??!0;if(J)console.log(`-- Running seeder: ${Z}`);let G=await z1(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=XZ();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 SU(Z){let $=J7(n9.cwd()),Y=d8($,"database/seeders");if(!X7(Y))IU(Y,{recursive:!0}),console.log(`-- Created seeders directory: ${Y}`);let J=`${Z.replace(/Seeder$/i,"")}Seeder`,G=`${J}.ts`,U=d8(Y,G);if(X7(U))throw console.error(`-- Seeder already exists: ${U}`),Error(`Seeder already exists: ${U}`);let H=`import type { QueryBuilder } from 'bun-query-builder'
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
361
  import { Seeder } from 'bun-query-builder'
362
362
  import { faker } from '@stacksjs/ts-faker'
363
363
 
@@ -402,7 +402,7 @@ export default class ${J} extends Seeder {
402
402
  return 100
403
403
  }
404
404
  }
405
- `;wU(U,H),console.log(`-- \u2713 Created seeder: ${U}`)}async function NU(Z={}){let $=J7(n9.cwd()),Y=Z.modelsDir||d8($,"app/Models"),X=Z.seedersDir||d8($,"database/seeders"),J=Z.verbose??!0;try{let{resetDatabase:G,generateMigration:U,executeMigration:H}=await import("./chunk-gp6krpcs.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 H1({seedersDir:X,verbose:J}),J)console.log("-- \u2713 Database refreshed successfully")}catch(G){throw console.error("-- \u2717 Database refresh failed:",G),G}}TZ();function PU(Z,$,Y={}){let X=W8({modelsDir:Z}),J=Y7(X);if(b.debug)b.debug.captureText=!0;let G=XZ({schema:J}),U=G.selectFrom($).limit(Number(Y.limit||10)).toText?.()??"";return console.log(U||"[query]"),{sql:U,qb:G,schema:J}}async function TU(Z,$={}){let Y=XZ(),X=$.params?JSON.parse($.params):void 0,J=await Y.unsafe(Z,X);return console.log(JSON.stringify(J)),J}TZ();import{existsSync as qU}from"fs";import{dirname as A1,join as W1}from"path";import j1 from"process";function kU(Z){let $=Z;while($!==A1($)){if(qU(W1($,"package.json")))return $;$=A1($)}return j1.cwd()}async function Q1(Z){if(!Z)Z=W1(kU(j1.cwd()),"app/Models");let $=b.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${Z}`),console.log(`-- Dialect: ${$}`),console.log();let Y=[];try{let X=await W8({modelsDir:Z}),J=i9(X,{dialect:$}),G=XZ(),U=[];if($==="sqlite")U=(await G.unsafe(`
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
406
  SELECT name FROM sqlite_master
407
407
  WHERE type = 'table'
408
408
  AND name NOT LIKE 'sqlite_%'
@@ -419,27 +419,27 @@ export default class ${J} extends Seeder {
419
419
  WHERE table_schema = DATABASE()
420
420
  AND table_type = 'BASE TABLE'
421
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((N)=>({name:N.name,type:N.type.toLowerCase()}));else if($==="postgres")W=(await G.unsafe(`
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
423
  SELECT column_name, data_type
424
424
  FROM information_schema.columns
425
425
  WHERE table_name = $1
426
- `,[A.table])).map((N)=>({name:N.column_name,type:N.data_type.toLowerCase()}));else if(YZ($))W=(await G.unsafe(`
426
+ `,[A.table])).map((T)=>({name:T.column_name,type:T.data_type.toLowerCase()}));else if(YZ($))W=(await G.unsafe(`
427
427
  SELECT column_name, data_type
428
428
  FROM information_schema.columns
429
429
  WHERE table_name = ?
430
430
  AND table_schema = DATABASE()
431
- `,[A.table])).map((N)=>({name:N.column_name,type:N.data_type.toLowerCase()}));let Q=W.map((O)=>O.name),R=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(!R.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 N=W.find((_)=>_.name===O.name);if(N){let _=(K)=>{return K.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim()},F=_(O.type),L=_(N.type);if(F!==L)Y.push({type:"type_mismatch",severity:"warning",table:A.table,column:O.name,expected:O.type,actual:N.type,message:`Column '${A.table}.${O.name}' type mismatch: expected '${O.type}', found '${N.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 xU(Z){return Q1(Z)}async function vU(Z={}){let $=Number(Z.attempts||10),Y=Number(Z.delay||100),X=XZ();try{return await X.waitForReady({attempts:$,delayMs:Y}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}k1();o9();TZ();class u8{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(Z){this.driver=t8(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 L8{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(Z){this.driver=t8(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 J3(Z){return new u8(Z)}function G3(Z){return new L8(Z)}function U3(Z){let $=t8(Z.config);return{query:()=>new u8(Z),item:()=>new L8(Z),driver:$,registerEntity:(Y)=>$.registerEntity(Y),buildKey:(Y,X)=>$.buildPrimaryKey(Y,X)}}class g1{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 p1{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 L8(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 L8(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 L8(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 L8(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 d1(this.manager,this.entityName,this.options)}async findAll(){let Z=this.manager.typeAttribute??"_type",$=new u8(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 d1{manager;entityName;options;builder;pkValue;skConditions=[];constructor(Z,$,Y){this.manager=Z,this.entityName=$,this.options=Y,this.builder=new u8(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 m1(Z){return new g1(Z)}function c1(Z,$,Y){return new p1(Z,$,Y)}var A3={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 u1(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 eU(Z){return{models:new Map}}function j3(Z){return Z}function Q3(Z){return Z}function _3(Z){return Z}function V3(Z){return Z}class n1{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=t8($);let Y={tableName:Z.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=m1(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 eU({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 c1(this.singleTableManager,Z,this.queryBuilderOptions)}query(Z){if(!this.models.get(Z))throw Error(`Model not found: ${Z}`);return new u8(this.queryBuilderOptions).table(this.config.tableName).entity(Z)}item(Z){if(!this.models.get(Z))throw Error(`Model not found: ${Z}`);return new L8(this.queryBuilderOptions).table(this.config.tableName)}buildKey(Z,$){let Y=this.models.get(Z);if(!Y)throw Error(`Model not found: ${Z}`);let X=u1(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=u1(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 O3(Z){return new n1(Z)}function D3(Z){return Z.accessPatterns}function E3(Z,$="#"){let Y=Z.name.toUpperCase(),X=Z.primaryKey??"id";return{name:Z.name,pkPattern:`${Y}${$}\${${X}}`,skPattern:`${Y}${$}\${${X}}`}}p8();function Y7(Z){let $={};for(let Y of Object.keys(Z)){let X=Z[Y],J=X.definition??X.getDefinition?.()??X,G=f8(J),U=J.attributes??{},H={};for(let z of Object.keys(U))H[z]=void 0;$[G]={columns:H,primaryKey:J.primaryKey??"id"}}return $}F0();p8();import{readdirSync as Z2}from"fs";import{basename as i1,extname as l1,isAbsolute as $2,join as s1}from"path";import Y2 from"process";var X2=new Set([".ts",".mts",".cts",".js",".mjs",".cjs"]);function J2(Z){let $=l1(Z);if(!X2.has($))return!1;let Y=i1(Z,$);if(Y.startsWith("_")||Y==="index")return!1;return!Y.endsWith(".d")}function G2(Z){if(!Z||typeof Z!=="object")return!1;let $=Z;return typeof $.name==="string"||typeof $.table==="string"}function o1(Z){let $=[],Y=Z2(Z,{withFileTypes:!0}).sort((X,J)=>X.name.localeCompare(J.name));for(let X of Y){let J=s1(Z,X.name);if(X.isDirectory()){$.push(...o1(J));continue}if(J2(X.name))$.push(J)}return $}async function W8(Z){let $=Z.cwd??Y2.cwd(),Y=$2(Z.modelsDir)?Z.modelsDir:s1($,Z.modelsDir),X={};for(let J of o1(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(!G2(z))continue;let A=z.name??i1(J,l1(J));X[A]={...z,name:A}}return X}p8();U7();function r1(Z){let $={},Y={},X={},J={},G={};for(let U of Object.keys(Z)){let H=Z[U],z=H.definition??H.getDefinition?.()??H,A=f8(z);$[U]=A,Y[A]=U,X[A]=z.primaryKey??"id";let W=(O)=>{if(!O)return{};let N={};if(Array.isArray(O)){for(let _ of O){let F=G7(_);if(F)N[F.model]=F.model}return N}if(typeof O==="object"){for(let[_,F]of Object.entries(O)){let L=G7(F);if(L)N[_]=L.model}return N}return{}},Q=(O)=>{if(!O)return{};if(Array.isArray(O)){let N={};for(let _ of O)if(typeof _==="string")N[_]=_;else if(_&&typeof _==="object"&&typeof _.model==="string")N[_.model]=_;return N}return O},R=(O)=>{if(!O)return{};return O};if(J[A]={hasOne:W(z.hasOne),hasMany:W(z.hasMany),belongsTo:W(z.belongsTo),belongsToMany:Q(z.belongsToMany),hasOneThrough:R(z.hasOneThrough),hasManyThrough:R(z.hasManyThrough),morphOne:W(z.morphOne),morphMany:W(z.morphMany),morphTo:z.morphTo,morphToMany:W(z.morphToMany),morphedByMany:W(z.morphedByMany)},z.scopes&&typeof z.scopes==="object"){G[A]={};for(let O of Object.keys(z.scopes)){let N=z.scopes[O];if(typeof N==="function")G[A][O]=N}}}return{modelToTable:$,tableToModel:Y,primaryKeys:X,relations:J,scopes:G,models:Z}}U7();p8();TZ();import{existsSync as x0,mkdirSync as U2,readdirSync as z2,readFileSync as H2,writeFileSync as A2}from"fs";import{dirname as a1,join as W7}from"path";import YJ from"process";function bZ(Z){if(b.verbose)console.log(Z)}function n8(Z){return Z.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}function S0(Z){return g8(b.relations?.singularizeStrategy)(Z)}var a9=0,q8=0,i8=0,j7=!0,Q7=[],S9=null;function XJ(){return[...Q7]}function W2(Z){let $=Z;while($!==a1($)){if(x0(W7($,"package.json")))return $;$=a1($)}return YJ.cwd()}function j2(){let Z=W2(YJ.cwd()),$=S8(Z,b.migrationDir);if(!x0($))U2($,{recursive:!0}),bZ(`-- Created SQL directory: ${$}`);return $}var JJ="-- qb:generated";function GJ(Z){return Z.trimStart().startsWith(JJ)}function UJ(Z){return Z.split(`
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
432
  `).filter(($)=>!$.trimStart().startsWith("--")).join(`
433
- `).replace(/\s+/g," ").trim().replace(/;+$/,"")}function Q2(Z){let $=new Set,Y;try{Y=z2(Z).filter((X)=>X.endsWith(".sql"))}catch{return $}for(let X of Y)try{$.add(UJ(H2(W7(Z,X),"utf8")))}catch{}return $}function zJ(Z,$){if(!Z)return!1;let Y=j2();if(S9===null)S9=Q2(Y);let X=UJ(Z);if(X.length>0&&S9.has(X))return bZ(`-- Migration already in the corpus, not writing it again: ${$}`),!1;a9++;let J=j7?String(a9).padStart(10,"0"):String(Math.floor(Date.now()/1000)+a9),G=`${J}-${$}.sql`;if(!j7){let H=Number(J);while(x0(W7(Y,G)))H+=1,J=String(H),G=`${J}-${$}.sql`}let U=W7(Y,G);return A2(U,`${JJ}
434
- ${Z}`),bZ(`-- Migration file created: ${G}`),q8++,Q7.push(G),S9?.add(X),!0}function _2(Z,$){return Z==="integer"&&$==="bigint"||Z==="string"&&$==="text"}function t1(Z){if(Z.endsWith("_id"))return"bigint";if(Z.endsWith("_at"))return"datetime";if(Z.startsWith("is_")||Z.startsWith("has_"))return"boolean";return}function e1(Z){if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean"||typeof Z==="bigint"||Z instanceof Date)return Z;return}function V2(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 P0(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 T0=767;function K2(Z){if(!Z||typeof Z!=="object")return;let $=Z;if($.name)switch(String($.name).toLowerCase()){case"string":{let X=P0($);return X&&X>T0?"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 L2(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 i9(Z,$){let Y=r1(Z),X=[];for(let H of Object.keys(Z)){let z=Z[H],A=f8(z),W=z.primaryKey??"id",Q=z.autoIncrement!==!1,R=z.attributes??{},O=[],N=[];if(!R[W])O.push({name:n8(W),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});let _=new Map,F=I9(z.belongsTo).length>0,L=new Set(Object.keys(R).map((M)=>n8(M))),K=new Set;for(let M of L){if(!M.endsWith("_type"))continue;let h=`${M.slice(0,-5)}_id`;if(L.has(h))K.add(h)}for(let M of I9(z.belongsTo)){let h=M.foreignKey??`${n8(M.model)}_id`,m=Y.modelToTable[M.model];if(m)_.set(h,{table:m,onDelete:M.onDelete})}for(let M of Object.keys(R)){let h=R[M],m=n8(M),n=Boolean(h.validation?.rule?.isRequired),s=M===W?!1:h.nullable??!(h.required??n),T,c,i=M===W;if(T=L2(h.type)??K2(h.validation?.rule),T==="string"){let o=P0(h.validation?.rule);if(o&&o>T0)T="text"}if(!T||T==="enum"){let o=V2(h.validation?.rule);if(o&&o.length>0)T="enum",c=o}if(!T)T=t1(m);if(!T){let o=e1(h.default);if(typeof o==="string")T=o.length>255?"text":"string";else if(typeof o==="number")T=Number.isInteger(o)?"integer":"float";else if(typeof o==="boolean")T="boolean";else if(typeof o==="bigint")T="bigint";else if(o instanceof Date)T="datetime"}if(!T)T=i?"bigint":"string";let v=T==="string"?P0(h.validation?.rule):void 0,t={name:m,type:T,isPrimaryKey:i,isUnique:Boolean(h.unique),isNullable:s,hasDefault:typeof h.default<"u",defaultValue:e1(h.default),enumValues:c,maxLength:typeof v==="number"&&v>0&&v<=T0?v:void 0};if(m.endsWith("_id")&&h.foreignKey!==!1&&!K.has(m))if(typeof h.foreignKey==="object"&&h.foreignKey!==null){let o=h.foreignKey;if(t.references={table:o.table,column:o.column??"id",onDelete:o.onDelete,onUpdate:o.onUpdate},o.nullable!==void 0)t.isNullable=o.nullable}else{let o=_.get(m),AZ=m.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(x8,BZ,$8)=>$8.toUpperCase()),mZ=o?.table??(F?void 0:Y.modelToTable[AZ]);if(mZ){let x8=Y.primaryKeys[mZ]??"id";t.references={table:mZ,column:x8,onDelete:o?.onDelete}}}O.push(t)}let I=I9(z.belongsTo);for(let M of I){let h=M.foreignKey??`${n8(M.model)}_id`;if(O.some((s)=>s.name===h))continue;let m=Y.modelToTable[M.model],n=m?Y.primaryKeys[m]??"id":void 0;O.push({name:h,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:m&&n&&!K.has(h)?{table:m,column:n,onDelete:M.onDelete}:void 0})}let B=z.traits;if(B?.useTimestamps??B?.timestampable??!1){if(!O.some((M)=>M.name==="created_at"))O.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:T8});if(!O.some((M)=>M.name==="updated_at"))O.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(B?.useSoftDeletes??B?.softDeletable??!1){if(!O.some((M)=>M.name==="deleted_at"))O.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(B?.useUuid??!1){if(!O.some((M)=>M.name==="uuid"))O.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let M of z.indexes??[])N.push({name:M.name,columns:M.columns.map((h)=>n8(h)),type:M.unique?"unique":"index",where:M.where});for(let M of O)if(M.isUnique&&!M.isPrimaryKey)N.push({name:`${A}_${M.name}_unique`,columns:[M.name],type:"unique"});let w=Array.isArray(z.shardKey)?z.shardKey.map(n8):void 0,C=Array.isArray(z.sortKey)?z.sortKey.map(n8):void 0,y=z.tableKind;X.push({table:A,columns:O,indexes:N,shardKey:w,sortKey:C,tableKind:y})}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=f8(z),Q=S0(W);if(A.likeable){let R=typeof A.likeable==="object"?A.likeable:{},O=R.table||`${W}_likes`,N=R.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:N,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:T8},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${O}_user_target_unique`,columns:["user_id",N],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:T8},{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:T8},{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:T8},{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:T8},{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=f8(z),Q=S0(W);for(let[R,O]of Object.entries(A)){let N=O;if(!N||typeof N!=="object")continue;if(N.through)continue;let _=N.pivot;if(!_||!_.columns&&!_.timestamps&&!_.uniques)continue;let F=N.model,K=Z[F]?.table||`${String(F).toLowerCase()}s`,I=S0(K),B=N.table||[Q,I].sort().join("_"),x=N.foreignKey||`${Q}_id`,P=N.relatedKey||`${I}_id`,k=new Set([x,P,...Object.keys(_.columns??{})]),w=new Set;for(let m of k){if(!m.endsWith("_type"))continue;let n=`${m.slice(0,-5)}_id`;if(k.has(n))w.add(n)}let C=(m,n)=>w.has(m)?void 0:{table:n,column:"id"},y=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:x,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:C(x,W)},{name:P,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:C(P,K)}];if(_.columns)for(let[m,n]of Object.entries(_.columns)){let s=n,T=t1(m)??"string";y.push({name:m,type:T,isPrimaryKey:!1,isUnique:!1,isNullable:s?.nullable??!1,hasDefault:s?.default!==void 0,defaultValue:s?.default})}if(_.timestamps)y.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:T8}),y.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let M=[],h=_.uniques&&_.uniques.length>0?_.uniques:[[x,P]];for(let m=0;m<h.length;m++){let n=h[m];M.push({name:`${B}_${n.join("_")}_unique${m>0?`_${m}`:""}`,columns:[...n],type:"unique"})}G({table:B,columns:y,indexes:M})}}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 _7(Z,$={}){a9=0,q8=0,i8=0,Q7=[],S9=null,j7=!0;let Y=$.dryRun?()=>!1:zJ,X=[],J=K8(Z.dialect,{vitessSharded:Z.vitessSharded}),{tables:G,deferredForeignKeys:U}=HJ(Z.tables,Z.dialect);for(let[z,A]of G.entries()){let W={...A,columns:A.columns.map((_)=>U.has(N9(A.table,_.name))?{..._,references:void 0}:_)},Q=[],R=new Set;for(let _ of W.columns)if(_.type==="enum"&&_.enumValues&&_.enumValues.length>0){let F=`${W.table}_${_.name}_type`;if(_.enumTypeName=F,!R.has(F)){let L=J.createEnumType(F,_.enumValues);if(L)Q.push(L);R.add(F)}}let O=J.createTable(W);Q.push(O);for(let _ of W.indexes)Q.push(J.createIndex(W.table,_,W.columns));if(z===G.length-1)for(let _ of G)for(let F of _.columns){if(!F.references||!U.has(N9(_.table,F.name)))continue;let L=J.addForeignKey(_.table,F.name,F.references.table,F.references.column,F.references.onDelete,F.references.onUpdate);if(L)Q.push(L)}X.push(...Q);let N=Q.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
435
 
436
- `);Y(N,`create-${W.table}-table`)}if(q8+i8===0)bZ("-- Nothing to migrate");else{let z=[];if(q8>0)z.push(`${q8} created`);if(i8>0)z.push(`${i8} updated`);bZ(`-- Migration files: ${z.join(", ")}`)}return X}function N9(Z,$){return`${Z}\x00${$}`}function HJ(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 u3(Z){return _7(Z).join(`
437
- `)}function n3(Z,$){return D2(Z,$).join(`
438
- `)}function AJ(Z){let $=sZ("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 ZJ(Z){let $={};for(let Y of Z)$[Y.table]=Y;return $}function r9(Z){let $={};for(let Y of Z)$[Y.name]=Y;return $}function q0(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 T8="UTC_TIMESTAMP";function k0(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 T8;if($==="sqlite"&&J==="CURRENT_TIMESTAMP")return T8;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 F2(Z,$,Y){if(q0(Z,Y)!==q0($,Y))return!0;if(Z.isNullable!==$.isNullable)return!0;if(Z.hasDefault!==$.hasDefault)return!0;if(k0(Z,Y)!==k0($,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 $J(Z,$){return JSON.stringify([q0(Z,$),Z.isPrimaryKey,Z.isUnique,Z.isNullable,Z.hasDefault,k0(Z,$)??null,(Z.enumValues??[]).slice().sort(),Z.references?[Z.references.table,Z.references.column,Z.references.onDelete??null,Z.references.onUpdate??null]:null])}function B2(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=$J(Z[W],Y),R=G.get(Q)??[];R.push(W),G.set(Q,R)}for(let W of J){let Q=$J($[W],Y),R=U.get(Q)??[];R.push(W),U.set(Q,R)}let H=[],z=new Set,A=new Set;for(let[W,Q]of G){let R=U.get(W);if(Q.length===1&&R&&R.length===1)H.push({from:Q[0],to:R[0]}),z.add(Q[0]),A.add(R[0])}return{renames:H,removed:X.filter((W)=>!z.has(W)),added:J.filter((W)=>!A.has(W))}}function R2(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 O2(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 WJ(Z,$){return`${Z.type}:${A8($,Z.name)}:${Z.columns.join(",")}`}function N0(Z,$){let Y={};for(let X of Z)Y[WJ(X,$)]=X;return Y}function v0(Z,$,Y={}){if(!Z||Z.dialect!==$.dialect){let K=_7($,{dryRun:Y.dryRun}),I=$.tables.map((B)=>({kind:"create_table",table:B.table,destructive:!1,sql:""}));return{statements:K,operations:I}}let X=Y.applyRenames!==!1,J=Y.preserveUnknownColumns===!0,G=Y.dryRun?()=>!1:zJ;a9=0,q8=0,i8=0,Q7=[],S9=null,j7=!1;let U=[],H=[],z=K8($.dialect,{vitessSharded:$.vitessSharded}),A=$.dialect,W=ZJ(Z.tables),Q=ZJ($.tables);for(let K of Object.keys(W))if(!Q[K]){let I=z.dropTable(K);U.push(I),H.push({kind:"drop_table",table:K,destructive:!0,sql:I}),G(I,`drop-${K}-table`),bZ(`-- Detected dropped table: ${K}`)}let R=Object.keys(Q).filter((K)=>!W[K]).map((K)=>Q[K]),{tables:O,deferredForeignKeys:N}=HJ(R,A);for(let[K,I]of O.entries()){let B={...I,columns:I.columns.map((C)=>N.has(N9(I.table,C.name))?{...C,references:void 0}:C)},x=[],P=new Set;for(let C of B.columns)if(C.type==="enum"&&C.enumValues&&C.enumValues.length>0){let y=`${B.table}_${C.name}_type`;if(C.enumTypeName=y,!P.has(y)){let M=z.createEnumType(y,C.enumValues);if(M)x.push(M);P.add(y)}}let k=z.createTable(B);x.push(k);for(let C of B.indexes){let y=z.createIndex(B.table,C,B.columns);x.push(y),H.push({kind:"create_index",table:B.table,column:C.name,destructive:!1,sql:y})}for(let C of I.columns)if(C.references&&!N.has(N9(I.table,C.name)))H.push({kind:"add_foreign_key",table:I.table,column:C.name,destructive:!1,sql:k});if(K===O.length-1)for(let C of O)for(let y of C.columns){if(!y.references||!N.has(N9(C.table,y.name)))continue;let M=z.addForeignKey(C.table,y.name,y.references.table,y.references.column,y.references.onDelete,y.references.onUpdate);if(!M)continue;x.push(M),H.push({kind:"add_foreign_key",table:C.table,column:y.name,destructive:!1,sql:M})}U.push(...x),H.push({kind:"create_table",table:B.table,destructive:!1,sql:k});let w=x.join(`
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
439
 
440
- `);G(w,`create-${B.table}-table`)}let _=new Set;for(let K of Object.keys(Q)){let I=W[K],B=Q[K];if(!I)continue;let x=r9(I.columns),P=r9(B.columns);for(let k of Object.keys(P)){let w=P[k];if(w.type!=="enum"||!w.enumValues||w.enumValues.length===0)continue;let C=`${B.table}_${w.name}_type`;if(w.enumTypeName=C,x[k])continue;if(!_.has(C)){let y=z.createEnumType(C,w.enumValues);if(y)U.push(y),H.push({kind:"create_enum",table:B.table,column:w.name,destructive:!1,sql:y}),G(y,`create-${C}-enum`);_.add(C)}}}for(let K of Object.keys(Q)){let I=W[K],B=Q[K];if(!I)continue;let x=r9(I.columns),P=N0(I.indexes,I.table),k=r9(B.columns),w=N0(B.indexes,B.table),C=[],y=Object.keys(x).filter((T)=>!k[T]),M=Object.keys(k).filter((T)=>!x[T]);if(X&&!J){let T=B2(x,k,A);C=T.renames,y=T.removed,M=T.added}if(J){let T=y.map((i)=>x[i]),c=I.indexes.filter((i)=>!w[WJ(i,I.table)]);if(T.length>0||c.length>0){if(T.length>0)bZ(`-- Keeping ${T.length} column(s) on "${B.table}" no model declares: ${y.join(", ")} \u2014 reconciled from the database, where an undeclared column is out of scope rather than removed`);if(c.length>0)bZ(`-- Keeping ${c.length} index(es) on "${B.table}" no model declares: ${c.map((i)=>i.name).join(", ")} \u2014 reconciled from the database, where an undeclared index is out of scope rather than removed`);B={...B,columns:[...B.columns,...T],indexes:[...B.indexes,...c]},k=r9(B.columns),w=N0(B.indexes,B.table)}y=[]}let h=Object.keys(k).filter((T)=>x[T]&&F2(x[T],k[T],A)),m=Object.keys(k).filter((T)=>x[T]&&O2(x[T].references,k[T].references));if(A==="sqlite"){if(h.length>0||m.length>0||y.some((c)=>R2(I,c))){let c={},i=new Map(C.map((AZ)=>[AZ.to,AZ.from]));for(let AZ of B.columns)if(x[AZ.name])c[AZ.name]=AZ.name;else if(i.has(AZ.name))c[AZ.name]=i.get(AZ.name);let v=`_qb_tmp_${B.table}`,t=0;while((W[v]||Q[v])&&t<100)t+=1,v=`_qb_tmp_${B.table}_${t}`;let o=z.rebuildTable({target:B,tempName:v,columnSource:c});U.push(o);let KZ=h.some((AZ)=>x[AZ].type!==k[AZ].type);H.push({kind:"rebuild_table",table:B.table,destructive:y.length>0||KZ,sql:o});for(let AZ of C)H.push({kind:"rename_column",table:B.table,from:AZ.from,to:AZ.to,destructive:!1,confidence:"high",sql:o});for(let AZ of y)H.push({kind:"drop_column",table:B.table,column:AZ,destructive:!0,sql:o});bZ(`-- Detected SQLite table rebuild required: ${B.table}`),G(o,`alter-${B.table}-table`);continue}}let n=[],s=!1;for(let T of Object.keys(P))if(!w[T]){let c=P[T],i=z.dropIndex(B.table,c.name);n.push(i),U.push(i),H.push({kind:"drop_index",table:B.table,column:c.name,destructive:!1,sql:i}),bZ(`-- Detected dropped index: ${c.name} from ${B.table}`),s=!0}for(let T of C){let c=z.renameColumn(B.table,T.from,T.to);n.push(c),U.push(c),H.push({kind:"rename_column",table:B.table,from:T.from,to:T.to,destructive:!1,confidence:"high",sql:c}),bZ(`-- Detected renamed column: ${B.table}.${T.from} -> ${T.to}`),s=!0}for(let T of y){let c=z.dropColumn(B.table,T);n.push(c),U.push(c),H.push({kind:"drop_column",table:B.table,column:T,destructive:!0,sql:c}),bZ(`-- Detected dropped column: ${B.table}.${T}`),s=!0}for(let T of h){let c=x[T],i=k[T],v=z.modifyColumn(B.table,i);n.push(v),U.push(v),H.push({kind:"modify_column",table:B.table,column:T,destructive:c.type!==i.type&&!_2(c.type,i.type),sql:v}),bZ(`-- Detected column change: ${B.table}.${T} (${c.type} -> ${i.type})`),s=!0}for(let T of m){let c=k[T];if(!c.references)continue;let i=z.addForeignKey(B.table,c.name,c.references.table,c.references.column,c.references.onDelete,c.references.onUpdate,x[T].references?.constraintNames);if(!i)continue;n.push(i),U.push(i),H.push({kind:"add_foreign_key",table:B.table,column:T,destructive:!1,sql:i}),bZ(`-- Detected foreign-key change: ${B.table}.${T} -> ${c.references.table}(${c.references.column})`),s=!0}for(let T of M){let c=k[T],i=z.addColumn(B.table,c);if(n.push(i),U.push(i),H.push({kind:"add_column",table:B.table,column:c.name,destructive:!1,sql:i}),bZ(`-- Detected new column: ${B.table}.${c.name}`),s=!0,c.references){let v=z.addForeignKey(B.table,c.name,c.references.table,c.references.column,c.references.onDelete,c.references.onUpdate);if(v)n.push(v),U.push(v),H.push({kind:"add_foreign_key",table:B.table,column:c.name,destructive:!1,sql:v})}}for(let T of Object.keys(w))if(!P[T]){let c=w[T],i=z.createIndex(B.table,c,B.columns);n.push(i),U.push(i),H.push({kind:"create_index",table:B.table,column:c.name,destructive:!1,sql:i}),bZ(`-- Detected new index: ${c.name} in ${B.table}`),s=!0}if(s){let T=n.join(`
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
441
 
442
- `);G(T,`alter-${B.table}-table`)}}if(q8+i8===0)bZ("-- Nothing to migrate");else{let K=[];if(q8>0)K.push(`${q8} created`);if(i8>0)K.push(`${i8} updated`);bZ(`-- Migration files: ${K.join(", ")}`)}return{statements:U.length===0?["-- No changes detected"]:U,operations:H}}function D2(Z,$,Y={}){return v0(Z,$,Y).statements}w0();function l3(Z){return Z}class E2{get order(){return 100}get description(){return}}function o3(Z){return Z}o9();o9();o$();m$();TZ();function jJ(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 QJ(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 _J(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 I2(Z,$={}){let Y=$.dialect??b.dialect,X=Z.tables.map((A)=>A.table),J=await H0({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((R)=>[R.name.toLowerCase(),R]));for(let R of A.columns){let O=Q.get(R.name.toLowerCase()),N=jJ(R.type);if(!O){H.push({table:A.table,column:R.name,expected:N});continue}let _=QJ(O.sqlType);if(!_J(N,_,Y))z.push({table:A.table,column:R.name,expected:N,actual:_,actualSqlType:O.sqlType})}}return{missingTables:U,missingColumns:H,typeMismatches:z,clean:U.length===0&&H.length===0&&z.length===0}}function M2(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 S2(Z,$,Y){if(Y.length===0)return;let X=IJ(U9());try{await MJ(Z,$);for(let J of Y)await V7(Z,J,$),$Z(`-- \u2713 Recorded applied migration: ${J}`)}catch(J){$Z(`-- Could not record applied migrations (the schema change itself succeeded): ${J instanceof Error?J.message:String(J)}`)}}function OJ(Z,$){try{return GJ(t9(Z8(Z,$),"utf8"))}catch{return!1}}function N2(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 $Z(Z){if(b.verbose)console.log(Z)}function DJ(Z){return Z8(Z,b.snapshotDir||".qb")}function b0(Z,$){return Z8(DJ(Z),`model-snapshot.${$}.json`)}function P2(Z,$){let Y=b0(Z,$);if(!k8(Y))return;try{let X=t9(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;$Z("-- Invalid snapshot format, treating as no previous state");return}catch(X){$Z(`-- Could not load snapshot, treating as no previous state: ${X instanceof Error?X.message:String(X)}`);return}}function EJ(Z,$,Y){let X=b0(Z,$),J=DJ(Z),G=AJ(Y);if(k8(X))try{let H=JSON.parse(t9(X,"utf8"));if(H?.hash===G&&H?.dialect===$&&H?.plan){$Z("-- Model snapshot unchanged");return}}catch{}if(!k8(J))LJ(J,{recursive:!0}),$Z(`-- Created snapshot directory: ${J}`);let U={plan:Y,hash:G,dialect:$,updatedAt:new Date().toISOString()};RJ(X,JSON.stringify(U,null,2)),$Z(`-- Model snapshot saved to ${X}`)}function yU(Z,$={}){let Y=$.dialect??Z.dialect;EJ($.workspaceRoot??U9(),Y,Z)}function U9(){return V0()}function IJ(Z){let $=S8(Z,b.migrationDir);if(!k8($))LJ($,{recursive:!0}),$Z(`-- Created SQL directory: ${$}`);return $}async function _0(Z,$={}){if(await d$(),!Z)Z=Z8(h0.cwd(),"app/Models");let Y=$.dialect||b.dialect||"postgres",X=U9(),J=await W8({modelsDir:Z}),G=i9(J,{dialect:Y,vitessSharded:$.vitessSharded}),U,H=!1;if(!$.full)if(U=P2(X,Y),U)$Z("-- Comparing with stored model snapshot");else{let O=Z8(Z,`.qb-migrations.${Y}.json`),N=String($.state||O);if(k8(N))try{let _=t9(N,"utf8"),F=JSON.parse(_);if(U=F?.plan&&F.plan.tables?F.plan:F?.tables?F:void 0,U)$Z("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!U||$.fromDb)try{let _=await iX(Y),F=new Set(G.tables.map((K)=>K.table)),L=_.tables.filter((K)=>F.has(K.table));if(L.length>0)U={dialect:_.dialect,tables:L},H=!0,$Z(`-- No snapshot; reconciling against live database (${L.length} matching table${L.length===1?"":"s"})`)}catch(_){$Z(`-- Could not introspect live database, treating as no previous state: ${_ instanceof Error?_.message:String(_)}`)}if(!U)$Z("-- No previous snapshot found, generating full migration")}else $Z("-- Full migration requested, ignoring any previous state");let z=$.full?{statements:_7(G,{dryRun:$.dryRun}),operations:G.tables.map((O)=>({kind:"create_table",table:O.table,destructive:!1,sql:""}))}:v0(U,G,{applyRenames:$.applyRenames,dryRun:$.dryRun,preserveUnknownColumns:H}),A=z.statements,W=z.operations,Q=A.join(`
444
- `),R=A.some((O)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(O));if($.apply){let O=w2(Z8(C2(),"qb-migrate-")),N=Z8(O,"migration.sql");try{if(R){RJ(N,Q);let _=XZ();await _.file(N),$Z("-- Migration applied"),await S2(_,Y,XJ())}else $Z("-- No changes; nothing to apply")}catch(_){throw console.error("-- Migration failed:",_),_}finally{BJ(O,{recursive:!0,force:!0})}}if(!$.dryRun)EJ(X,Y,G);return{sql:Q,sqlStatements:A,hasChanges:R,plan:G,operations:W}}var VJ="bun-query-builder:migrate",T2=/\bCONCURRENTLY\b|^\s*VACUUM\b|^\s*BEGIN\s*(?:;|TRANSACTION\b)|^\s*PRAGMA\s+foreign_keys\b/im;function KJ(Z){return Z==="postgres"||Z==="sqlite"}async function q2(Z,$){if(Z==="sqlite")return await $();let Y=XZ(),X;try{X=await Y.reserve()}catch{return await $()}let J=!1;try{return await X.advisoryLock(VJ),J=!0,await $()}finally{try{if(J)await X.advisoryUnlock(VJ)}finally{X.release?.()}}}async function hU(Z){await d$();let $=U9(),Y=IJ($),X=b.dialect||"postgres",G=FJ(Y).filter((U)=>U.endsWith(".sql")).sort();if(G.length===0)return $Z("-- No migration files found to execute"),!0;$Z(`-- Found ${G.length} script files to execute`);try{let U=XZ();return await q2(X,async()=>{await MJ(U,X);let H=await y2(U,X),z=G.filter((A)=>!H.includes(A));if(z.length===0)return $Z("-- No pending migrations to execute"),!0;$Z(`-- Executing ${z.length} migration${z.length===1?"":"s"}`);for(let A of z){let W=Z8(Y,A);$Z(`-- Executing: ${A}`);try{if(KJ(X)&&!T2.test(t9(W,"utf-8")))await U.transaction(async(R)=>{await R.file(W),await V7(R,A,X)});else if(await U.file(W),await V7(U,A,X),!KJ(X))$Z(`-- (${X} commits DDL implicitly, so ${A} was not applied atomically)`);else $Z(`-- (${A} contains a statement that cannot run in a transaction, so it was not applied atomically)`);$Z(`-- \u2713 Migration ${A} executed and recorded`)}catch(Q){if(OJ(Y,A)&&N2(Q)){await V7(U,A,X),$Z(`-- \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 $Z("-- All migrations executed successfully"),!0})}catch(U){throw console.error("-- Migration execution failed:",U),U}return!0}async function bU(Z,$={}){if(await d$(),!Z)Z=Z8(h0.cwd(),"app/Models");let Y=$.dialect||b.dialect||"postgres",X=K8(Y),J=U9(),G=async(U)=>{let H=X.dropTable(U);await J0(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"),$Z("-- Dropped migrations table")}catch(z){console.error(z)}let U=[],H=[];try{let z=await W8({modelsDir:Z}),A=i9(z,{dialect:Y});U=A.tables.map((Q)=>Q.table);let W=new Set;for(let Q of A.tables)for(let R of Q.columns)if(R.type==="enum"&&R.enumValues&&R.enumValues.length>0){let O=`${Q.table}_${R.name}_type`;W.add(O)}H=Array.from(W)}catch(z){console.error(z),U=[],H=[]}if(U.length===0)$Z("-- No tables found to drop");else{$Z(`-- Dropping ${U.length} tables: ${U.join(", ")}`);for(let z of U.reverse())try{await G(z),$Z(`-- Dropped table: ${z}`)}catch(A){console.error(A),$Z(`-- Table ${z} may not exist, skipping drop`)}}if(H.length>0){$Z(`-- Dropping ${H.length} enum types: ${H.join(", ")}`);for(let z of H)try{let A=X.dropEnumType(z);if(A)await J0(async(W)=>{await W.unsafe(A).execute(),$Z(`-- Dropped enum type: ${z}`)})}catch(A){console.error(A),$Z(`-- Enum type ${z} may not exist, skipping drop`)}}else $Z("-- No enum types found to drop");if(U.length>0&&!$.preserveMigrationState)try{await k2(Z,J,$)}catch(z){console.error(z),$Z("-- Could not clean up migration files")}else if(U.length===0)$Z("-- No models directory found; keeping committed migration files in place");else $Z("-- Preserving migration files and model snapshot for fresh replay");if(!$.preserveMigrationState)try{await v2(J)}catch(z){console.error(z),$Z("-- Could not clear generated directory")}return $Z("-- Database reset completed successfully"),!0}catch(U){return console.error("-- Database reset failed:",U),!1}}async function k2(Z,$,Y={}){if(!Z)Z=Z8(h0.cwd(),"app/Models");if(!$)$=U9();let X=String(Y.dialect||b.dialect||"postgres"),J=b0($,X);if(k8(J))y0(J),$Z(`-- Removed model snapshot file: ${J}`);let G=Z8(Z,`.qb-migrations.${X}.json`),U=String(Y.state||G);if(k8(U))y0(U),$Z(`-- Removed legacy migration state file: ${U}`);x2(S8($,b.migrationDir))}function x2(Z){if(!k8(Z))return;let $=0,Y=[];for(let X of FJ(Z).filter((J)=>J.endsWith(".sql"))){if(!OJ(Z,X)){Y.push(X);continue}y0(Z8(Z,X)),$Z(`-- Removed generated migration file: ${X}`),$+=1}if($Z(`-- Cleaned up ${$} generated migration file${$===1?"":"s"} from migrations directory`),Y.length>0)$Z(`-- Kept ${Y.length} hand-written migration${Y.length===1?"":"s"}: ${Y.slice(0,5).join(", ")}${Y.length>5?`, +${Y.length-5} more`:""}`)}async function fj(Z,$){}async function v2(Z){if(!Z)Z=U9();let $=Z8(Z,"generated");if(k8($))try{BJ($,{recursive:!0,force:!0}),$Z("-- Cleared generated directory")}catch(Y){console.error("-- Failed to clear generated directory:",Y)}}async function MJ(Z,$){let X=K8($).createMigrationsTable();try{await Z.unsafe(X).execute(),$Z("-- Migrations table ready")}catch(J){throw console.error("-- Failed to create migrations table:",J),J}}async function y2(Z,$){let Y=K8($);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 V7(Z,$,Y){let X=K8(Y);try{$Z(`-- Recording migration: ${$}`),await Z.unsafe(X.recordMigrationQuery(),[$]).execute(),$Z(`-- Successfully recorded migration: ${$}`)}catch(J){throw console.error(`-- Failed to record migration ${$}:`,J),J}}
445
- export{YZ as a,KX as b,b as c,p$ as d,r as e,PZ as f,d$ as g,BX as h,T4 as i,i5 as j,l5 as k,g9 as l,CX as m,A6 as n,U0 as o,f8 as p,W6 as q,j6 as r,g8 as s,e8 as t,DH as u,_6 as v,PH as w,M8 as x,L6 as y,XZ as z,vX as A,yX as B,M6 as C,w6 as D,C6 as E,hX as F,N6 as G,q6 as H,k6 as I,x6 as J,bX as K,v6 as L,fX as M,gX as N,y6 as O,h6 as P,pX as Q,b6 as R,f6 as S,dX as T,z0 as U,cX as V,H0 as W,e6 as X,yZ as Y,u$ as Z,n$ as _,i$ as $,s$ as aa,K8 as ba,yU as ca,_0 as da,hU as ea,bU as fa,k2 as ga,fj as ha,v2 as ia,ZU as ja,HU as ka,eX as la,jU as ma,$1 as na,VU as oa,J1 as pa,G1 as qa,H1 as ra,CU as sa,SU as ta,NU as ua,PU as va,TU as wa,Q1 as xa,xU as ya,vU as za,V1 as Aa,M1 as Ba,L1 as Ca,F1 as Da,oW as Ea,rW as Fa,N1 as Ga,P1 as Ha,aW as Ia,tW as Ja,x1 as Ka,v1 as La,y1 as Ma,h1 as Na,b1 as Oa,C0 as Pa,f1 as Qa,tU as Ra,u8 as Sa,L8 as Ta,J3 as Ua,G3 as Va,U3 as Wa,g1 as Xa,p1 as Ya,d1 as Za,m1 as _a,c1 as $a,A3 as ab,u1 as bb,eU as cb,j3 as db,Q3 as eb,_3 as fb,V3 as gb,n1 as hb,O3 as ib,D3 as jb,E3 as kb,Y7 as lb,W8 as mb,r1 as nb,XJ as ob,JJ as pb,GJ as qb,UJ as rb,_2 as sb,i9 as tb,_7 as ub,u3 as vb,n3 as wb,AJ as xb,q0 as yb,T8 as zb,k0 as Ab,v0 as Bb,D2 as Cb,l3 as Db,E2 as Eb,o3 as Fb,jJ as Gb,QJ as Hb,_J as Ib,I2 as Jb,M2 as Kb};
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};