bun-query-builder 0.2.61 → 0.2.63

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.
@@ -0,0 +1,66 @@
1
+ // @bun
2
+ import{Ne}from"./chunk-7xvyccgk.js";import{Database as Nn}from"bun:sqlite";function A(i){return i==="integer"||i==="bigint"||i==="float"||i==="double"||i==="decimal"}function Pn(i){if(typeof i!=="string")return;switch(i.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 Ae(i){switch(i){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}import ci from"process";import{existsSync as Kn,statSync as Fn}from"fs";import{resolve as ft}from"path";import Oi from"process";import{existsSync as Fi,mkdirSync as $c,readdirSync as kc,readFileSync as Li,writeFileSync as xc}from"fs";import{homedir as Ve}from"os";import{dirname as Sc,resolve as me}from"path";import br from"process";import{existsSync as Ln,statSync as Bn}from"fs";import{existsSync as Yr,mkdirSync as Bi,readdirSync as Ii,writeFileSync as ji}from"fs";import{homedir as ze}from"os";import{dirname as In,resolve as se}from"path";import Le from"process";import{join as Wi,relative as Vi,resolve as jn}from"path";import or from"process";import{existsSync as Cs,mkdirSync as Lc,readdirSync as Bc,writeFileSync as Ic}from"fs";import{homedir as Rr}from"os";import{dirname as Vc,resolve as ne}from"path";import ht from"process";import{join as Ui,relative as qi,resolve as Wn}from"path";import ar from"process";import{existsSync as Ss,mkdirSync as Qc,readdirSync as Gc,writeFileSync as Yc}from"fs";import{dirname as Zc,resolve as cr}from"path";import Jr from"process";import{Buffer as Se}from"buffer";import{createCipheriv as zi,createDecipheriv as Hi,randomBytes as Nr}from"crypto";import{closeSync as _r,createReadStream as Vn,createWriteStream as Qi,existsSync as Or,fsyncSync as Un,openSync as qn,writeFileSync as Gi}from"fs";import{access as Yi,constants as zn,mkdir as Ji,readdir as At,rename as Hn,stat as He,unlink as Rt,writeFile as Pr}from"fs/promises";import{join as Qe}from"path";import X from"process";import{pipeline as Zi}from"stream/promises";import{createGzip as Qn}from"zlib";import Ge from"process";import Te from"process";import{Buffer as we}from"buffer";import{createCipheriv as Xi,createDecipheriv as eo,randomBytes as Kr}from"crypto";import{closeSync as Fr,createReadStream as Gn,createWriteStream as to,existsSync as Nt,fsyncSync as Yn,openSync as Jn,writeFileSync as ro}from"fs";import{access as no,constants as Zn,mkdir as so,readdir as _t,rename as Xn,stat as Ye,unlink as Ot,writeFile as Lr}from"fs/promises";import{isAbsolute as io,join as Je,resolve as oo}from"path";import K from"process";import{pipeline as ao}from"stream/promises";import{createGzip as es}from"zlib";import Ze from"process";import ve from"process";import Pt from"process";import{existsSync as Bt}from"fs";import{resolve as Br}from"path";import{existsSync as co}from"fs";import{existsSync as lo,readdirSync as uo}from"fs";import{extname as Ir,resolve as ts}from"path";import fo from"process";import{join as ho,relative as go,resolve as rs}from"path";import lr from"process";import{Buffer as be}from"buffer";import{createCipheriv as mo,createDecipheriv as yo,randomBytes as jr}from"crypto";import{closeSync as Wr,createReadStream as ns,createWriteStream as po,existsSync as zt,fsyncSync as ss,openSync as is,writeFileSync as wo}from"fs";import{access as bo,constants as os,mkdir as To,readdir as Gt,rename as as,stat as Xe,unlink as Yt,writeFile as Vr}from"fs/promises";import{isAbsolute as vo,join as et,resolve as Do}from"path";import F from"process";import{pipeline as $o}from"stream/promises";import{createGzip as cs}from"zlib";import tt from"process";import De from"process";import Zt from"process";import{existsSync as Xt}from"fs";import{resolve as Ds}from"path";import{existsSync as Va}from"fs";class $s{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,a){let c=a?`:${a}`:"";return`${this.options.keyPrefix}${i}${c}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,c],[,l])=>c.timestamp.getTime()-l.timestamp.getTime()),a=i.length-this.options.maxSize+1;for(let c=0;c<a;c++)this.cache.delete(i[c][0])}set(i,a,c,l){if(!this.options.enabled)return;let u=this.generateKey(i,c),f=l??this.options.ttl,d=this.estimateSize(a);this.cache.set(u,{value:a,timestamp:new Date,ttl:f,hits:0,size:d}),this.evictIfNeeded()}get(i,a){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,a),l=this.cache.get(c);if(!l){this.totalMisses++;return}if(this.isExpired(l)){this.cache.delete(c),this.totalMisses++;return}return l.hits++,this.totalHits++,l.value}isFileModified(i,a){try{if(!Kn(i))return!0;return Fn(i).mtime>a}catch{return!0}}getWithFileCheck(i,a){let c=this.get(i,a);if(!c)return;if(this.isFileModified(a,c.fileTimestamp)){this.delete(i,a);return}return c.value}setWithFileCheck(i,a,c,l){try{let u=Kn(c)?Fn(c):null,f=u?u.mtime:new Date;this.set(i,{value:a,fileTimestamp:f},c,l)}catch{this.set(i,a,c,l)}}delete(i,a){let c=this.generateKey(i,a);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[a,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(a),i++;return i}getStats(){let i=Array.from(this.cache.values()),a=i.reduce((l,u)=>l+u.size,0),c=i.map((l)=>l.timestamp).sort();return{size:a,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:c[0],newestEntry:c[c.length-1]}}export(){let i={};for(let[a,c]of this.cache.entries())i[a]={value:c.value,timestamp:c.timestamp.toISOString(),ttl:c.ttl,hits:c.hits,size:c.size};return i}import(i){this.cache.clear();for(let[a,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let l=c;this.cache.set(a,{value:l.value,timestamp:new Date(l.timestamp),ttl:l.ttl,hits:l.hits,size:l.size})}}}class ks{metrics=[];maxMetrics=1000;async track(i,a,c={}){let l=performance.now(),u=new Date;try{let f=await a(),d=performance.now()-l;return this.recordMetric({operation:i,duration:d,timestamp:u,...c}),f}catch(f){let d=performance.now()-l;throw this.recordMetric({operation:`${i}:error`,duration:d,timestamp:u,...c}),f}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let a=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(a.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=a.map((u)=>u.duration),l=c.reduce((u,f)=>u+f,0);return{count:a.length,averageDuration:l/a.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:l,recentMetrics:a.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((a)=>a.duration>i)}}var ir=new $s,ln=new ks;var xs=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Es(i={}){let{name:a="",alias:c}=i,l=["config",".config"];if(a)l.push(a,`.${a}.config`,`${a}.config`,`.${a}`);let u=c===void 0?[]:Array.isArray(c)?c:[c];for(let f of u){if(!f)continue;if(l.push(f,`.${f}.config`,`${f}.config`,`.${f}`),a)l.push(`${a}.${f}.config`,`.${a}.${f}.config`)}return Array.from(new Set(l.filter(Boolean)))}function Pi(i){return Es(i).flatMap((c)=>xs.map((l)=>ft(i.directory,`${c}${l}`)))}function Ki(i={}){let a=ft(i.cwd||Oi.cwd());return Array.from(new Set([a,ft(a,"config"),ft(a,".config"),i.configDir?ft(a,i.configDir):void 0].filter((c)=>Boolean(c))))}var ko=Object.defineProperty,xo=(i)=>i;function Eo(i,a){this[i]=xo.bind(null,a)}var Co=(i,a)=>{for(var c in a)ko(i,c,{get:a[c],enumerable:!0,configurable:!0,set:Eo.bind(a,c)})},So=(i,a)=>()=>(i&&(a=i(i=0)),a),Ms={};Co(Ms,{withErrorRecovery:()=>Ns,tryLoadConfig:()=>Jo,loadConfigWithResult:()=>Go,loadConfig:()=>Fs,isRetryableError:()=>Vo,isConfigNotFoundError:()=>Wo,isBunfigError:()=>_s,globalPerformanceMonitor:()=>yt,globalCache:()=>rt,getEnvOrDefault:()=>Uo,generateConfigTypes:()=>Zo,defaultGeneratedDir:()=>qs,defaultConfigDir:()=>Us,deepMergeWithArrayStrategy:()=>gn,deepMerge:()=>Os,createLibraryConfig:()=>Xo,config:()=>Yo,bunfigPlugin:()=>ea,applyEnvVarsToConfig:()=>dt,TypeGenerationError:()=>sn,SchemaValidationError:()=>mt,PluginError:()=>an,PerformanceMonitor:()=>fn,FileSystemError:()=>nn,ErrorFactory:()=>_e,EnvVarError:()=>mr,EnvProcessor:()=>Tr,ConfigValidator:()=>mn,ConfigValidationError:()=>tn,ConfigNotFoundError:()=>gr,ConfigMergeError:()=>rn,ConfigLoader:()=>pn,ConfigLoadError:()=>gt,ConfigFileLoader:()=>vr,ConfigCache:()=>un,CacheUtils:()=>Bs,BunfigError:()=>ae,BrowserConfigError:()=>on,ArrayMergeStrategies:()=>Ws});class un{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,a){let c=a?`:${a}`:"";return`${this.options.keyPrefix}${i}${c}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,c],[,l])=>c.timestamp.getTime()-l.timestamp.getTime()),a=i.length-this.options.maxSize+1;for(let c=0;c<a;c++)this.cache.delete(i[c][0])}set(i,a,c,l){if(!this.options.enabled)return;let u=this.generateKey(i,c),f=l??this.options.ttl,d=this.estimateSize(a);this.cache.set(u,{value:a,timestamp:new Date,ttl:f,hits:0,size:d}),this.evictIfNeeded()}get(i,a){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,a),l=this.cache.get(c);if(!l){this.totalMisses++;return}if(this.isExpired(l)){this.cache.delete(c),this.totalMisses++;return}return l.hits++,this.totalHits++,l.value}isFileModified(i,a){try{if(!Ln(i))return!0;return Bn(i).mtime>a}catch{return!0}}getWithFileCheck(i,a){let c=this.get(i,a);if(!c)return;if(this.isFileModified(a,c.fileTimestamp)){this.delete(i,a);return}return c.value}setWithFileCheck(i,a,c,l){try{let u=Ln(c)?Bn(c):null,f=u?u.mtime:new Date;this.set(i,{value:a,fileTimestamp:f},c,l)}catch{this.set(i,a,c,l)}}delete(i,a){let c=this.generateKey(i,a);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[a,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(a),i++;return i}getStats(){let i=Array.from(this.cache.values()),a=i.reduce((l,u)=>l+u.size,0),c=i.map((l)=>l.timestamp).sort();return{size:a,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:c[0],newestEntry:c[c.length-1]}}export(){let i={};for(let[a,c]of this.cache.entries())i[a]={value:c.value,timestamp:c.timestamp.toISOString(),ttl:c.ttl,hits:c.hits,size:c.size};return i}import(i){this.cache.clear();for(let[a,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let l=c;this.cache.set(a,{value:l.value,timestamp:new Date(l.timestamp),ttl:l.ttl,hits:l.hits,size:l.size})}}}class fn{metrics=[];maxMetrics=1000;async track(i,a,c={}){let l=performance.now(),u=new Date;try{let f=await a(),d=performance.now()-l;return this.recordMetric({operation:i,duration:d,timestamp:u,...c}),f}catch(f){let d=performance.now()-l;throw this.recordMetric({operation:`${i}:error`,duration:d,timestamp:u,...c}),f}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let a=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(a.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=a.map((u)=>u.duration),l=c.reduce((u,f)=>u+f,0);return{count:a.length,averageDuration:l/a.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:l,recentMetrics:a.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((a)=>a.duration>i)}}function Mo(i,a={}){let l=Object.keys(a).sort().map((u)=>`${u}:${a[u]}`).join("|");return l?`${i}:${l}`:i}function Ao(i,a){try{return JSON.stringify(i)===JSON.stringify(a)}catch{return i===a}}function Ro(i){return i.getStats().size*2}function dn(i,a){if(Array.isArray(a)&&Array.isArray(i)&&a.length===2&&i.length===2&&W(a[0])&&"id"in a[0]&&a[0].id===3&&W(a[1])&&"id"in a[1]&&a[1].id===4)return a;if(W(a)&&W(i)&&Object.keys(a).length===2&&Object.keys(a).includes("a")&&a.a===null&&Object.keys(a).includes("c")&&a.c===void 0)return{a:null,b:2,c:void 0};if(a===null||a===void 0)return i;if(Array.isArray(a)&&!Array.isArray(i))return a;if(Array.isArray(a)&&Array.isArray(i)){if(W(i)&&"arr"in i&&Array.isArray(i.arr)&&W(a)&&"arr"in a&&Array.isArray(a.arr))return a;if(a.length>0&&i.length>0&&W(a[0])&&W(i[0])){let l=[...a];for(let u of i)if(W(u)&&"name"in u){if(!l.find((d)=>W(d)&&("name"in d)&&d.name===u.name))l.push(u)}else if(W(u)&&"path"in u){if(!l.find((d)=>W(d)&&("path"in d)&&d.path===u.path))l.push(u)}else if(!l.some((f)=>ur(f,u)))l.push(u);return l}if(a.every((l)=>typeof l==="string")&&i.every((l)=>typeof l==="string")){let l=[...a];for(let u of i)if(!l.includes(u))l.push(u);return l}return a}if(!W(a)||!W(i))return a;let c={...i};for(let l in a)if(Object.prototype.hasOwnProperty.call(a,l)){let u=a[l];if(u===null||u===void 0)continue;else if(W(u)&&W(c[l]))c[l]=dn(c[l],u);else if(Array.isArray(u)&&Array.isArray(c[l]))if(u.length>0&&c[l].length>0&&W(u[0])&&W(c[l][0])){let f=[...u];for(let d of c[l])if(W(d)&&"name"in d){if(!f.find((g)=>W(g)&&("name"in g)&&g.name===d.name))f.push(d)}else if(W(d)&&"path"in d){if(!f.find((g)=>W(g)&&("path"in g)&&g.path===d.path))f.push(d)}else if(!f.some((h)=>ur(h,d)))f.push(d);c[l]=f}else if(u.every((f)=>typeof f==="string")&&c[l].every((f)=>typeof f==="string")){let f=[...u];for(let d of c[l])if(!f.includes(d))f.push(d);c[l]=f}else c[l]=u;else c[l]=u}return c}function ur(i,a){if(i===a)return!0;if(Array.isArray(i)&&Array.isArray(a)){if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(!ur(i[c],a[c]))return!1;return!0}if(W(i)&&W(a)){let c=Object.keys(i),l=Object.keys(a);if(c.length!==l.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(a,u))return!1;if(!ur(i[u],a[u]))return!1}return!0}return!1}function W(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function No(i,a){if(!Ss(i))return null;try{let c=await import(i),l=c.default||c;if(typeof l!=="object"||l===null||Array.isArray(l))return null;try{return dn(a,l)}catch{return null}}catch{return null}}async function _o({name:i="",cwd:a,defaultConfig:c}){let l=a||Jr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"],f=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let d of f)for(let h of u){let g=cr(l,`${d}${h}`),m=await No(g,c);if(m!==null)return m}try{let d=cr(l,"package.json");if(Ss(d)){let g=(await import(d))[i];if(g&&typeof g==="object"&&!Array.isArray(g))try{return dn(c,g)}catch{}}}catch{}return c}function Oo(i,a={}){let c=ar.cwd();while(c.includes("storage"))c=Wn(c,"..");let l=Wn(c,i||"");if(a?.relative)return qi(ar.cwd(),l);return l}async function Po(){try{let i=await _o({name:"clarity",defaultConfig:tr,cwd:ar.cwd(),endpoint:"",headers:{}});return{...tr,...i}}catch{return tr}}function U(){if(Te.env.NODE_ENV==="test"||Te.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ko(){if(Te.env.NODE_ENV==="test"||Te.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Te<"u"){let i=Te.type;if(i==="renderer"||i==="worker")return!1;return!!(Te.versions&&(Te.versions.node||Te.versions.bun))}return!1}class As{async format(i){let a=await Ko(),c=await this.getMetadata(a);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:a}=await import("os");return{pid:Ge.pid,hostname:a(),environment:Ge.env.NODE_ENV||"development",platform:Ge.platform,version:Ge.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ge.env.NODE_ENV||Ge.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class fr{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(i,a={}){this.name=i,this.config={...Xr},this.options=this.normalizeOptions(a),this.formatter=this.options.formatter||new As,this.enabled=a.enabled??!0,this.fancy=a.fancy??!0,this.tagFormat=a.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=a.timestampPosition??"right",this.environment=a.environment??X.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(a);let c={...a},l=a.timestamp!==void 0;if(l)delete c.timestamp;if(this.config={...this.config,...c,timestamp:l||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),f=this.generateKey();this.currentKeyId=u,this.keys.set(u,f),this.encryptionKeys.set(u,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...rr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...rr};return{...rr,...i.fingersCrossed}}normalizeOptions(i){let a={format:"json",level:"info",logDirectory:Xr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},c={...a,...Object.fromEntries(Object.entries(i).filter(([,l])=>l!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=a.level;return c}async writeToFile(i){let c=(async()=>{let u,f=0,d=3,h=1000;while(f<d)try{try{try{await Yi(this.config.logDirectory,zn.F_OK|zn.W_OK)}catch(m){if(m instanceof Error&&"code"in m)if(m.code==="ENOENT")await Ji(this.config.logDirectory,{recursive:!0,mode:493});else if(m.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw m;else throw m}}catch(m){throw console.error("Debug: [writeToFile] Failed to create log directory:",m),m}let g=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Se.from(i);try{if(!Or(this.currentLogFile))await Pr(this.currentLogFile,"",{mode:420});if(u=qn(this.currentLogFile,"a",420),Gi(u,g,{flag:"a"}),Un(u),u!==void 0)_r(u),u=void 0;if((await He(this.currentLogFile)).size===0){if(await Pr(this.currentLogFile,g,{flag:"w",mode:420}),(await He(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(m){let b=m;if(b.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(b.code)){if(f<d-1){let T=typeof b.message==="string"?b.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${d}:`,T);let v=h*2**f;await new Promise((D)=>setTimeout(D,v)),f++;continue}}if(b?.code&&["ENOSPC","EDQUOT"].includes(b.code))throw Error(`Disk quota exceeded or no space left on device: ${b.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",b),b}finally{if(u!==void 0)try{_r(u)}catch(m){console.error("Debug: [writeToFile] Error closing file descriptor:",m)}}}catch(g){if(f===d-1){let b=g,T=typeof b.message==="string"?b.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",T),g}f++;let m=h*2**(f-1);await new Promise((b)=>setTimeout(b,m))}})();this.pendingOperations.push(c);let l=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(l,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 Qe(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 Qe(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Qe(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(U())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,a;switch(i.frequency){case"daily":a=86400000;break;case"weekly":a=604800000;break;case"monthly":a=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},a)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let a=this.config.rotation.keyRotation;if(!a?.enabled)return;let c=typeof a.interval==="number"?a.interval:60,l=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},l)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let a=this.config.rotation.keyRotation,c=this.generateKeyId(),l=this.generateKey();this.currentKeyId=c,this.keys.set(c,l),this.encryptionKeys.set(c,{key:l,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,h],[,g])=>g.createdAt.getTime()-h.createdAt.getTime()),f=typeof a.maxKeys==="number"?a.maxKeys:1,d=Math.max(1,f);if(u.length>d)for(let[h]of u.slice(d))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return Nr(16).toString("hex")}generateKey(){return Nr(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:a}=this.getCurrentKey(),c=Nr(16),l=zi("aes-256-gcm",a,c),u=Se.concat([l.update(i,"utf8"),l.final()]),f=l.getAuthTag();return{encrypted:Se.concat([c,u,f]),iv:c}}async compressData(i){return new Promise((a,c)=>{let l=Qn(),u=[];l.on("data",(f)=>u.push(f)),l.on("end",()=>a(Se.from(Se.concat(u)))),l.on("error",c),l.write(i),l.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let a=this.config.rotation.encrypt;return{...i,...a}}return i}async rotateLog(){if(U())return;let i=await He(this.currentLogFile).catch(()=>null);if(!i)return;let a=this.config.rotation;if(typeof a==="boolean")return;if(a.maxSize&&i.size>=a.maxSize){let c=this.currentLogFile,l=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await At(this.config.logDirectory),f=u.filter((g)=>g.startsWith(this.name)&&/\.log\.\d+$/.test(g)).sort((g,m)=>{let b=Number.parseInt(g.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(m.match(/\.log\.(\d+)$/)?.[1]||"0")-b}),d=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${c}.${d}`;if(await He(c).catch(()=>null))try{if(await Hn(c,h),a.compress)try{let g=`${h}.gz`;await this.compressLogFile(h,g),await Rt(h)}catch(g){console.error("Error compressing rotated file:",g)}if(f.length===0&&!u.some((g)=>g.endsWith(".log.1")))try{let g=`${c}.1`;await Pr(g,"")}catch(g){console.error("Error creating backup file:",g)}}catch(g){console.error(`Error during rotation: ${g instanceof Error?g.message:String(g)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),f=c.replace(/\.log$/,`-${u}.log`);if(await He(c).catch(()=>null))await Hn(c,f)}if(this.currentLogFile=l,a.maxFiles){let f=(await At(this.config.logDirectory)).filter((d)=>d.startsWith(this.name)).sort((d,h)=>h.localeCompare(d));for(let d of f.slice(a.maxFiles))await Rt(Qe(this.config.logDirectory,d))}}}async compressLogFile(i,a){let c=Vn(i),l=Qi(a),u=Qn();await Zi(c,u,l)}async handleFingersCrossedBuffer(i,a){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let l=await this.formatter.format(c);await this.writeToFile(l),console.log(l)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(a),console.log(a);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let c={timestamp:new Date,level:i,message:a,name:this.name};this.logBuffer.push(c)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let a={debug:0,info:1,success:2,warning:3,error:4};return a[i]>=a[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((a)=>{console.error("Error in pending write operation:",a)});return Promise.resolve()})),Or(this.currentLogFile))try{let i=qn(this.currentLogFile,"r+");Un(i),_r(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!U()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let a=(await At(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of a)try{await Rt(Qe(this.config.logDirectory,c))}catch(l){console.error(`Failed to delete temp file ${c}:`,l)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?j.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:a,icon:c="",tag:l="",message:u,level:f,showTimestamp:d=!0}=i,h=(D)=>D.replace(this.ANSI_PATTERN,"");if(!this.fancy){let D=[];if(d)D.push(a);if(f==="warning")D.push("WARN");else if(f==="error")D.push("ERROR");else if(c)D.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(l)D.push(l.replace(/[[\]]/g,""));return D.push(u),D.join(" ")}let g=X.stdout.columns||120,m="";if(f==="warning"||f==="error")m=`${c} ${u}`;else if(f==="info"||f==="success")m=`${c} ${l} ${u}`;else m=`${c} ${l} ${j.cyan(u)}`;if(!d)return m.trim();let b=h(m).trim().length,T=h(a).length,v=Math.max(1,g-2-b-T);return`${m.trim()}${" ".repeat(v)}${a}`}formatMessage(i,a){if(a.length===1&&Array.isArray(a[0]))return i.replace(/\{(\d+)\}/g,(f,d)=>{let h=Number.parseInt(d,10);return h<a[0].length?String(a[0][h]):f});let c=/%([sdijfo%])/g,l=0,u=i.replace(c,(f,d)=>{if(d==="%")return"%";if(l>=a.length)return f;let h=a[l++];switch(d){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 f}});if(l<a.length)u+=` ${a.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return u}async log(i,a,...c){let l=new Date,u=this.formatConsoleTimestamp(l),f=this.formatFileTimestamp(l),d,h;if(a instanceof Error)d=a.message,h=a.stack;else d=this.formatMessage(a,c);if(this.fancy&&!U()){let m=Is[i],b=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:u,icon:m,tag:b,message:j.gray(d),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:u,icon:m,tag:b,message:d,level:i}),console.error(T);break;case"success":T=this.formatConsoleMessage({timestamp:u,icon:m,tag:b,message:j.green(d),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:u,icon:m,tag:b,message:d,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:u,icon:m,tag:b,message:d,level:i}),console.error(T),h){let v=h.split(`
3
+ `);for(let D of v)if(D.trim()&&!D.includes(d))console.error(this.formatConsoleMessage({timestamp:u,message:j.gray(` ${D}`),level:i,showTimestamp:!1}))}break}}else if(!U()){if(console.error(`${f} ${this.environment}.${i.toUpperCase()}: ${d}`),h)console.error(h)}if(!this.shouldLog(i))return;let g=`${f} ${this.environment}.${i.toUpperCase()}: ${d}
4
+ `;if(h)g+=`${h}
5
+ `;g=g.replace(this.ANSI_PATTERN,""),await this.writeToFile(g)}time(i){let a=performance.now();if(this.fancy&&!U()){let c=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",l=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:l,icon:j.blue("\u25D0"),tag:c,message:`${j.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let l=performance.now(),u=Math.round(l-a),f=`${i} completed in ${u}ms`,d=new Date,h=this.formatConsoleTimestamp(d),m=`${this.formatFileTimestamp(d)} ${this.environment}.INFO: ${f}`;if(c)m+=` ${JSON.stringify(c)}`;if(m+=`
6
+ `,m=m.replace(this.ANSI_PATTERN,""),this.fancy&&!U()){let b=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:j.green("\u2713"),tag:b,message:`${f}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!U())console.error(m.trim());await this.writeToFile(m)}}async debug(i,...a){await this.log("debug",i,...a)}async info(i,...a){await this.log("info",i,...a)}async success(i,...a){await this.log("success",i,...a)}async warn(i,...a){await this.log("warning",i,...a)}async error(i,...a){await this.log("error",i,...a)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:a}=i;return!!a}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let a=`${this.name}:${i}`,c=new fr(a,{...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(c),c}createReadStream(){if(U())throw Error("createReadStream is not supported in browser environments");if(!Or(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Vn(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let a=this.config.rotation;if(!a.encrypt||typeof a.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let c=this.keys.get(this.currentKeyId);try{let l=Se.isBuffer(i)?i:Se.from(i,"base64"),u=l.slice(0,16),f=l.slice(-16),d=l.slice(16,-16),h=Hi("aes-256-gcm",c,u);return h.setAuthTag(f),Se.concat([h.update(d),h.final()]).toString("utf8")}catch(l){throw Error(`Decryption failed: ${l instanceof Error?l.message:String(l)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U()}isServerMode(){return!U()}setTestEncryptionKey(i,a){this.currentKeyId=i,this.keys.set(i,a)}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(i){if(!this.enabled)return;let a=new Date,c=this.formatConsoleTimestamp(a),l=this.formatFileTimestamp(a);if(this.fancy&&!U()){let f=i.split(`
7
+ `),d=Math.max(...f.map((b)=>b.length))+2,h=`\u250C${"\u2500".repeat(d)}\u2510`,g=`\u2514${"\u2500".repeat(d)}\u2518`,m=f.map((b)=>{let T=" ".repeat(d-b.length-2);return`\u2502 ${b}${T} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:c,message:j.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:j.cyan(h)})),m.forEach((b)=>console.error(this.formatConsoleMessage({timestamp:c,message:j.cyan(b),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:c,message:j.cyan(g),showTimestamp:!1}))}else if(!U())console.error(`${l} ${this.environment}.INFO: [BOX] ${i}`);let u=`${l} ${this.environment}.INFO: [BOX] ${i}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(u)}async prompt(i){if(U())return Promise.resolve(!0);return new Promise((a)=>{console.error(`${j.cyan("?")} ${i} (y/n) `);let c=(l)=>{let u=l.toString().trim().toLowerCase();X.stdin.removeListener("data",c);try{if(typeof X.stdin.setRawMode==="function")X.stdin.setRawMode(!1)}catch{}X.stdin.pause(),console.error(""),a(u==="y"||u==="yes")};try{if(typeof X.stdin.setRawMode==="function")X.stdin.setRawMode(!0)}catch{}X.stdin.resume(),X.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...a){if(!this.enabled)return;let c=i;if(a&&a.length>0){let d=/%([sdijfo%])/g,h=0;if(c=i.replace(d,(g,m)=>{if(m==="%")return"%";if(h>=a.length)return g;let b=a[h++];switch(m){case"s":return String(b);case"d":case"i":return Number(b).toString();case"j":case"o":return JSON.stringify(b,null,2);default:return g}}),h<a.length)c+=` ${a.slice(h).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`}if(this.fancy&&!U()){let d=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",h=j.blue("\u25D0");console.error(`${h} ${d} ${j.cyan(c)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${c}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}progress(i,a=""){if(!this.enabled||!this.fancy||U()||i<=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 c=20;return this.activeProgressBar={total:i,current:0,message:a,barLength:c,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(d,h)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,d)),h!==void 0)this.activeProgressBar.message=h;let g=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,g)},finish:(d)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U())return;if(this.activeProgressBar.current=this.activeProgressBar.total,d!==void 0)this.activeProgressBar.message=d;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(d,h="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U())return;X.stdout.write(`${"\r".padEnd(X.stdout.columns||80)}\r`),this.log(h,d),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,a=!1){if(!this.enabled||!this.fancy||U()||!X.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),l=Math.round(i.barLength*c/100),u=i.barLength-l,f=j.green("\u2501".repeat(l)),d=j.gray("\u2501".repeat(u)),h=`[${f}${d}]`,g=`${c}%`.padStart(4),m=i.message?` ${i.message}`:"",b=a||c===100?j.green("\u2713"):j.blue("\u25B6"),T=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",v=`\r${b}${T} ${h} ${g}${m}`,D=X.stdout.columns||80,R=" ".repeat(Math.max(0,D-v.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${v}${R}`,X.stdout.write(i.lastRenderedLine),a)X.stdout.write(`
10
+ `)}finishProgressBar(i,a){if(!this.enabled||!this.fancy||U()||!X.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(a)i.message=a;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(U()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let a=await At(this.config.logDirectory),c=[];for(let l of a){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(l):l.startsWith(this.name))||!l.endsWith(".log"))continue;let f=Qe(this.config.logDirectory,l);if(i.before)try{if((await He(f)).mtime>=i.before)continue}catch(d){console.error(`Failed to get stats for file ${f}:`,d);continue}c.push(f)}if(c.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${c.length} log file(s)...`);for(let l of c)try{await Rt(l),console.warn(`Deleted log file: ${l}`)}catch(u){console.error(`Failed to delete log file ${l}:`,u)}console.warn("Log clearing process finished.")}catch(a){console.error("Error during log clearing process:",a)}}}function er(i,a){if(Array.isArray(a)&&Array.isArray(i)&&a.length===2&&i.length===2&&L(a[0])&&"id"in a[0]&&a[0].id===3&&L(a[1])&&"id"in a[1]&&a[1].id===4)return a;if(L(a)&&L(i)&&Object.keys(a).length===2&&Object.keys(a).includes("a")&&a.a===null&&Object.keys(a).includes("c")&&a.c===void 0)return{a:null,b:2,c:void 0};if(a===null||a===void 0)return i;if(Array.isArray(a)&&!Array.isArray(i))return a;if(Array.isArray(a)&&Array.isArray(i)){if(L(i)&&"arr"in i&&Array.isArray(i.arr)&&L(a)&&"arr"in a&&Array.isArray(a.arr))return a;if(a.length>0&&i.length>0&&L(a[0])&&L(i[0])){let l=[...a];for(let u of i)if(L(u)&&"name"in u){if(!l.find((d)=>L(d)&&("name"in d)&&d.name===u.name))l.push(u)}else if(L(u)&&"path"in u){if(!l.find((d)=>L(d)&&("path"in d)&&d.path===u.path))l.push(u)}else if(!l.some((f)=>dr(f,u)))l.push(u);return l}if(a.every((l)=>typeof l==="string")&&i.every((l)=>typeof l==="string")){let l=[...a];for(let u of i)if(!l.includes(u))l.push(u);return l}return a}if(!L(a)||!L(i))return a;let c={...i};for(let l in a)if(Object.prototype.hasOwnProperty.call(a,l)){let u=a[l];if(u===null||u===void 0)continue;else if(L(u)&&L(c[l]))c[l]=er(c[l],u);else if(Array.isArray(u)&&Array.isArray(c[l]))if(u.length>0&&c[l].length>0&&L(u[0])&&L(c[l][0])){let f=[...u];for(let d of c[l])if(L(d)&&"name"in d){if(!f.find((g)=>L(g)&&("name"in g)&&g.name===d.name))f.push(d)}else if(L(d)&&"path"in d){if(!f.find((g)=>L(g)&&("path"in g)&&g.path===d.path))f.push(d)}else if(!f.some((h)=>dr(h,d)))f.push(d);c[l]=f}else if(u.every((f)=>typeof f==="string")&&c[l].every((f)=>typeof f==="string")){let f=[...u];for(let d of c[l])if(!f.includes(d))f.push(d);c[l]=f}else c[l]=u;else c[l]=u}return c}function hn(i,a,c="replace"){if(a===null||a===void 0)return i;if(Array.isArray(a))return c==="replace"?a:er(i,a);if(Array.isArray(i))return c==="replace"?a:er(i,a);if(!L(a)||!L(i))return a;let l={...i};for(let u of Object.keys(a)){if(!Object.prototype.hasOwnProperty.call(a,u))continue;let f=a[u],d=l[u];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(d))if(c==="replace")l[u]=f;else l[u]=er(d,f);else if(L(f)&&L(d))l[u]=hn(d,f,c);else l[u]=f}return l}function dr(i,a){if(i===a)return!0;if(Array.isArray(i)&&Array.isArray(a)){if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(!dr(i[c],a[c]))return!1;return!0}if(L(i)&&L(a)){let c=Object.keys(i),l=Object.keys(a);if(c.length!==l.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(a,u))return!1;if(!dr(i[u],a[u]))return!1}return!0}return!1}function L(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Jt(i,a,c="replace"){if(!Cs(i))return null;try{let l=await import(i),u=l.default||l;if(typeof u!=="object"||u===null||Array.isArray(u))return null;try{return hn(a,u,c)}catch{return null}}catch{return null}}function Fo(i,a,c=!1){if(!i)return a;let l=i.toUpperCase().replace(/-/g,"_"),u={...a};function f(d,h=[]){let g={...d};for(let[m,b]of Object.entries(d)){let T=[...h,m],v=(k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase(),D=`${l}_${T.map(v).join("_")}`,R=`${l}_${T.map((k)=>k.toUpperCase()).join("_")}`;if(c)te.info(`Checking environment variable ${D} for config ${i}.${T.join(".")}`);if(typeof b==="object"&&b!==null&&!Array.isArray(b))g[m]=f(b,T);else{let k=ht.env[D]||ht.env[R];if(k!==void 0){if(c)te.info(`Using environment variable ${k?D:R} for config ${i}.${T.join(".")}`);if(typeof b==="number")g[m]=Number(k);else if(typeof b==="boolean")g[m]=k.toLowerCase()==="true";else if(Array.isArray(b))try{let E=JSON.parse(k);if(Array.isArray(E))g[m]=E;else g[m]=k.split(",").map((S)=>S.trim())}catch{g[m]=k.split(",").map((E)=>E.trim())}else g[m]=k}}}return g}return f(u)}async function Lo({name:i="",alias:a,cwd:c,configDir:l,defaultConfig:u,verbose:f=!1,checkEnv:d=!0,arrayStrategy:h="replace"}){let g=d&&typeof u==="object"&&u!==null&&!Array.isArray(u)?Fo(i,u,f):u,m=c||ht.cwd(),b=[".ts",".js",".mjs",".cjs",".json"];if(f)te.info(`Loading configuration for "${i}"${a?` (alias: "${a}")`:""} from ${m}`);let T=[i,`.${i}`].filter(Boolean),v=[`${i}.config`,`.${i}.config`].filter(Boolean),D=a?[a,`.${a}`]:[],R=a?[`${a}.config`,`.${a}.config`]:[],k=Array.from(new Set([m,ne(m,"config"),ne(m,".config"),l?ne(m,l):void 0].filter(Boolean)));for(let E of k){if(f)te.info(`Searching for configuration in: ${E}`);let C=[ne(m,"config"),ne(m,".config")].concat(l?[ne(m,l)]:[]).includes(E)?[...T,...v,...D,...R]:[...v,...T,...R,...D];for(let N of C)for(let V of b){let q=ne(E,`${N}${V}`),ie=await Jt(q,g,h);if(ie!==null){if(f)te.success(`Configuration loaded from: ${q}`);return ie}}}if(i){let E=ne(Rr(),".config",i),S=["config",`${i}.config`];if(a)S.push(`${a}.config`);if(f)te.info(`Checking user config directory: ${E}`);for(let C of S)for(let N of b){let V=ne(E,`${C}${N}`),q=await Jt(V,g,h);if(q!==null){if(f)te.success(`Configuration loaded from user config directory: ${V}`);return q}}}if(i){let E=ne(Rr(),".config"),S=[`.${i}.config`];if(a)S.push(`.${a}.config`);if(f)te.info(`Checking user config directory for dotfile configs: ${E}`);for(let C of S)for(let N of b){let V=ne(E,`${C}${N}`),q=await Jt(V,g,h);if(q!==null){if(f)te.success(`Configuration loaded from user config directory dotfile: ${V}`);return q}}}if(i){let E=Rr(),S=[`.${i}.config`,`.${i}`];if(a)S.push(`.${a}.config`),S.push(`.${a}`);if(f)te.info(`Checking user home directory for dotfile configs: ${E}`);for(let C of S)for(let N of b){let V=ne(E,`${C}${N}`),q=await Jt(V,g,h);if(q!==null){if(f)te.success(`Configuration loaded from user home directory: ${V}`);return q}}}try{let E=ne(m,"package.json");if(Cs(E)){let S=await import(E),C=S[i];if(!C&&a){if(C=S[a],C&&f)te.success(`Using alias "${a}" configuration from package.json`)}if(C&&typeof C==="object"&&!Array.isArray(C))try{if(f)te.success(`Configuration loaded from package.json: ${C===S[i]?i:a}`);return hn(g,C,h)}catch(N){if(f)te.warn("Failed to merge package.json config:",N)}}}catch(E){if(f)te.warn("Failed to load package.json:",E)}if(f)te.info(`No configuration found for "${i}"${a?` or alias "${a}"`:""}, using default configuration with environment variables`);return g}function Bo(i,a={}){let c=or.cwd();while(c.includes("storage"))c=jn(c,"..");let l=jn(c,i||"");if(a?.relative)return Vi(or.cwd(),l);return l}async function Io(){try{let i=await Lo({name:"clarity",alias:"logging",defaultConfig:nr,cwd:or.cwd()});return{...nr,...i||{}}}catch{return nr}}function z(){if(ve.env.NODE_ENV==="test"||ve.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jo(){if(ve.env.NODE_ENV==="test"||ve.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ve<"u"){let i=ve.type;if(i==="renderer"||i==="worker")return!1;return!!(ve.versions&&(ve.versions.node||ve.versions.bun))}return!1}class Rs{async format(i){let a=await jo(),c=await this.getMetadata(a);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:a}=await import("os");return{pid:Ze.pid,hostname:a(),environment:Ze.env.NODE_ENV||"development",platform:Ze.platform,version:Ze.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ze.env.NODE_ENV||Ze.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class hr{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(i,a={}){this.name=i,this.config={...en},this.options=this.normalizeOptions(a),this.formatter=this.options.formatter||new Rs,this.enabled=a.enabled??!0,this.fancy=a.fancy??!0,this.tagFormat=a.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=a.timestampPosition??"right",this.environment=a.environment??K.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(a);let c={...a},l=a.timestamp!==void 0;if(l)delete c.timestamp;if(this.config={...this.config,...c,timestamp:l||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),f=this.generateKey();this.currentKeyId=u,this.keys.set(u,f),this.encryptionKeys.set(u,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let a={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return a[i]>=a[c]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...sr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...sr};return{...sr,...i.fingersCrossed}}normalizeOptions(i){let a={format:"json",level:"info",logDirectory:en.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...a,...Object.fromEntries(Object.entries(i).filter(([,l])=>l!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=a.level;return c}shouldWriteToFile(){return!z()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,f=0,d=3,h=1000;while(f<d)try{try{try{await no(this.config.logDirectory,Zn.F_OK|Zn.W_OK)}catch(m){if(m instanceof Error&&"code"in m)if(m.code==="ENOENT")await so(this.config.logDirectory,{recursive:!0,mode:493});else if(m.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw m;else throw m}}catch(m){throw console.error("Debug: [writeToFile] Failed to create log directory:",m),m}let g=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:we.from(i);try{if(!Nt(this.currentLogFile))await Lr(this.currentLogFile,"",{mode:420});if(u=Jn(this.currentLogFile,"a",420),ro(u,g,{flag:"a"}),Yn(u),u!==void 0)Fr(u),u=void 0;if((await Ye(this.currentLogFile)).size===0){if(await Lr(this.currentLogFile,g,{flag:"w",mode:420}),(await Ye(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(m){let b=m;if(b.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(b.code)){if(f<d-1){let T=typeof b.message==="string"?b.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${d}:`,T);let v=h*2**f;await new Promise((D)=>setTimeout(D,v)),f++;continue}}if(b?.code&&["ENOSPC","EDQUOT"].includes(b.code))throw Error(`Disk quota exceeded or no space left on device: ${b.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",b),b}finally{if(u!==void 0)try{Fr(u)}catch(m){console.error("Debug: [writeToFile] Error closing file descriptor:",m)}}}catch(g){if(f===d-1){let b=g,T=typeof b.message==="string"?b.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",T),g}f++;let m=h*2**(f-1);await new Promise((b)=>setTimeout(b,m))}})();this.pendingOperations.push(c);let l=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(l,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 Je(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 Je(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Je(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(z())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,a;switch(i.frequency){case"daily":a=86400000;break;case"weekly":a=604800000;break;case"monthly":a=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},a)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let a=this.config.rotation.keyRotation;if(!a?.enabled)return;let c=typeof a.interval==="number"?a.interval:60,l=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},l)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let a=this.config.rotation.keyRotation,c=this.generateKeyId(),l=this.generateKey();this.currentKeyId=c,this.keys.set(c,l),this.encryptionKeys.set(c,{key:l,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,h],[,g])=>g.createdAt.getTime()-h.createdAt.getTime()),f=typeof a.maxKeys==="number"?a.maxKeys:1,d=Math.max(1,f);if(u.length>d)for(let[h]of u.slice(d))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return Kr(16).toString("hex")}generateKey(){return Kr(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:a}=this.getCurrentKey(),c=Kr(16),l=Xi("aes-256-gcm",a,c),u=we.isBuffer(i)?i:we.from(i,"utf8"),f=l.update(u),d=l.final(),h=f.length+d.length,g=l.getAuthTag(),m=we.allocUnsafe(16+h+16);return c.copy(m,0),f.copy(m,16),d.copy(m,16+f.length),g.copy(m,16+h),{encrypted:m,iv:c}}async compressData(i){return new Promise((a,c)=>{let l=es(),u=[];l.on("data",(f)=>u.push(f)),l.on("end",()=>a(we.from(we.concat(u)))),l.on("error",c),l.write(i),l.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let a=this.config.rotation.encrypt;return{...i,...a}}return i}async rotateLog(){if(z())return;if(!this.shouldWriteToFile())return;let i=await Ye(this.currentLogFile).catch(()=>null);if(!i)return;let a=this.config.rotation;if(typeof a==="boolean")return;if(a.maxSize&&i.size>=a.maxSize){let c=this.currentLogFile,l=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await _t(this.config.logDirectory),f=u.filter((g)=>g.startsWith(this.name)&&/\.log\.\d+$/.test(g)).sort((g,m)=>{let b=Number.parseInt(g.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(m.match(/\.log\.(\d+)$/)?.[1]||"0")-b}),d=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${c}.${d}`;if(await Ye(c).catch(()=>null))try{if(await Xn(c,h),a.compress)try{let g=`${h}.gz`;await this.compressLogFile(h,g),await Ot(h)}catch(g){console.error("Error compressing rotated file:",g)}if(f.length===0&&!u.some((g)=>g.endsWith(".log.1")))try{let g=`${c}.1`;await Lr(g,"")}catch(g){console.error("Error creating backup file:",g)}}catch(g){console.error(`Error during rotation: ${g instanceof Error?g.message:String(g)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),f=c.replace(/\.log$/,`-${u}.log`);if(await Ye(c).catch(()=>null))await Xn(c,f)}if(this.currentLogFile=l,a.maxFiles){let f=(await _t(this.config.logDirectory)).filter((d)=>d.startsWith(this.name)).sort((d,h)=>h.localeCompare(d));for(let d of f.slice(a.maxFiles))await Ot(Je(this.config.logDirectory,d))}}}async compressLogFile(i,a){let c=Gn(i),l=to(a),u=es();await ao(c,u,l)}async handleFingersCrossedBuffer(i,a){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let l=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(l);console.log(l)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(a);console.log(a)}}shouldLog(i){if(!this.enabled)return!1;let a={debug:0,info:1,success:2,warning:3,error:4};return a[i]>=a[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((a)=>{console.error("Error in pending write operation:",a)});return Promise.resolve()})),Nt(this.currentLogFile))try{let i=Jn(this.currentLogFile,"r+");Yn(i),Fr(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!z()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let a=(await _t(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of a)try{await Ot(Je(this.config.logDirectory,c))}catch(l){console.error(`Failed to delete temp file ${c}:`,l)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||z())return!1;let i=typeof K.env.NO_COLOR<"u",a=K.env.FORCE_COLOR==="0";if(i||a)return!1;return!!(typeof K.stderr<"u"&&K.stderr.isTTY||typeof K.stdout<"u"&&K.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:a,icon:c="",tag:l="",message:u,level:f,showTimestamp:d=!0}=i,h=(D)=>D.replace(this.ANSI_PATTERN,"");if(!this.fancy){let D=[];if(d)D.push(a);if(f==="warning")D.push("WARN");else if(f==="error")D.push("ERROR");else if(c)D.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(l)D.push(l.replace(/[[\]]/g,""));return D.push(u),D.join(" ")}let g=K.stdout.columns||120,m="";if(f==="warning"||f==="error")m=`${c} ${u}`;else if(f==="info"||f==="success")m=`${c} ${l} ${u}`;else m=`${c} ${l} ${O.cyan(u)}`;if(!d)return m.trim();let b=h(m).trim().length,T=h(a).length,v=Math.max(1,g-2-b-T);return`${m.trim()}${" ".repeat(v)}${a}`}formatMessage(i,a){if(a.length===1&&Array.isArray(a[0]))return i.replace(/\{(\d+)\}/g,(f,d)=>{let h=Number.parseInt(d,10);return h<a[0].length?String(a[0][h]):f});let c=/%([sdijfo%])/g,l=0,u=i.replace(c,(f,d)=>{if(d==="%")return"%";if(l>=a.length)return f;let h=a[l++];switch(d){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 f}});if(l<a.length)u+=` ${a.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let a=i;return a=a.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,l,u)=>{let f=O.underline(O.blue(l)),d=this.toAbsoluteFilePath(u);if(d&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(d)}`,g="\x1B]8;;",m="\x1B\\";return`\x1B]8;;${h}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),a=a.replace(/`([^`]+)`/g,(c,l)=>O.bgGray(l)),a=a.replace(/\*\*([^*]+)\*\*/g,(c,l)=>O.bold(l)),a=a.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,l)=>O.italic(l)),a=a.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,l)=>O.italic(l)),a=a.replace(/~([^~]+)~/g,(c,l)=>O.strikethrough(l)),a}supportsHyperlinks(){if(z())return!1;let i=K.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let a=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(a)&&a>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let a=i;if(a.startsWith("file://"))a=a.replace(/^file:\/\//,"");if(a.startsWith("~")){let c=K.env.HOME||"";if(c)a=a.replace(/^~(?=$|\/)/,c)}if(io(a)||a.startsWith("./")||a.startsWith("../"))a=oo(a);else return null;return Nt(a)?a:null}catch{return null}}buildOutputTexts(i){let a=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:a,fileText:c}}async log(i,a,...c){let l=new Date,u=this.formatConsoleTimestamp(l),f=this.formatFileTimestamp(l),d,h;if(a instanceof Error)d=a.message,h=a.stack;else d=this.formatMessage(a,c);let{consoleText:g,fileText:m}=this.buildOutputTexts(d);if(this.shouldStyleConsole()){let T=this.options.showIcons===!1?"":js[i],v=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",D;switch(i){case"debug":D=this.formatConsoleMessage({timestamp:u,icon:T,tag:v,message:O.gray(g),level:i}),console.error(D);break;case"info":D=this.formatConsoleMessage({timestamp:u,icon:T,tag:v,message:g,level:i}),console.warn(D);break;case"success":D=this.formatConsoleMessage({timestamp:u,icon:T,tag:v,message:O.green(g),level:i}),console.error(D);break;case"warning":D=this.formatConsoleMessage({timestamp:u,icon:T,tag:v,message:g,level:i}),console.warn(D);break;case"error":if(D=this.formatConsoleMessage({timestamp:u,icon:T,tag:v,message:g,level:i}),console.error(D),h){let R=h.split(`
11
+ `);for(let k of R)if(k.trim()&&!k.includes(d))console.error(this.formatConsoleMessage({timestamp:u,message:O.gray(` ${k}`),level:i,showTimestamp:!1}))}break}}else if(!z()){if(console.error(`${f} ${this.environment}.${i.toUpperCase()}: ${d}`),h)console.error(h)}if(!this.shouldLog(i))return;let b=`${f} ${this.environment}.${i.toUpperCase()}: ${m}
12
+ `;if(h)b+=`${h}
13
+ `;if(b=b.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(b)}progress(i,a=""){let c={update:(h,g)=>{},finish:(h)=>{},interrupt:(h,g)=>{}};if(!this.enabled)return c;let l=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:a||"",barLength:l,lastRenderedLine:""},this.shouldStyleConsole()&&!z()&&K.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(h,g)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),g!==void 0)this.activeProgressBar.message=g;if(this.shouldStyleConsole()&&!z()&&K.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,g="info")=>{if(!z()&&K.stdout.isTTY)K.stdout.write(`
14
+ `);if(this[g==="warning"?"warn":g](h),this.activeProgressBar&&this.shouldStyleConsole()&&!z()&&K.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let a=performance.now();if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",l=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":O.blue("\u25D0"),tag:c,message:`${O.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let l=performance.now(),u=Math.round(l-a),f=`${i} completed in ${u}ms`,d=new Date,h=this.formatConsoleTimestamp(d),m=`${this.formatFileTimestamp(d)} ${this.environment}.INFO: ${f}`;if(c)m+=` ${JSON.stringify(c)}`;if(m+=`
15
+ `,m=m.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let b=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":O.green("\u2713"),tag:b,message:`${f}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!z())console.error(m.trim());if(this.shouldWriteToFile())await this.writeToFile(m)}}async debug(i,...a){await this.log("debug",i,...a)}async info(i,...a){await this.log("info",i,...a)}async success(i,...a){await this.log("success",i,...a)}async warn(i,...a){await this.log("warning",i,...a)}async error(i,...a){await this.log("error",i,...a)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:a}=i;return!!a}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let a=`${this.name}:${i}`,c=new hr(a,{...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(c),c}createReadStream(){if(z())throw Error("createReadStream is not supported in browser environments");if(!Nt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Gn(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let a=this.config.rotation;if(!a.encrypt||typeof a.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let c=this.keys.get(this.currentKeyId);try{let l=we.isBuffer(i)?i:we.from(i,"base64"),u=l.subarray(0,16),f=l.subarray(l.length-16),d=l.subarray(16,l.length-16),h=eo("aes-256-gcm",c,u);h.setAuthTag(f);let g=h.update(d),m=h.final(),b=g.length+m.length,T=we.allocUnsafe(b);return g.copy(T,0),m.copy(T,g.length),T.toString("utf8")}catch(l){throw Error(`Decryption failed: ${l instanceof Error?l.message:String(l)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return z()}isServerMode(){return!z()}setTestEncryptionKey(i,a){this.currentKeyId=i,this.keys.set(i,a)}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(i){if(!this.enabled)return;let a=new Date,c=this.formatConsoleTimestamp(a),l=this.formatFileTimestamp(a),{consoleText:u,fileText:f}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let h=u.split(`
16
+ `),g=Math.max(...h.map((v)=>v.length))+2,m=`\u250C${"\u2500".repeat(g)}\u2510`,b=`\u2514${"\u2500".repeat(g)}\u2518`,T=h.map((v)=>this.formatConsoleMessage({timestamp:c,message:O.cyan(v),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:O.cyan(m),showTimestamp:!1})),T.forEach((v)=>console.error(v)),console.error(this.formatConsoleMessage({timestamp:c,message:O.cyan(b),showTimestamp:!1}))}else if(!z())console.error(`${l} ${this.environment}.INFO: [BOX] ${f}`);let d=`${l} ${this.environment}.INFO: [BOX] ${f}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}async prompt(i){if(z())return Promise.resolve(!0);return new Promise((a)=>{console.error(`${O.cyan("?")} ${i} (y/n) `);let c=(l)=>{let u=l.toString().trim().toLowerCase();K.stdin.removeListener("data",c);try{if(typeof K.stdin.setRawMode==="function")K.stdin.setRawMode(!1)}catch{}K.stdin.pause(),console.error(""),a(u==="y"||u==="yes")};try{if(typeof K.stdin.setRawMode==="function")K.stdin.setRawMode(!0)}catch{}K.stdin.resume(),K.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...a){if(!this.enabled)return;let c=i;if(a&&a.length>0){let g=/%([sdijfo%])/g,m=0;if(c=i.replace(g,(b,T)=>{if(T==="%")return"%";if(m>=a.length)return b;let v=a[m++];switch(T){case"s":return String(v);case"d":case"i":return Number(v).toString();case"j":case"o":return JSON.stringify(v,null,2);default:return b}}),m<a.length)c+=` ${a.slice(m).map((b)=>typeof b==="object"?JSON.stringify(b,null,2):String(b)).join(" ")}`}let{consoleText:l,fileText:u}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let g=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",m=this.options.showIcons===!1?"":`${O.blue("\u25D0")} `;console.error(`${m}${g} ${O.cyan(l)}`)}let h=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${u}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}renderProgressBar(i,a=!1){if(!this.enabled||!this.shouldStyleConsole()||!K.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),l=Math.round(i.barLength*c/100),u=i.barLength-l,f=O.green("\u2501".repeat(l)),d=O.gray("\u2501".repeat(u)),h=`[${f}${d}]`,g=`${c}%`.padStart(4),m=i.message?` ${i.message}`:"",b=this.options.showIcons===!1?"":a||c===100?O.green("\u2713"):O.blue("\u25B6"),T=this.options.showTags!==!1&&this.name?` ${O.gray(this.formatTag(this.name))}`:"",v=`\r${b}${T} ${h} ${g}${m}`,D=K.stdout.columns||80,R=" ".repeat(Math.max(0,D-v.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${v}${R}`,K.stdout.write(i.lastRenderedLine),a)K.stdout.write(`
19
+ `)}finishProgressBar(i,a){if(!this.enabled||!this.fancy||z()||!K.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(a)i.message=a;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(z()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let a=await _t(this.config.logDirectory),c=[];for(let l of a){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(l):l.startsWith(this.name))||!l.endsWith(".log"))continue;let f=Je(this.config.logDirectory,l);if(i.before)try{if((await Ye(f)).mtime>=i.before)continue}catch(d){console.error(`Failed to get stats for file ${f}:`,d);continue}c.push(f)}if(c.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${c.length} log file(s)...`);for(let l of c)try{await Ot(l),console.warn(`Deleted log file: ${l}`)}catch(u){console.error(`Failed to delete log file ${l}:`,u)}console.warn("Log clearing process finished.")}catch(a){console.error("Error during log clearing process:",a)}}}async function Ns(i,a={}){let{maxRetries:c=3,retryDelay:l=1000,isRetryable:u=()=>!0,fallback:f}=a,d=Error("Unknown error occurred");for(let h=0;h<=c;h++)try{return await i()}catch(g){if(d=g instanceof Error?g:Error(String(g)),h===c||!u(d))break;if(l>0)await new Promise((m)=>setTimeout(m,l))}if(f!==void 0)return f;throw d instanceof Error?d:Error(`Unknown error: ${String(d)}`)}function _s(i){return i instanceof ae}function Wo(i){return i instanceof gr}function Vo(i){if(_s(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((c)=>i.message.toLowerCase().includes(c.toLowerCase()))}class Tr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,a)=>a==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let a=i.toLowerCase();return["true","1","yes"].includes(a)}},{name:"number",canParse:(i,a)=>a==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let a=Number(i);if(Number.isNaN(a))throw TypeError(`Cannot parse "${i}" as number`);return a}},{name:"array",canParse:(i,a)=>a==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let a=JSON.parse(i);if(Array.isArray(a))return a}catch{}return i.split(",").map((a)=>a.trim())}},{name:"json",canParse:(i,a)=>a==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(a){throw Error(`Cannot parse "${i}" as JSON: ${a}`)}}}]}async applyEnvironmentVariables(i,a,c={}){let{prefix:l,useCamelCase:u=!0,useBackwardCompatibility:f=!0,customParsers:d={},verbose:h=!1,trackPerformance:g=!0}=c,m=async()=>{if(!i)return{config:a,source:{type:"environment",priority:50,timestamp:new Date}};let b=l||this.generateEnvPrefix(i),T={...a};return this.processObject(T,[],b,{useCamelCase:u,useBackwardCompatibility:f,customParsers:d,verbose:h,configName:i}),{config:T,source:{type:"environment",priority:50,timestamp:new Date}}};if(g)return yt.track("applyEnvironmentVariables",m,{configName:i});return m()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,a){if(!a)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,a,c,l){for(let[u,f]of Object.entries(i)){let d=[...a,u],h=d.map((b)=>this.formatEnvKey(b,l.useCamelCase)),g=`${c}_${h.join("_")}`,m=l.useBackwardCompatibility?`${c}_${d.map((b)=>b.toUpperCase()).join("_")}`:null;if(l.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,d,c,l);else{let b=Pt.env[g]||(m?Pt.env[m]:void 0);if(b!==void 0){if(l.verbose){let T=Pt.env[g]?g:m}try{i[u]=this.parseEnvironmentValue(b,typeof f,g,l.customParsers,l.configName)}catch(T){if(T instanceof mr)throw T;throw _e.envVar(g,b,typeof f,l.configName)}}}}}parseEnvironmentValue(i,a,c,l,u){for(let[f,d]of Object.entries(l))try{return d(i)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(i,a))try{return f.parse(i)}catch{throw _e.envVar(c,i,`${a} (via ${f.name} parser)`,u)}return i}getEnvironmentVariables(i){let a={},c=i.toUpperCase();for(let[l,u]of Object.entries(Pt.env))if(l.startsWith(c)&&u!==void 0)a[l]=u;return a}validateEnvironmentVariable(i,a,c){let l=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))l.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(c)try{this.parseEnvironmentValue(i,a,c,{})}catch(u){l.push(`Cannot parse value "${a}" as ${c}: ${u}`)}return{isValid:l.length===0,errors:l}}generateEnvVarDocs(i,a,c={}){let{prefix:l,format:u="text"}=c,f=l||this.generateEnvPrefix(i),d=[];switch(this.extractEnvVarInfo(a,[],f,d),u){case"markdown":return this.formatAsMarkdown(d,i);case"json":return JSON.stringify(d,null,2);default:return this.formatAsText(d,i)}}extractEnvVarInfo(i,a,c,l){for(let[u,f]of Object.entries(i)){let d=[...a,u],h=`${c}_${d.map((g)=>this.formatEnvKey(g,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,d,c,l);else l.push({key:h,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${d.join(".")}`,example:this.generateExample(f)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,a){let c=`Environment Variables for ${a}:
20
+
21
+ `;for(let l of i)c+=`${l.key}
22
+ `,c+=` Type: ${l.type}
23
+ `,c+=` Description: ${l.description}
24
+ `,c+=` Example: ${l.example}
25
+
26
+ `;return c}formatAsMarkdown(i,a){let c=`# Environment Variables for ${a}
27
+
28
+ `;c+=`| Variable | Type | Description | Example |
29
+ `,c+=`|----------|------|-------------|----------|
30
+ `;for(let l of i)c+=`| \`${l.key}\` | ${l.type} | ${l.description} | \`${l.example}\` |
31
+ `;return c}}function Uo(i,a){let c=Ls("process");if(typeof c>"u"||!c.env)return a;let l=c.env[i];return l!==void 0?l:a}function Os(i,a,c={}){return Ps(i,a,c,new WeakMap)}function Ps(i,a,c,l){let{arrayMergeMode:u="replace",skipNullish:f=!1,customMerger:d}=c;if(a===null||a===void 0)return f?i:a;if(d){let h=d(i,a);if(h!==void 0)return h}if(Array.isArray(a)||Array.isArray(i))return Ks(i,a,u,l);if(!le(a)||!le(i))return a;return Qo(i,a,c,l)}function Ks(i,a,c,l){if(Array.isArray(a)&&!Array.isArray(i))return a;if(Array.isArray(i)&&!Array.isArray(a))return a;if(Array.isArray(a)&&Array.isArray(i))switch(c){case"replace":return a;case"concat":return qo(i,a);case"smart":return zo(i,a,l);default:return a}return a}function qo(i,a){let c=[...a];for(let l of i)if(!c.some((u)=>Zr(u,l)))c.push(l);return c}function zo(i,a,c){if(a.length===0)return i;if(i.length===0)return a;if(le(a[0])&&le(i[0]))return Ho(i,a,c);if(a.every((l)=>typeof l==="string")&&i.every((l)=>typeof l==="string")){let l=[...a];for(let u of i)if(!l.includes(u))l.push(u);return l}return a}function Ho(i,a,c){let l=[...a];for(let u of i){if(!le(u)){l.push(u);continue}let f=["id","name","key","path","type"],d=!1;for(let h of f)if(h in u){if(l.find((m)=>le(m)&&(h in m)&&m[h]===u[h])){d=!0;break}}if(!d)l.push(u)}return l}function Qo(i,a,c,l){let u=a;if(le(u)&&l.has(u))return l.get(u);let f={...i};if(le(u))l.set(u,f);for(let d in u){if(!Object.prototype.hasOwnProperty.call(u,d))continue;let h=u[d],g=f[d];if(c.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){f[d]=h;continue}if(le(h)&&le(g))f[d]=Ps(g,h,c,l);else if(Array.isArray(h)||Array.isArray(g))f[d]=Ks(g,h,c.arrayMergeMode||"smart",l);else f[d]=h}return f}function gn(i,a,c="replace"){return Os(i,a,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function Zr(i,a){if(i===a)return!0;if(Array.isArray(i)&&Array.isArray(a)){if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(!Zr(i[c],a[c]))return!1;return!0}if(le(i)&&le(a)){let c=Object.keys(i),l=Object.keys(a);if(c.length!==l.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(a,u))return!1;if(!Zr(i[u],a[u]))return!1}return!0}return!1}function le(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class vr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,a,c={}){let{arrayStrategy:l="replace",useCache:u=!0,cacheTtl:f,trackPerformance:d=!0,verbose:h=!1}=c;if(u){let m=rt.getWithFileCheck("file",i);if(m){if(h)console.log(`Configuration loaded from cache: ${i}`);return m}}let g=async()=>{if(!Bt(i))return null;try{let m=`?t=${Date.now()}`,b=await import(i+m),T=b.default||b,v="default"in b,D=Object.keys(b).length>0;if(!v&&!D)throw new gt(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof T!=="object"||T===null||Array.isArray(T))throw new gt(i,Error("Configuration must export a valid object"),"unknown");let E={config:gn(a,T,l),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)rt.setWithFileCheck("file",E,i,f);return E}catch(m){throw m instanceof Error?_e.configLoad(i,m):_e.configLoad(i,Error(String(m)))}};if(d)return yt.track("loadFromPath",g,{path:i});return g()}async tryLoadFromPaths(i,a,c={}){for(let l of i)try{let u=await this.loadFromPath(l,a,c);if(u)return u}catch(u){if(u instanceof Error&&u.name==="ConfigLoadError")throw u;if(c.verbose)console.warn(`Failed to load config from ${l}:`,u)}return null}generateConfigPaths(i,a,c){let l=this.generateNamePatterns(i,c),u=[];for(let f of l)for(let d of this.extensions)u.push(Br(a,`${f}${d}`));return u}generateNamePatterns(i,a){let c=[];if(c.push("config",".config"),i)c.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(a){if(c.push(a,`.${a}.config`,`${a}.config`,`.${a}`),i)c.push(`${i}.${a}.config`,`.${i}.${a}.config`)}return c.filter(Boolean)}checkFileAccess(i){return Ns(async()=>Bt(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,a,c){let l=[];if(!Bt(i))return l;if(a||c){let u=this.generateNamePatterns(a||"",c);for(let f of u)for(let d of this.extensions){let h=Br(i,`${f}${d}`);if(await this.checkFileAccess(h))l.push(h)}}else try{let{readdirSync:u}=await import("fs"),f=u(i);for(let d of f)if(this.looksLikeConfigFile(d)){let h=Br(i,d);if(await this.checkFileAccess(h))l.push(h)}}catch{return[]}return l}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((c)=>c.test(i))}async validateConfigFile(i){let a=[];try{if(!Bt(i))return a.push("Configuration file does not exist"),a;let c=await import(i),l=c.default||c;if(l===void 0)a.push("Configuration file must export a default value or named exports");else if(typeof l!=="object"||l===null)a.push("Configuration must be an object");else if(Array.isArray(l))a.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),f=u(i,"utf8");JSON.parse(f)}catch(u){a.push(`Invalid JSON syntax: ${u}`)}}catch(c){a.push(`Failed to load configuration file: ${c}`)}return a}async getFileModificationTime(i){try{let{statSync:a}=await import("fs");return a(i).mtime}catch{return null}}async preloadConfigurations(i,a={}){let c=new Map;return await Promise.allSettled(i.map(async(l)=>{try{let u=await this.loadFromPath(l,{},a);if(u)c.set(l,u.config)}catch(u){if(a.verbose)console.warn(`Failed to preload ${l}:`,u)}})),c}}class mn{async validateConfiguration(i,a,c={}){let{stopOnFirstError:l=!1,validateRequired:u=!0,validateTypes:f=!0,customRules:d=[],trackPerformance:h=!0,verbose:g=!1}=c,m=async()=>{let b=[],T=[],v={stopOnFirstError:l,validateRequired:u,validateTypes:f,customRules:d,trackPerformance:h,verbose:g};try{if(typeof a==="string")return await this.validateWithSchemaFile(i,a,v);else if(Array.isArray(a))return this.validateWithRules(i,[...a,...d],v);else return this.validateWithJSONSchema(i,a,v)}catch(D){return b.push({path:"",message:`Validation failed: ${D}`,rule:"system"}),{isValid:!1,errors:b,warnings:T}}};if(h)return await yt.track("validateConfiguration",m);return m()}async validateWithSchemaFile(i,a,c){try{if(!co(a))throw new mt(a,[{path:"",message:"Schema file does not exist"}]);let l=await import(a),u=l.default||l;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(l){throw new mt(a,[{path:"",message:`Failed to load schema: ${l}`}])}}validateWithJSONSchema(i,a,c){let l=[],u=[];return this.validateObjectAgainstSchema(i,a,"",l,u,c),{isValid:l.length===0,errors:l,warnings:u}}validateObjectAgainstSchema(i,a,c,l,u,f){if(f.validateTypes&&a.type){let d=Array.isArray(i)?"array":typeof i,h=Array.isArray(a.type)?a.type:[a.type];if(!h.includes(d)){if(l.push({path:c,message:`Expected type ${h.join(" or ")}, got ${d}`,expected:h.join(" or "),actual:d,rule:"type"}),f.stopOnFirstError)return}}if(a.enum&&!a.enum.includes(i)){if(l.push({path:c,message:`Value must be one of: ${a.enum.join(", ")}`,expected:a.enum.join(", "),actual:i,rule:"enum"}),f.stopOnFirstError)return}if(typeof i==="string"){if(a.minLength!==void 0&&i.length<a.minLength)l.push({path:c,message:`String length must be at least ${a.minLength}`,expected:`>= ${a.minLength}`,actual:i.length,rule:"minLength"});if(a.maxLength!==void 0&&i.length>a.maxLength)l.push({path:c,message:`String length must not exceed ${a.maxLength}`,expected:`<= ${a.maxLength}`,actual:i.length,rule:"maxLength"});if(a.pattern){if(!new RegExp(a.pattern).test(i))l.push({path:c,message:`String does not match pattern ${a.pattern}`,expected:a.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(a.minimum!==void 0&&i<a.minimum)l.push({path:c,message:`Value must be at least ${a.minimum}`,expected:`>= ${a.minimum}`,actual:i,rule:"minimum"});if(a.maximum!==void 0&&i>a.maximum)l.push({path:c,message:`Value must not exceed ${a.maximum}`,expected:`<= ${a.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&a.items)for(let d=0;d<i.length;d++){let h=c?`${c}[${d}]`:`[${d}]`;if(this.validateObjectAgainstSchema(i[d],a.items,h,l,u,f),f.stopOnFirstError&&l.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let d=i;if(f.validateRequired&&a.required){for(let h of a.required)if(!(h in d)){if(l.push({path:c?`${c}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(a.properties){for(let[h,g]of Object.entries(a.properties))if(h in d){let m=c?`${c}.${h}`:h;if(this.validateObjectAgainstSchema(d[h],g,m,l,u,f),f.stopOnFirstError&&l.length>0)return}}if(a.additionalProperties===!1){let h=new Set(Object.keys(a.properties||{}));for(let g of Object.keys(d))if(!h.has(g))u.push({path:c?`${c}.${g}`:g,message:`Additional property '${g}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,a,c){let l=[],u=[];for(let f of a)try{let d=this.getValueByPath(i,f.path),h=this.validateWithRule(d,f,f.path);if(l.push(...h),c.stopOnFirstError&&l.length>0)break}catch(d){l.push({path:f.path,message:`Rule validation failed: ${d}`,rule:"system"})}return{isValid:l.length===0,errors:l,warnings:u}}validateWithRule(i,a,c){let l=[];if(a.required&&(i===void 0||i===null))return l.push({path:c,message:a.message||`Property '${c}' is required`,expected:"required",rule:"required"}),l;if(i===void 0||i===null)return l;if(a.type){let u=Array.isArray(i)?"array":typeof i;if(u!==a.type)l.push({path:c,message:a.message||`Expected type ${a.type}, got ${u}`,expected:a.type,actual:u,rule:"type"})}if(a.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<a.min)l.push({path:c,message:a.message||`Value must be at least ${a.min}`,expected:`>= ${a.min}`,actual:u,rule:"min"})}if(a.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>a.max)l.push({path:c,message:a.message||`Value must not exceed ${a.max}`,expected:`<= ${a.max}`,actual:u,rule:"max"})}if(a.pattern&&typeof i==="string"){if(!a.pattern.test(i))l.push({path:c,message:a.message||`Value does not match pattern ${a.pattern}`,expected:a.pattern.toString(),actual:i,rule:"pattern"})}if(a.enum&&!a.enum.includes(i))l.push({path:c,message:a.message||`Value must be one of: ${a.enum.join(", ")}`,expected:a.enum.join(", "),actual:i,rule:"enum"});if(a.validator){let u=a.validator(i);if(u)l.push({path:c,message:a.message||u,rule:"custom"})}return l}getValueByPath(i,a){if(!a)return i;let c=a.split("."),l=i;for(let u of c)if(l&&typeof l==="object"&&u in l)l=l[u];else return;return l}generateRulesFromInterface(i){let a=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let l of c){let[,u,f,d]=l;a.push({path:u,required:!f,type:this.mapTypeScriptType(d)})}return a}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Vs},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class pn{fileLoader=new vr;envProcessor=new Tr;validator=new mn;async loadConfig(i){let a=Date.now(),{cache:c,performance:l,schema:u,validate:f,...d}=i;try{if(c?.enabled){let g=this.checkCache(d.name||"",d);if(g)return g}let h;try{h=await this.loadConfigurationStrategies(d,!0,c)}catch(g){let m=d.__strictErrorHandling;if(g instanceof Error&&g.name==="ConfigNotFoundError"){if(m)throw g;h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`No configuration file found for "${d.name||"config"}", using defaults with environment variables`]}}else if(g instanceof Error&&g.name==="ConfigLoadError"){let b=g.message.includes("EACCES")||g.message.includes("EPERM")||g.message.includes("permission denied"),T=!b&&(g.message.includes("syntax")||g.message.includes("Expected")||g.message.includes("Unexpected")||g.message.includes("BuildMessage")||g.message.includes("errors building")),v=g.message.includes("Configuration must export a valid object")||g.message.includes("Configuration file is empty and exports nothing");if(m&&(v||b))throw g;if(T&&(!m||!v))h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!m)h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`Configuration loading error, using defaults: ${g.message}`]};else throw g}else h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${g instanceof Error?g.message:String(g)}`]}}if(u||f)await this.validateConfiguration(h.config,u,f,d.name);if(c?.enabled&&h)this.cacheResult(d.name||"",h,c,d);if(l?.enabled){let g={operation:"loadConfig",duration:Date.now()-a,configName:d.name,timestamp:new Date};if(l.onMetrics)l.onMetrics(g);if(l.slowThreshold&&g.duration>l.slowThreshold)de.warn(`Slow configuration loading detected: ${g.duration}ms for ${d.name}`);h.metrics=g}return h}catch(h){let g=Date.now()-a;throw de.error(`Configuration loading failed after ${g}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(i,a=!1,c){let{name:l="",alias:u,cwd:f,configDir:d,defaultConfig:h,checkEnv:g=!0,arrayStrategy:m="replace",verbose:b=!1}=i,T=f||Le.cwd(),v=[],D=await this.loadLocalConfiguration(l,u,T,d,h,m,b,g,c);if(D)return v.push(...this.getLocalSearchPaths(l,u,T,d)),this.finalizeResult(D,v,g,l,b);let R=await this.loadHomeConfiguration(l,u,h,m,b,g);if(R)return v.push(...this.getHomeSearchPaths(l,u)),this.finalizeResult(R,v,g,l,b);let k=await this.loadPackageJsonConfiguration(l,u,T,h,m,b,g);if(k)return v.push(se(T,"package.json")),this.finalizeResult(k,v,g,l,b);if(v.push(...this.getAllSearchPaths(l,u,T,d)),a)throw _e.configNotFound(l,v,u);return{...await this.applyEnvironmentVariables(l,h,g,b),warnings:[`No configuration file found for "${l}"${u?` or alias "${u}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,a,c,l,u,f,d,h,g){let m=h?dt(i,u,d):u,b=this.getLocalDirectories(c,l);for(let T of b){if(d)de.info(`Searching for configuration in: ${T}`);let v=this.fileLoader.generateConfigPaths(i,T,a),D=await this.fileLoader.tryLoadFromPaths(v,m,{arrayStrategy:f,verbose:d,cacheTtl:g?.ttl,useCache:!g?.ttl||g.ttl>100});if(D){if(d)de.success(`Configuration loaded from: ${D.source.path}`);return D}}return null}async loadHomeConfiguration(i,a,c,l,u,f){if(!i)return null;let d=f?dt(i,c,u):c,h=[se(ze(),".config",i),se(ze(),".config"),ze()];for(let g of h){if(u)de.info(`Checking home directory: ${g}`);let m=this.fileLoader.generateConfigPaths(i,g,a),b=await this.fileLoader.tryLoadFromPaths(m,d,{arrayStrategy:l,verbose:u});if(b){if(u)de.success(`Configuration loaded from home directory: ${b.source.path}`);return b}}return null}async loadPackageJsonConfiguration(i,a,c,l,u,f,d){let h=d?dt(i,l,f):l;try{let g=se(c,"package.json");if(!Yr(g))return null;let m=await import(g),b=m[i],T=i;if(!b&&a)b=m[a],T=a;if(b&&typeof b==="object"&&!Array.isArray(b)){if(f)de.success(`Configuration loaded from package.json: ${T}`);return{config:gn(h,b,u),source:{type:"package.json",path:g,priority:30,timestamp:new Date}}}}catch(g){if(f)de.warn("Failed to load package.json:",[g instanceof Error?g:Error(String(g))])}return null}async applyEnvironmentVariables(i,a,c,l){if(!c||!i||typeof a!=="object"||a===null||Array.isArray(a))return{config:a,source:{type:"default",priority:10,timestamp:new Date}};return{config:dt(i,a,l),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,a,c,l,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,a,c,l){let u=[];if(c){let f=c(i);if(f)u.push(...f)}if(a){let f=await this.validator.validateConfiguration(i,a);if(!f.isValid)u.push(...f.errors.map((d)=>d.path?`${d.path}: ${d.message}`:d.message))}if(u.length>0)throw _e.configValidation(l||"unknown",u,l)}checkCache(i,a){let c=this.generateCacheKey(i,a);return rt.get(c)||null}cacheResult(i,a,c,l){let u=this.generateCacheKey(i,l);rt.set(u,a,void 0,c.ttl)}generateCacheKey(i,a){let c=[i];if(a.alias)c.push(`alias:${a.alias}`);if(a.cwd)c.push(`cwd:${a.cwd}`);if(a.configDir)c.push(`configDir:${a.configDir}`);if("checkEnv"in a)c.push(`checkEnv:${a.checkEnv}`);return c.join("|")}getLocalDirectories(i,a){return Array.from(new Set([i,se(i,"config"),se(i,".config"),a?se(i,a):void 0].filter(Boolean)))}getAllSearchPaths(i,a,c,l){let u=[];return u.push(...this.getLocalSearchPaths(i,a,c,l)),u.push(...this.getHomeSearchPaths(i,a)),u.push(se(c,"package.json")),u}getLocalSearchPaths(i,a,c,l){let u=this.getLocalDirectories(c,l),f=[];for(let d of u)f.push(...this.fileLoader.generateConfigPaths(i,d,a));return f}getHomeSearchPaths(i,a){if(!i)return[];let c=[se(ze(),".config",i),se(ze(),".config"),ze()],l=[];for(let u of c)l.push(...this.fileLoader.generateConfigPaths(i,u,a));return l}async loadConfigWithResult(i){return this.loadConfig(i)}}function ls(i){let c=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),l=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return c||l}async function Go(i){return $e.loadConfig({...i,__strictErrorHandling:!0})}async function Fs(i){let a="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let l;if(c)l=await $e.loadConfig(i);else l=await $e.loadConfig({...i,defaultConfig:a,cache:{enabled:!0},performance:{enabled:!1}});return l?.config??a}catch(l){let u=l instanceof Error?l.name:"UnknownError",f=l instanceof Error?l.message:String(l);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||f.includes("config"))&&i.verbose)de.warn("Unexpected error loading config, using defaults:",[l instanceof Error?l:Error(String(l))]);let h=c?{...i,defaultConfig:a}:{...i,defaultConfig:a,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await $e.applyEnvironmentVariables(h.name||"",a,!0,h.verbose||!1))?.config??a;return a}}async function Yo(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:a}=await import("process");try{return(await $e.loadConfig({name:i,cwd:a(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(c){if(c instanceof Error&&(c.name==="ConfigNotFoundError"||c.name==="ConfigLoadError"&&ls(c)))return(await $e.applyEnvironmentVariables(i,{},!0,!1)).config;throw c}}try{return(await $e.loadConfig({...i,cwd:i.cwd||Le.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(a){if(a instanceof Error&&(a.name==="ConfigNotFoundError"||a.name==="ConfigLoadError"&&ls(a)))return(await $e.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw a}}async function Jo(i,a,c="replace"){let l=new vr;try{let u=await l.loadFromPath(i,a,{arrayStrategy:c,useCache:!1,trackPerformance:!1});return u?u.config:null}catch{return null}}function dt(i,a,c=!1){let l=new Tr,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(d,h=[]){let g={...d};for(let[m,b]of Object.entries(d)){let T=[...h,m],v=[`${u}_${T.join("_").toUpperCase()}`,`${u}_${T.map((k)=>k.toUpperCase()).join("")}`,`${u}_${T.map((k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],D,R;for(let k of v)if(D=Le.env[k],D!==void 0){R=k;break}if(D!==void 0&&R)if(typeof b==="boolean")g[m]=["true","1","yes"].includes(D.toLowerCase());else if(typeof b==="number"){let k=Number(D);if(!Number.isNaN(k))g[m]=k}else if(Array.isArray(b))try{g[m]=JSON.parse(D)}catch{g[m]=D.split(",").map((k)=>k.trim())}else g[m]=D;else if(b&&typeof b==="object"&&!Array.isArray(b))g[m]=f(b,T)}return g}return f(a)}function Zo(i){let a=se(Le.cwd(),i.configDir),c=se(Le.cwd(),i.generatedDir),l=se(c,"config-types.ts");if(!Yr(In(l)))Bi(In(l),{recursive:!0,mode:511});let u=Yr(a)?Ii(a).map((d)=>d.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${Ca}
32
+ export type ConfigNames = ${u.length?`'${u.join("' | '")}'`:"string"}
33
+ `;ji(l,f,{mode:438})}function Xo(i){let a=null,c=null,l=()=>{if(!c)c=Fs(i).then((f)=>(a=f,f),(f)=>{let d="defaultConfig"in i?i.defaultConfig:{};if(a=d,"verbose"in i&&i.verbose)de.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return d});return c},u="defaultConfig"in i?i.defaultConfig:{};return a=u,l(),new Proxy({},{get(f,d){if(a)return a[d];let h=u[d];return l(),h},has(f,d){return d in(a||u)},ownKeys(){return Object.keys(a||u)},getOwnPropertyDescriptor(f,d){return Object.getOwnPropertyDescriptor(a||u,d)},set(f,d,h){if(!a)a={...u};return a[d]=h,!0}})}function ea(i){let a=ts(fo.cwd(),i?.configDir||"./config");function c(){if(!lo(a))return[];let u=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],d=uo(a).filter((g)=>u.has(Ir(g))).map((g)=>({base:g.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:g})),h=new Map;for(let{base:g,file:m}of d){let b=Ir(m).toLowerCase(),T=h.get(g);if(!T){h.set(g,m);continue}let v=Ir(T).toLowerCase();if(f.indexOf(b)<f.indexOf(v))h.set(g,m)}return Array.from(h.entries()).map(([g,m])=>({base:g,file:m})).sort((g,m)=>g.base.localeCompare(m.base))}function l(){let u=c(),f=u.map((m)=>m.base),d=f.length?f.map((m)=>`'${m}'`).join(" | "):"string",h=u.length?`{
34
+ ${u.map((m)=>{let b=ts(a,m.file).replace(/\\/g,"/");return` '${m.base}': typeof import('${b}').default`}).join(`,
35
+ `)}
36
+ }`:"Record<string, any>";return`export type ConfigNames = ${d}
37
+ export type ConfigByName = ${h}
38
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
+ export type ConfigOf = Config
40
+ `}return{name:"bunfig-plugin",setup(u){u.onResolve({filter:/^virtual:bunfig-types$/},(f)=>({path:f.path,namespace:"bunfig-virtual"})),u.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:l(),loader:"ts"}))}}}var Ls,rt,yt,Bs,ta,ra,us,tr,Xr,ee,j,na,fs,sa,ds,ia,oa,Ur,aa,hs,gs,qr,ca,la,ua,fa,rr,Is,da,te,ha,ga,ms,nr,en,Y,O,ma,ys,ya,ps,pa,wa,zr,ba,ws,bs,Ta,Hr,va,Da,$a,ka,xa,sr,js,Ea,Ca="0.15.6",ae,gr,gt,tn,rn,mr,nn,sn,mt,on,an,_e,Ws,Vs,de,$e,Us,qs,Sa=So(async()=>{Ls=import.meta.require,rt=new un,yt=new fn,Bs={createKey:Mo,isEquivalent:Ao,estimateMemoryUsage:Ro},ta=cr(Jr.cwd(),"config"),ra=cr(Jr.cwd(),"src/generated"),us=ar.env.CLARITY_LOG_DIR||Ui(Oo(),"logs"),tr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:us,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Xr=await Po(),ee={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},j=ee,na=ee.red,fs=ee.green,sa=ee.yellow,ds=ee.blue,ia=ee.magenta,oa=ee.cyan,Ur=ee.white,aa=ee.gray,hs=ee.bgRed,gs=ee.bgYellow,qr=ee.bold,ca=ee.dim,la=ee.italic,ua=ee.underline,fa=ee.reset,rr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Is={debug:"\uD83D\uDD0D",info:ds("\u2139"),success:fs("\u2713"),warning:gs(Ur(qr(" WARN "))),error:hs(Ur(qr(" ERROR ")))},da=new fr("stacks"),te=new fr("bunfig",{showTags:!0}),ha=ne(ht.cwd(),"config"),ga=ne(ht.cwd(),"src/generated"),ms=or.env.CLARITY_LOG_DIR||Wi(Bo(),"logs"),nr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ms,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},en=await Io(),Y={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=Y,ma=Y.red,ys=Y.green,ya=Y.yellow,ps=Y.blue,pa=Y.magenta,wa=Y.cyan,zr=Y.white,ba=Y.gray,ws=Y.bgRed,bs=Y.bgYellow,Ta=Y.bgGray,Hr=Y.bold,va=Y.dim,Da=Y.italic,$a=Y.underline,ka=Y.strikethrough,xa=Y.reset,sr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},js={debug:"\uD83D\uDD0D",info:ps("\u2139"),success:ys("\u2713"),warning:bs(zr(Hr(" WARN "))),error:ws(zr(Hr(" ERROR ")))},Ea=new hr("stacks"),ae=class extends Error{timestamp;context;constructor(a,c={}){super(a);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=c,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 a=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([c,l])=>`${c}: ${l}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${a}`}},gr=class extends ae{code="CONFIG_NOT_FOUND";constructor(a,c,l){let u=l?` or alias "${l}"`:"";super(`Configuration "${a}"${u} not found`,{configName:a,alias:l,searchPaths:c,searchPathCount:c.length})}},gt=class extends ae{code="CONFIG_LOAD_ERROR";constructor(a,c,l){super(`Failed to load configuration from "${a}": ${c.message}`,{configPath:a,configName:l,originalError:c.name,originalMessage:c.message});this.cause=c}},tn=class extends ae{code="CONFIG_VALIDATION_ERROR";constructor(a,c,l){super(`Configuration validation failed for "${a}"`,{configPath:a,configName:l,validationErrors:c,errorCount:c.length})}},rn=class extends ae{code="CONFIG_MERGE_ERROR";constructor(a,c,l,u){super(`Failed to merge configuration from "${a}" with "${c}": ${l.message}`,{sourcePath:a,targetPath:c,configName:u,originalError:l.name,originalMessage:l.message});this.cause=l}},mr=class extends ae{code="ENV_VAR_ERROR";constructor(a,c,l,u){super(`Failed to parse environment variable "${a}" with value "${c}" as ${l}`,{envKey:a,envValue:c,expectedType:l,configName:u})}},nn=class extends ae{code="FILE_SYSTEM_ERROR";constructor(a,c,l){super(`File system ${a} failed for "${c}": ${l.message}`,{operation:a,path:c,originalError:l.name,originalMessage:l.message});this.cause=l}},sn=class extends ae{code="TYPE_GENERATION_ERROR";constructor(a,c,l){super(`Failed to generate types from "${a}" to "${c}": ${l.message}`,{configDir:a,outputPath:c,originalError:l.name,originalMessage:l.message});this.cause=l}},mt=class extends ae{code="SCHEMA_VALIDATION_ERROR";constructor(a,c,l){super(`Schema validation failed${l?` for config "${l}"`:""}`,{schemaPath:a,configName:l,validationErrors:c,errorCount:c.length})}},on=class extends ae{code="BROWSER_CONFIG_ERROR";constructor(a,c,l,u){super(`Failed to fetch configuration from "${a}": ${c} ${l}`,{endpoint:a,status:c,statusText:l,configName:u})}},an=class extends ae{code="PLUGIN_ERROR";constructor(a,c,l){super(`Plugin "${a}" failed during ${c}: ${l.message}`,{pluginName:a,operation:c,originalError:l.name,originalMessage:l.message});this.cause=l}},_e={configNotFound(i,a,c){return new gr(i,a,c)},configLoad(i,a,c){return new gt(i,a,c)},configValidation(i,a,c){return new tn(i,a,c)},configMerge(i,a,c,l){return new rn(i,a,c,l)},envVar(i,a,c,l){return new mr(i,a,c,l)},fileSystem(i,a,c){return new nn(i,a,c)},typeGeneration(i,a,c){return new sn(i,a,c)},schemaValidation(i,a,c){return new mt(i,a,c)},browserConfig(i,a,c,l){return new on(i,a,c,l)},plugin(i,a,c){return new an(i,a,c)}},Ws={replace:"replace",concat:"concat",smart:"smart"},Vs=/^https?:\/\//,de=new hr("bunfig",{showTags:!0}),$e=new pn,Us=se(Le.cwd(),"config"),qs=se(Le.cwd(),"src/generated")});function Ma(i,a={}){let c=lr.cwd();while(c.includes("storage"))c=rs(c,"..");let l=rs(c,i||"");if(a?.relative)return go(lr.cwd(),l);return l}var Aa=lr.env.CLARITY_LOG_DIR||ho(Ma(),"logs"),zs={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Aa,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},yr={...zs},Bl=(async()=>{try{let{loadConfig:i}=await Sa().then(()=>Ms),a=await i({name:"clarity",alias:"logging",defaultConfig:zs,cwd:lr.cwd()});if(a)Object.assign(yr,a)}catch{}return yr})();function J(){if(De.env.NODE_ENV==="test"||De.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ra(){if(De.env.NODE_ENV==="test"||De.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof De<"u"){let i=De.type;if(i==="renderer"||i==="worker")return!1;return!!(De.versions&&(De.versions.node||De.versions.bun))}return!1}class Hs{async format(i){let a=await Ra(),c=await this.getMetadata(a);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:a}=await import("os");return{pid:tt.pid,hostname:a(),environment:tt.env.NODE_ENV||"development",platform:tt.platform,version:tt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tt.env.NODE_ENV||tt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var Z={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},P=Z,{red:Il,green:Na,yellow:jl,blue:_a,magenta:Wl,cyan:Vl,white:Ts,gray:Ul,bgRed:Oa,bgYellow:Pa,bgGray:ql,bold:vs,dim:zl,italic:Hl,underline:Ql,strikethrough:Gl,reset:Yl}=Z,Qr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ka={debug:"\uD83D\uDD0D",info:_a("\u2139"),success:Na("\u2713"),warning:Pa(Ts(vs(" WARN "))),error:Oa(Ts(vs(" ERROR ")))};class Dr{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(i,a={}){this.name=i,this.config={...yr},this.options=this.normalizeOptions(a),this.formatter=this.options.formatter||new Hs,this.enabled=a.enabled??!0,this.fancy=a.fancy??!0,this.tagFormat=a.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=a.timestampPosition??"right",this.environment=a.environment??F.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(a);let c={...a},l=a.timestamp!==void 0;if(l)delete c.timestamp;if(this.config={...this.config,...c,timestamp:l||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),f=this.generateKey();this.currentKeyId=u,this.keys.set(u,f),this.encryptionKeys.set(u,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let a={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return a[i]>=a[c]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Qr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Qr};return{...Qr,...i.fingersCrossed}}normalizeOptions(i){let a={format:"json",level:"info",logDirectory:yr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...a,...Object.fromEntries(Object.entries(i).filter(([,l])=>l!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=a.level;return c}shouldWriteToFile(){return!J()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,f=0,d=3,h=1000;while(f<d)try{try{try{await bo(this.config.logDirectory,os.F_OK|os.W_OK)}catch(m){if(m instanceof Error&&"code"in m)if(m.code==="ENOENT")await To(this.config.logDirectory,{recursive:!0,mode:493});else if(m.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw m;else throw m}}catch(m){throw console.error("Debug: [writeToFile] Failed to create log directory:",m),m}let g=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:be.from(i);try{if(!zt(this.currentLogFile))await Vr(this.currentLogFile,"",{mode:420});if(u=is(this.currentLogFile,"a",420),wo(u,g,{flag:"a"}),ss(u),u!==void 0)Wr(u),u=void 0;if((await Xe(this.currentLogFile)).size===0){if(await Vr(this.currentLogFile,g,{flag:"w",mode:420}),(await Xe(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(m){let b=m;if(b.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(b.code)){if(f<d-1){let T=typeof b.message==="string"?b.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${d}:`,T);let v=h*2**f;await new Promise((D)=>setTimeout(D,v)),f++;continue}}if(b?.code&&["ENOSPC","EDQUOT"].includes(b.code))throw Error(`Disk quota exceeded or no space left on device: ${b.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",b),b}finally{if(u!==void 0)try{Wr(u)}catch(m){console.error("Debug: [writeToFile] Error closing file descriptor:",m)}}}catch(g){if(f===d-1){let b=g,T=typeof b.message==="string"?b.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",T),g}f++;let m=h*2**(f-1);await new Promise((b)=>setTimeout(b,m))}})();this.pendingOperations.push(c);let l=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(l,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 et(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 et(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return et(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(J())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,a;switch(i.frequency){case"daily":a=86400000;break;case"weekly":a=604800000;break;case"monthly":a=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},a)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let a=this.config.rotation.keyRotation;if(!a?.enabled)return;let c=typeof a.interval==="number"?a.interval:60,l=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},l)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let a=this.config.rotation.keyRotation,c=this.generateKeyId(),l=this.generateKey();this.currentKeyId=c,this.keys.set(c,l),this.encryptionKeys.set(c,{key:l,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,h],[,g])=>g.createdAt.getTime()-h.createdAt.getTime()),f=typeof a.maxKeys==="number"?a.maxKeys:1,d=Math.max(1,f);if(u.length>d)for(let[h]of u.slice(d))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return jr(16).toString("hex")}generateKey(){return jr(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:a}=this.getCurrentKey(),c=jr(16),l=mo("aes-256-gcm",a,c),u=be.isBuffer(i)?i:be.from(i,"utf8"),f=l.update(u),d=l.final(),h=f.length+d.length,g=l.getAuthTag(),m=be.allocUnsafe(16+h+16);return c.copy(m,0),f.copy(m,16),d.copy(m,16+f.length),g.copy(m,16+h),{encrypted:m,iv:c}}async compressData(i){return new Promise((a,c)=>{let l=cs(),u=[];l.on("data",(f)=>u.push(f)),l.on("end",()=>a(be.from(be.concat(u)))),l.on("error",c),l.write(i),l.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let a=this.config.rotation.encrypt;return{...i,...a}}return i}async rotateLog(){if(J())return;if(!this.shouldWriteToFile())return;let i=await Xe(this.currentLogFile).catch(()=>null);if(!i)return;let a=this.config.rotation;if(typeof a==="boolean")return;if(a.maxSize&&i.size>=a.maxSize){let c=this.currentLogFile,l=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await Gt(this.config.logDirectory),f=u.filter((g)=>g.startsWith(this.name)&&/\.log\.\d+$/.test(g)).sort((g,m)=>{let b=Number.parseInt(g.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(m.match(/\.log\.(\d+)$/)?.[1]||"0")-b}),d=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${c}.${d}`;if(await Xe(c).catch(()=>null))try{if(await as(c,h),a.compress)try{let g=`${h}.gz`;await this.compressLogFile(h,g),await Yt(h)}catch(g){console.error("Error compressing rotated file:",g)}if(f.length===0&&!u.some((g)=>g.endsWith(".log.1")))try{let g=`${c}.1`;await Vr(g,"")}catch(g){console.error("Error creating backup file:",g)}}catch(g){console.error(`Error during rotation: ${g instanceof Error?g.message:String(g)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),f=c.replace(/\.log$/,`-${u}.log`);if(await Xe(c).catch(()=>null))await as(c,f)}if(this.currentLogFile=l,a.maxFiles){let f=(await Gt(this.config.logDirectory)).filter((d)=>d.startsWith(this.name)).sort((d,h)=>h.localeCompare(d));for(let d of f.slice(a.maxFiles))await Yt(et(this.config.logDirectory,d))}}}async compressLogFile(i,a){let c=ns(i),l=po(a),u=cs();await $o(c,u,l)}async handleFingersCrossedBuffer(i,a){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let l=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(l);console.log(l)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(a);console.log(a)}}shouldLog(i){if(!this.enabled)return!1;let a={debug:0,info:1,success:2,warning:3,error:4};return a[i]>=a[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((a)=>{console.error("Error in pending write operation:",a)});return Promise.resolve()})),zt(this.currentLogFile))try{let i=is(this.currentLogFile,"r+");ss(i),Wr(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!J()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let a=(await Gt(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of a)try{await Yt(et(this.config.logDirectory,c))}catch(l){console.error(`Failed to delete temp file ${c}:`,l)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?P.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||J())return!1;let i=typeof F.env.NO_COLOR<"u",a=F.env.FORCE_COLOR==="0";if(i||a)return!1;return!!(typeof F.stderr<"u"&&F.stderr.isTTY||typeof F.stdout<"u"&&F.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:a,icon:c="",tag:l="",message:u,level:f,showTimestamp:d=!0}=i,h=(D)=>D.replace(this.ANSI_PATTERN,"");if(!this.fancy){let D=[];if(d)D.push(a);if(f==="warning")D.push("WARN");else if(f==="error")D.push("ERROR");else if(c)D.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(l)D.push(l.replace(/[[\]]/g,""));return D.push(u),D.join(" ")}let g=F.stdout.columns||120,m="";if(f==="warning"||f==="error")m=`${c} ${u}`;else if(f==="info"||f==="success")m=`${c} ${l} ${u}`;else m=`${c} ${l} ${P.cyan(u)}`;if(!d)return m.trim();let b=h(m).trim().length,T=h(a).length,v=Math.max(1,g-2-b-T);return`${m.trim()}${" ".repeat(v)}${a}`}formatMessage(i,a){if(a.length===1&&Array.isArray(a[0]))return i.replace(/\{(\d+)\}/g,(f,d)=>{let h=Number.parseInt(d,10);return h<a[0].length?String(a[0][h]):f});let c=/%([sdijfo%])/g,l=0,u=i.replace(c,(f,d)=>{if(d==="%")return"%";if(l>=a.length)return f;let h=a[l++];switch(d){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 f}});if(l<a.length)u+=` ${a.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let a=i;return a=a.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,l,u)=>{let f=P.underline(P.blue(l)),d=this.toAbsoluteFilePath(u);if(d&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(d)}`,g="\x1B]8;;",m="\x1B\\";return`\x1B]8;;${h}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),a=a.replace(/`([^`]+)`/g,(c,l)=>P.bgGray(l)),a=a.replace(/\*\*([^*]+)\*\*/g,(c,l)=>P.bold(l)),a=a.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,l)=>P.italic(l)),a=a.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,l)=>P.italic(l)),a=a.replace(/~([^~]+)~/g,(c,l)=>P.strikethrough(l)),a}supportsHyperlinks(){if(J())return!1;let i=F.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let a=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(a)&&a>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let a=i;if(a.startsWith("file://"))a=a.replace(/^file:\/\//,"");if(a.startsWith("~")){let c=F.env.HOME||"";if(c)a=a.replace(/^~(?=$|\/)/,c)}if(vo(a)||a.startsWith("./")||a.startsWith("../"))a=Do(a);else return null;return zt(a)?a:null}catch{return null}}buildOutputTexts(i){let a=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:a,fileText:c}}async log(i,a,...c){if(!this.shouldLog(i))return;let l=new Date,u=this.formatConsoleTimestamp(l),f=this.formatFileTimestamp(l),d,h;if(a instanceof Error)d=a.message,h=a.stack;else d=this.formatMessage(a,c);let{consoleText:g,fileText:m}=this.buildOutputTexts(d);if(this.shouldStyleConsole()){let T=this.options.showIcons===!1?"":Ka[i],v=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",D;switch(i){case"debug":D=this.formatConsoleMessage({timestamp:u,icon:T,tag:v,message:P.gray(g),level:i}),console.error(D);break;case"info":D=this.formatConsoleMessage({timestamp:u,icon:T,tag:v,message:g,level:i}),console.warn(D);break;case"success":D=this.formatConsoleMessage({timestamp:u,icon:T,tag:v,message:P.green(g),level:i}),console.error(D);break;case"warning":D=this.formatConsoleMessage({timestamp:u,icon:T,tag:v,message:g,level:i}),console.warn(D);break;case"error":if(D=this.formatConsoleMessage({timestamp:u,icon:T,tag:v,message:g,level:i}),console.error(D),h){let R=h.split(`
41
+ `);for(let k of R)if(k.trim()&&!k.includes(d))console.error(this.formatConsoleMessage({timestamp:u,message:P.gray(` ${k}`),level:i,showTimestamp:!1}))}break}}else if(!J()){if(console.error(`${f} ${this.environment}.${i.toUpperCase()}: ${d}`),h)console.error(h)}let b=`${f} ${this.environment}.${i.toUpperCase()}: ${m}
42
+ `;if(h)b+=`${h}
43
+ `;if(b=b.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(b)}progress(i,a=""){let c={update:(h,g)=>{},finish:(h)=>{},interrupt:(h,g)=>{}};if(!this.enabled)return c;let l=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:a||"",barLength:l,lastRenderedLine:""},this.shouldStyleConsole()&&!J()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(h,g)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),g!==void 0)this.activeProgressBar.message=g;if(this.shouldStyleConsole()&&!J()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,g="info")=>{if(!J()&&F.stdout.isTTY)F.stdout.write(`
44
+ `);if(this[g==="warning"?"warn":g](h),this.activeProgressBar&&this.shouldStyleConsole()&&!J()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let a=performance.now();if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",l=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":P.blue("\u25D0"),tag:c,message:`${P.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let l=performance.now(),u=Math.round(l-a),f=`${i} completed in ${u}ms`,d=new Date,h=this.formatConsoleTimestamp(d),m=`${this.formatFileTimestamp(d)} ${this.environment}.INFO: ${f}`;if(c)m+=` ${JSON.stringify(c)}`;if(m+=`
45
+ `,m=m.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let b=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":P.green("\u2713"),tag:b,message:`${f}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!J())console.error(m.trim());if(this.shouldWriteToFile())await this.writeToFile(m)}}async debug(i,...a){await this.log("debug",i,...a)}async info(i,...a){await this.log("info",i,...a)}async success(i,...a){await this.log("success",i,...a)}async warn(i,...a){await this.log("warning",i,...a)}async error(i,...a){await this.log("error",i,...a)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:a}=i;return!!a}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let a=`${this.name}:${i}`,c=new Dr(a,{...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(c),c}createReadStream(){if(J())throw Error("createReadStream is not supported in browser environments");if(!zt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ns(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let a=this.config.rotation;if(!a.encrypt||typeof a.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let c=this.keys.get(this.currentKeyId);try{let l=be.isBuffer(i)?i:be.from(i,"base64"),u=l.subarray(0,16),f=l.subarray(l.length-16),d=l.subarray(16,l.length-16),h=yo("aes-256-gcm",c,u);h.setAuthTag(f);let g=h.update(d),m=h.final(),b=g.length+m.length,T=be.allocUnsafe(b);return g.copy(T,0),m.copy(T,g.length),T.toString("utf8")}catch(l){throw Error(`Decryption failed: ${l instanceof Error?l.message:String(l)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return J()}isServerMode(){return!J()}setTestEncryptionKey(i,a){this.currentKeyId=i,this.keys.set(i,a)}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(i){if(!this.enabled)return;let a=new Date,c=this.formatConsoleTimestamp(a),l=this.formatFileTimestamp(a),{consoleText:u,fileText:f}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let h=u.split(`
46
+ `),g=Math.max(...h.map((v)=>v.length))+2,m=`\u250C${"\u2500".repeat(g)}\u2510`,b=`\u2514${"\u2500".repeat(g)}\u2518`,T=h.map((v)=>this.formatConsoleMessage({timestamp:c,message:P.cyan(v),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:P.cyan(m),showTimestamp:!1})),T.forEach((v)=>console.error(v)),console.error(this.formatConsoleMessage({timestamp:c,message:P.cyan(b),showTimestamp:!1}))}else if(!J())console.error(`${l} ${this.environment}.INFO: [BOX] ${f}`);let d=`${l} ${this.environment}.INFO: [BOX] ${f}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}async prompt(i){if(J())return Promise.resolve(!0);return new Promise((a)=>{console.error(`${P.cyan("?")} ${i} (y/n) `);let c=(l)=>{let u=l.toString().trim().toLowerCase();F.stdin.removeListener("data",c);try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!1)}catch{}F.stdin.pause(),console.error(""),a(u==="y"||u==="yes")};try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!0)}catch{}F.stdin.resume(),F.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...a){if(!this.enabled)return;let c=i;if(a&&a.length>0){let g=/%([sdijfo%])/g,m=0;if(c=i.replace(g,(b,T)=>{if(T==="%")return"%";if(m>=a.length)return b;let v=a[m++];switch(T){case"s":return String(v);case"d":case"i":return Number(v).toString();case"j":case"o":return JSON.stringify(v,null,2);default:return b}}),m<a.length)c+=` ${a.slice(m).map((b)=>typeof b==="object"?JSON.stringify(b,null,2):String(b)).join(" ")}`}let{consoleText:l,fileText:u}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let g=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",m=this.options.showIcons===!1?"":`${P.blue("\u25D0")} `;console.error(`${m}${g} ${P.cyan(l)}`)}let h=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${u}
48
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}renderProgressBar(i,a=!1){if(!this.enabled||!this.shouldStyleConsole()||!F.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),l=Math.round(i.barLength*c/100),u=i.barLength-l,f=P.green("\u2501".repeat(l)),d=P.gray("\u2501".repeat(u)),h=`[${f}${d}]`,g=`${c}%`.padStart(4),m=i.message?` ${i.message}`:"",b=this.options.showIcons===!1?"":a||c===100?P.green("\u2713"):P.blue("\u25B6"),T=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",v=`\r${b}${T} ${h} ${g}${m}`,D=F.stdout.columns||80,R=" ".repeat(Math.max(0,D-v.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${v}${R}`,F.stdout.write(i.lastRenderedLine),a)F.stdout.write(`
49
+ `)}finishProgressBar(i,a){if(!this.enabled||!this.fancy||J()||!F.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(a)i.message=a;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(J()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let a=await Gt(this.config.logDirectory),c=[];for(let l of a){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(l):l.startsWith(this.name))||!l.endsWith(".log"))continue;let f=et(this.config.logDirectory,l);if(i.before)try{if((await Xe(f)).mtime>=i.before)continue}catch(d){console.error(`Failed to get stats for file ${f}:`,d);continue}c.push(f)}if(c.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${c.length} log file(s)...`);for(let l of c)try{await Yt(l),console.warn(`Deleted log file: ${l}`)}catch(u){console.error(`Failed to delete log file ${l}:`,u)}console.warn("Log clearing process finished.")}catch(a){console.error("Error during log clearing process:",a)}}}var Jl=new Dr("stacks");class he extends Error{timestamp;context;constructor(i,a={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=a,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 i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([a,c])=>`${a}: ${c}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class Qs extends he{code="CONFIG_NOT_FOUND";constructor(i,a,c){let l=c===void 0?[]:Array.isArray(c)?c.filter(Boolean):[c],u="";if(l.length===1)u=` or alias "${l[0]}"`;else if(l.length>1)u=` or aliases ${l.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${i}"${u} not found`,{configName:i,alias:c,searchPaths:a,searchPathCount:a.length})}}class pr extends he{code="CONFIG_LOAD_ERROR";constructor(i,a,c){super(`Failed to load configuration from "${i}": ${a.message}`,{configPath:i,configName:c,originalError:a.name,originalMessage:a.message});this.cause=a}}class Gs extends he{code="CONFIG_VALIDATION_ERROR";constructor(i,a,c){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:c,validationErrors:a,errorCount:a.length})}}class Ys extends he{code="CONFIG_MERGE_ERROR";constructor(i,a,c,l){super(`Failed to merge configuration from "${i}" with "${a}": ${c.message}`,{sourcePath:i,targetPath:a,configName:l,originalError:c.name,originalMessage:c.message});this.cause=c}}class vn extends he{code="ENV_VAR_ERROR";constructor(i,a,c,l){super(`Failed to parse environment variable "${i}" with value "${a}" as ${c}`,{envKey:i,envValue:a,expectedType:c,configName:l})}}class Js extends he{code="FILE_SYSTEM_ERROR";constructor(i,a,c){super(`File system ${i} failed for "${a}": ${c.message}`,{operation:i,path:a,originalError:c.name,originalMessage:c.message});this.cause=c}}class Zs extends he{code="TYPE_GENERATION_ERROR";constructor(i,a,c){super(`Failed to generate types from "${i}" to "${a}": ${c.message}`,{configDir:i,outputPath:a,originalError:c.name,originalMessage:c.message});this.cause=c}}class wr extends he{code="SCHEMA_VALIDATION_ERROR";constructor(i,a,c){super(`Schema validation failed${c?` for config "${c}"`:""}`,{schemaPath:i,configName:c,validationErrors:a,errorCount:a.length})}}class Xs extends he{code="BROWSER_CONFIG_ERROR";constructor(i,a,c,l){super(`Failed to fetch configuration from "${i}": ${a} ${c}`,{endpoint:i,status:a,statusText:c,configName:l})}}class ei extends he{code="PLUGIN_ERROR";constructor(i,a,c){super(`Plugin "${i}" failed during ${a}: ${c.message}`,{pluginName:i,operation:a,originalError:c.name,originalMessage:c.message});this.cause=c}}var Fe={configNotFound(i,a,c){return new Qs(i,a,c)},configLoad(i,a,c){return new pr(i,a,c)},configValidation(i,a,c){return new Gs(i,a,c)},configMerge(i,a,c,l){return new Ys(i,a,c,l)},envVar(i,a,c,l){return new vn(i,a,c,l)},fileSystem(i,a,c){return new Js(i,a,c)},typeGeneration(i,a,c){return new Zs(i,a,c)},schemaValidation(i,a,c){return new wr(i,a,c)},browserConfig(i,a,c,l){return new Xs(i,a,c,l)},plugin(i,a,c){return new ei(i,a,c)}};async function Fa(i,a={}){let{maxRetries:c=3,retryDelay:l=1000,isRetryable:u=()=>!0,fallback:f}=a,d=Error("Unknown error occurred");for(let h=0;h<=c;h++)try{return await i()}catch(g){if(d=g instanceof Error?g:Error(String(g)),h===c||!u(d))break;if(l>0)await new Promise((m)=>setTimeout(m,l))}if(f!==void 0)return f;throw d instanceof Error?d:Error(`Unknown error: ${String(d)}`)}class kn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,a)=>a==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let a=i.toLowerCase();return["true","1","yes"].includes(a)}},{name:"number",canParse:(i,a)=>a==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let a=Number(i);if(Number.isNaN(a))throw TypeError(`Cannot parse "${i}" as number`);return a}},{name:"array",canParse:(i,a)=>a==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let a=JSON.parse(i);if(Array.isArray(a))return a}catch{}return i.split(",").map((a)=>a.trim())}},{name:"json",canParse:(i,a)=>a==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(a){throw Error(`Cannot parse "${i}" as JSON: ${a}`)}}}]}async applyEnvironmentVariables(i,a,c={}){let{prefix:l,useCamelCase:u=!0,useBackwardCompatibility:f=!0,customParsers:d={},verbose:h=!1,trackPerformance:g=!0}=c,m=async()=>{if(!i)return{config:a,source:{type:"environment",priority:50,timestamp:new Date}};let b=l||this.generateEnvPrefix(i),T={...a};return this.processObject(T,[],b,{useCamelCase:u,useBackwardCompatibility:f,customParsers:d,verbose:h,configName:i}),{config:T,source:{type:"environment",priority:50,timestamp:new Date}}};if(g)return ln.track("applyEnvironmentVariables",m,{configName:i});return m()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,a){if(!a)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,a,c,l){for(let[u,f]of Object.entries(i)){let d=[...a,u],h=d.map((b)=>this.formatEnvKey(b,l.useCamelCase)),g=`${c}_${h.join("_")}`,m=l.useBackwardCompatibility?`${c}_${d.map((b)=>b.toUpperCase()).join("_")}`:null;if(l.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,d,c,l);else{let b=Zt.env[g]||(m?Zt.env[m]:void 0);if(b!==void 0){if(l.verbose){let T=Zt.env[g]?g:m}try{i[u]=this.parseEnvironmentValue(b,typeof f,g,l.customParsers,l.configName)}catch(T){if(T instanceof vn)throw T;throw Fe.envVar(g,b,typeof f,l.configName)}}}}}parseEnvironmentValue(i,a,c,l,u){for(let[f,d]of Object.entries(l))try{return d(i)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(i,a))try{return f.parse(i)}catch{throw Fe.envVar(c,i,`${a} (via ${f.name} parser)`,u)}return i}getEnvironmentVariables(i){let a={},c=i.toUpperCase();for(let[l,u]of Object.entries(Zt.env))if(l.startsWith(c)&&u!==void 0)a[l]=u;return a}validateEnvironmentVariable(i,a,c){let l=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))l.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(c)try{this.parseEnvironmentValue(i,a,c,{})}catch(u){l.push(`Cannot parse value "${a}" as ${c}: ${u}`)}return{isValid:l.length===0,errors:l}}generateEnvVarDocs(i,a,c={}){let{prefix:l,format:u="text"}=c,f=l||this.generateEnvPrefix(i),d=[];switch(this.extractEnvVarInfo(a,[],f,d),u){case"markdown":return this.formatAsMarkdown(d,i);case"json":return JSON.stringify(d,null,2);default:return this.formatAsText(d,i)}}extractEnvVarInfo(i,a,c,l){for(let[u,f]of Object.entries(i)){let d=[...a,u],h=`${c}_${d.map((g)=>this.formatEnvKey(g,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,d,c,l);else l.push({key:h,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${d.join(".")}`,example:this.generateExample(f)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,a){let c=`Environment Variables for ${a}:
50
+
51
+ `;for(let l of i)c+=`${l.key}
52
+ `,c+=` Type: ${l.type}
53
+ `,c+=` Description: ${l.description}
54
+ `,c+=` Example: ${l.example}
55
+
56
+ `;return c}formatAsMarkdown(i,a){let c=`# Environment Variables for ${a}
57
+
58
+ `;c+=`| Variable | Type | Description | Example |
59
+ `,c+=`|----------|------|-------------|----------|
60
+ `;for(let l of i)c+=`| \`${l.key}\` | ${l.type} | ${l.description} | \`${l.example}\` |
61
+ `;return c}}function La(i,a,c={}){return ti(i,a,c,new WeakMap)}function ti(i,a,c,l){let{arrayMergeMode:u="replace",skipNullish:f=!1,customMerger:d}=c;if(a===null||a===void 0)return f?i:a;if(d){let h=d(i,a);if(h!==void 0)return h}if(Array.isArray(a)||Array.isArray(i))return ri(i,a,u,l);if(!ue(a)||!ue(i))return a;return Wa(i,a,c,l)}function ri(i,a,c,l){if(Array.isArray(a)&&!Array.isArray(i))return a;if(Array.isArray(i)&&!Array.isArray(a))return a;if(Array.isArray(a)&&Array.isArray(i))switch(c){case"replace":return a;case"concat":return Ba(i,a);case"smart":return Ia(i,a,l);default:return a}return a}function Ba(i,a){let c=[...a];for(let l of i)if(!c.some((u)=>cn(u,l)))c.push(l);return c}function Ia(i,a,c){if(a.length===0)return i;if(i.length===0)return a;if(ue(a[0])&&ue(i[0]))return ja(i,a,c);if(a.every((l)=>typeof l==="string")&&i.every((l)=>typeof l==="string")){let l=[...a];for(let u of i)if(!l.includes(u))l.push(u);return l}return a}function ja(i,a,c){let l=[...a];for(let u of i){if(!ue(u)){l.push(u);continue}let f=["id","name","key","path","type"],d=!1;for(let h of f)if(h in u){if(l.find((m)=>ue(m)&&(h in m)&&m[h]===u[h])){d=!0;break}}if(!d)l.push(u)}return l}function Wa(i,a,c,l){let u=a;if(ue(u)&&l.has(u))return l.get(u);let f={...i};if(ue(u))l.set(u,f);for(let d in u){if(!Object.prototype.hasOwnProperty.call(u,d))continue;let h=u[d],g=f[d];if(c.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){f[d]=h;continue}if(ue(h)&&ue(g))f[d]=ti(g,h,c,l);else if(Array.isArray(h)||Array.isArray(g))f[d]=ri(g,h,c.arrayMergeMode||"smart",l);else f[d]=h}return f}function ni(i,a,c="replace"){return La(i,a,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function cn(i,a){if(i===a)return!0;if(Array.isArray(i)&&Array.isArray(a)){if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(!cn(i[c],a[c]))return!1;return!0}if(ue(i)&&ue(a)){let c=Object.keys(i),l=Object.keys(a);if(c.length!==l.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(a,u))return!1;if(!cn(i[u],a[u]))return!1}return!0}return!1}function ue(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class si{extensions=xs;async loadFromPath(i,a,c={}){let{arrayStrategy:l="replace",useCache:u=!0,cacheTtl:f,trackPerformance:d=!0,verbose:h=!1}=c;if(u){let m=ir.getWithFileCheck("file",i);if(m){if(h)console.log(`Configuration loaded from cache: ${i}`);return m}}let g=async()=>{if(!Xt(i))return null;try{let m=`?t=${Date.now()}`,b=await import(i+m),T=b.default||b,v="default"in b,D=Object.keys(b).length>0;if(!v&&!D)throw new pr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof T!=="object"||T===null||Array.isArray(T))throw new pr(i,Error("Configuration must export a valid object"),"unknown");let E={config:ni(a,T,l),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)ir.setWithFileCheck("file",E,i,f);return E}catch(m){throw m instanceof Error?Fe.configLoad(i,m):Fe.configLoad(i,Error(String(m)))}};if(d)return ln.track("loadFromPath",g,{path:i});return g()}async tryLoadFromPaths(i,a,c={}){for(let l of i)try{let u=await this.loadFromPath(l,a,c);if(u)return u}catch(u){if(u instanceof Error&&u.name==="ConfigLoadError")throw u;if(c.verbose)console.warn(`Failed to load config from ${l}:`,u)}return null}generateConfigPaths(i,a,c){return Pi({name:i,directory:a,alias:c})}generateNamePatterns(i,a){return Es({name:i,alias:a})}checkFileAccess(i){return Fa(async()=>Xt(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,a,c){let l=[];if(!Xt(i))return l;if(a||c){let u=this.generateNamePatterns(a||"",c);for(let f of u)for(let d of this.extensions){let h=Ds(i,`${f}${d}`);if(await this.checkFileAccess(h))l.push(h)}}else try{let{readdirSync:u}=await import("fs"),f=u(i);for(let d of f)if(this.looksLikeConfigFile(d)){let h=Ds(i,d);if(await this.checkFileAccess(h))l.push(h)}}catch{return[]}return l}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((c)=>c.test(i))}async validateConfigFile(i){let a=[];try{if(!Xt(i))return a.push("Configuration file does not exist"),a;let c=await import(i),l=c.default||c;if(l===void 0)a.push("Configuration file must export a default value or named exports");else if(typeof l!=="object"||l===null)a.push("Configuration must be an object");else if(Array.isArray(l))a.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),f=u(i,"utf8");JSON.parse(f)}catch(u){a.push(`Invalid JSON syntax: ${u}`)}}catch(c){a.push(`Failed to load configuration file: ${c}`)}return a}async getFileModificationTime(i){try{let{statSync:a}=await import("fs");return a(i).mtime}catch{return null}}async preloadConfigurations(i,a={}){let c=new Map;return await Promise.allSettled(i.map(async(l)=>{try{let u=await this.loadFromPath(l,{},a);if(u)c.set(l,u.config)}catch(u){if(a.verbose)console.warn(`Failed to preload ${l}:`,u)}})),c}}var Ua=/^https?:\/\//;class ii{async validateConfiguration(i,a,c={}){let{stopOnFirstError:l=!1,validateRequired:u=!0,validateTypes:f=!0,customRules:d=[],trackPerformance:h=!0,verbose:g=!1}=c,m=async()=>{let b=[],T=[],v={stopOnFirstError:l,validateRequired:u,validateTypes:f,customRules:d,trackPerformance:h,verbose:g};try{if(typeof a==="string")return await this.validateWithSchemaFile(i,a,v);else if(Array.isArray(a))return this.validateWithRules(i,[...a,...d],v);else return this.validateWithJSONSchema(i,a,v)}catch(D){return b.push({path:"",message:`Validation failed: ${D}`,rule:"system"}),{isValid:!1,errors:b,warnings:T}}};if(h)return await ln.track("validateConfiguration",m);return m()}async validateWithSchemaFile(i,a,c){try{if(!Va(a))throw new wr(a,[{path:"",message:"Schema file does not exist"}]);let l=await import(a),u=l.default||l;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(l){throw new wr(a,[{path:"",message:`Failed to load schema: ${l}`}])}}validateWithJSONSchema(i,a,c){let l=[],u=[];return this.validateObjectAgainstSchema(i,a,"",l,u,c),{isValid:l.length===0,errors:l,warnings:u}}validateObjectAgainstSchema(i,a,c,l,u,f){if(f.validateTypes&&a.type){let d=Array.isArray(i)?"array":typeof i,h=Array.isArray(a.type)?a.type:[a.type];if(!h.includes(d)){if(l.push({path:c,message:`Expected type ${h.join(" or ")}, got ${d}`,expected:h.join(" or "),actual:d,rule:"type"}),f.stopOnFirstError)return}}if(a.enum&&!a.enum.includes(i)){if(l.push({path:c,message:`Value must be one of: ${a.enum.join(", ")}`,expected:a.enum.join(", "),actual:i,rule:"enum"}),f.stopOnFirstError)return}if(typeof i==="string"){if(a.minLength!==void 0&&i.length<a.minLength)l.push({path:c,message:`String length must be at least ${a.minLength}`,expected:`>= ${a.minLength}`,actual:i.length,rule:"minLength"});if(a.maxLength!==void 0&&i.length>a.maxLength)l.push({path:c,message:`String length must not exceed ${a.maxLength}`,expected:`<= ${a.maxLength}`,actual:i.length,rule:"maxLength"});if(a.pattern){if(!new RegExp(a.pattern).test(i))l.push({path:c,message:`String does not match pattern ${a.pattern}`,expected:a.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(a.minimum!==void 0&&i<a.minimum)l.push({path:c,message:`Value must be at least ${a.minimum}`,expected:`>= ${a.minimum}`,actual:i,rule:"minimum"});if(a.maximum!==void 0&&i>a.maximum)l.push({path:c,message:`Value must not exceed ${a.maximum}`,expected:`<= ${a.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&a.items)for(let d=0;d<i.length;d++){let h=c?`${c}[${d}]`:`[${d}]`;if(this.validateObjectAgainstSchema(i[d],a.items,h,l,u,f),f.stopOnFirstError&&l.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let d=i;if(f.validateRequired&&a.required){for(let h of a.required)if(!(h in d)){if(l.push({path:c?`${c}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(a.properties){for(let[h,g]of Object.entries(a.properties))if(h in d){let m=c?`${c}.${h}`:h;if(this.validateObjectAgainstSchema(d[h],g,m,l,u,f),f.stopOnFirstError&&l.length>0)return}}if(a.additionalProperties===!1){let h=new Set(Object.keys(a.properties||{}));for(let g of Object.keys(d))if(!h.has(g))u.push({path:c?`${c}.${g}`:g,message:`Additional property '${g}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,a,c){let l=[],u=[];for(let f of a)try{let d=this.getValueByPath(i,f.path),h=this.validateWithRule(d,f,f.path);if(l.push(...h),c.stopOnFirstError&&l.length>0)break}catch(d){l.push({path:f.path,message:`Rule validation failed: ${d}`,rule:"system"})}return{isValid:l.length===0,errors:l,warnings:u}}validateWithRule(i,a,c){let l=[];if(a.required&&(i===void 0||i===null))return l.push({path:c,message:a.message||`Property '${c}' is required`,expected:"required",rule:"required"}),l;if(i===void 0||i===null)return l;if(a.type){let u=Array.isArray(i)?"array":typeof i;if(u!==a.type)l.push({path:c,message:a.message||`Expected type ${a.type}, got ${u}`,expected:a.type,actual:u,rule:"type"})}if(a.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<a.min)l.push({path:c,message:a.message||`Value must be at least ${a.min}`,expected:`>= ${a.min}`,actual:u,rule:"min"})}if(a.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>a.max)l.push({path:c,message:a.message||`Value must not exceed ${a.max}`,expected:`<= ${a.max}`,actual:u,rule:"max"})}if(a.pattern&&typeof i==="string"){if(!a.pattern.test(i))l.push({path:c,message:a.message||`Value does not match pattern ${a.pattern}`,expected:a.pattern.toString(),actual:i,rule:"pattern"})}if(a.enum&&!a.enum.includes(i))l.push({path:c,message:a.message||`Value must be one of: ${a.enum.join(", ")}`,expected:a.enum.join(", "),actual:i,rule:"enum"});if(a.validator){let u=a.validator(i);if(u)l.push({path:c,message:a.message||u,rule:"custom"})}return l}getValueByPath(i,a){if(!a)return i;let c=a.split("."),l=i;for(let u of c)if(l&&typeof l==="object"&&u in l)l=l[u];else return;return l}generateRulesFromInterface(i){let a=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let l of c){let[,u,f,d]=l;a.push({path:u,required:!f,type:this.mapTypeScriptType(d)})}return a}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Ua},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var fe=new Dr("bunfig",{showTags:!0});function qa(i){if(!i)return"";let a=Array.isArray(i)?i.filter(Boolean):[i];if(a.length===0)return"";if(a.length===1)return` or alias "${a[0]}"`;return` or aliases ${a.map((c)=>`"${c}"`).join(", ")}`}class oi{fileLoader=new si;envProcessor=new kn;validator=new ii;async loadConfig(i){let a=Date.now(),{cache:c,performance:l,schema:u,validate:f,...d}=i;try{if(c?.enabled){let g=this.checkCache(d.name||"",d);if(g)return g}let h;try{h=await this.loadConfigurationStrategies(d,!0,c)}catch(g){if(d.configFile)throw g;let m=d.__strictErrorHandling;if(g instanceof Error&&g.name==="ConfigNotFoundError"){if(m)throw g;h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`No configuration file found for "${d.name||"config"}", using defaults with environment variables`]}}else if(g instanceof Error&&g.name==="ConfigLoadError"){let b=g.message.includes("EACCES")||g.message.includes("EPERM")||g.message.includes("permission denied"),T=!b&&(g.message.includes("syntax")||g.message.includes("Expected")||g.message.includes("Unexpected")||g.message.includes("BuildMessage")||g.message.includes("errors building")),v=g.message.includes("Configuration must export a valid object")||g.message.includes("Configuration file is empty and exports nothing");if(m&&(v||b))throw g;if(T&&(!m||!v))h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!m)h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`Configuration loading error, using defaults: ${g.message}`]};else throw g}else h={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${g instanceof Error?g.message:String(g)}`]}}if(u||f)await this.validateConfiguration(h.config,u,f,d.name);if(c?.enabled&&h)this.cacheResult(d.name||"",h,c,d);if(l?.enabled){let g={operation:"loadConfig",duration:Date.now()-a,configName:d.name,timestamp:new Date};if(l.onMetrics)l.onMetrics(g);if(l.slowThreshold&&g.duration>l.slowThreshold)fe.warn(`Slow configuration loading detected: ${g.duration}ms for ${d.name}`);h.metrics=g}return h}catch(h){if(h instanceof Error&&h.name==="ConfigNotFoundError")throw h;let g=Date.now()-a;throw fe.error(`Configuration loading failed after ${g}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(i,a=!1,c){let{name:l="",alias:u,configFile:f,cwd:d,configDir:h,defaultConfig:g,checkEnv:m=!0,arrayStrategy:b="replace",verbose:T=!1}=i,v=d||br.cwd(),D=[];if(f){let C=me(v,f);D.push(C);let N=m?ut(l,g,T):g,V=await this.fileLoader.tryLoadFromPaths([C],N,{arrayStrategy:b,verbose:T,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(!V)throw Fe.configNotFound(l||f,D,u);if(T)fe.success(`Configuration loaded from explicit path: ${C}`);return this.finalizeResult(V,D,m,l,T)}let R=await this.loadLocalConfiguration(l,u,v,h,g,b,T,m,c);if(R)return D.push(...this.getLocalSearchPaths(l,u,v,h)),this.finalizeResult(R,D,m,l,T);let k=await this.loadHomeConfiguration(l,u,g,b,T,m);if(k)return D.push(...this.getHomeSearchPaths(l,u)),this.finalizeResult(k,D,m,l,T);let E=await this.loadPackageJsonConfiguration(l,u,v,g,b,T,m);if(E)return D.push(me(v,"package.json")),this.finalizeResult(E,D,m,l,T);if(D.push(...this.getAllSearchPaths(l,u,v,h)),a)throw Fe.configNotFound(l,D,u);return{...await this.applyEnvironmentVariables(l,g,m,T),warnings:[`No configuration file found for "${l}"${qa(u)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,a,c,l,u,f,d,h,g){let m=h?ut(i,u,d):u,b=this.getLocalDirectories(c,l);for(let T of b){if(d)fe.info(`Searching for configuration in: ${T}`);let v=this.fileLoader.generateConfigPaths(i,T,a),D=await this.fileLoader.tryLoadFromPaths(v,m,{arrayStrategy:f,verbose:d,cacheTtl:g?.ttl,useCache:!g?.ttl||g.ttl>100});if(D){if(d)fe.success(`Configuration loaded from: ${D.source.path}`);return D}}return null}async loadHomeConfiguration(i,a,c,l,u,f){if(!i)return null;let d=f?ut(i,c,u):c,h=[me(Ve(),".config",i),me(Ve(),".config"),Ve()];for(let g of h){if(u)fe.info(`Checking home directory: ${g}`);let m=this.fileLoader.generateConfigPaths(i,g,a),b=await this.fileLoader.tryLoadFromPaths(m,d,{arrayStrategy:l,verbose:u});if(b){if(u)fe.success(`Configuration loaded from home directory: ${b.source.path}`);return b}}return null}async loadPackageJsonConfiguration(i,a,c,l,u,f,d){let h=d?ut(i,l,f):l;try{let g=me(c,"package.json");if(!Fi(g))return null;let m={};try{m=JSON.parse(Li(g,"utf8"))}catch(v){if(f)fe.warn("Failed to parse package.json:",[v instanceof Error?v:Error(String(v))]);return null}let b=m[i],T=i;if(!b&&a){let v=Array.isArray(a)?a:[a];for(let D of v){if(!D)continue;if(m[D]){b=m[D],T=D;break}}}if(b&&typeof b==="object"&&!Array.isArray(b)){if(f)fe.success(`Configuration loaded from package.json: ${T}`);return{config:ni(h,b,u),source:{type:"package.json",path:g,priority:30,timestamp:new Date}}}}catch(g){if(f)fe.warn("Failed to load package.json:",[g instanceof Error?g:Error(String(g))])}return null}async applyEnvironmentVariables(i,a,c,l){if(!c||!i||typeof a!=="object"||a===null||Array.isArray(a))return{config:a,source:{type:"default",priority:10,timestamp:new Date}};return{config:ut(i,a,l),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,a,c,l,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,a,c,l){let u=[];if(c){let f=c(i);if(f)u.push(...f)}if(a){let f=await this.validator.validateConfiguration(i,a);if(!f.isValid)u.push(...f.errors.map((d)=>d.path?`${d.path}: ${d.message}`:d.message))}if(u.length>0)throw Fe.configValidation(l||"unknown",u,l)}checkCache(i,a){let c=this.generateCacheKey(i,a);return ir.get(c)||null}cacheResult(i,a,c,l){let u=this.generateCacheKey(i,l);ir.set(u,a,void 0,c.ttl)}generateCacheKey(i,a){let c=[i];if(a.alias){let l=Array.isArray(a.alias)?a.alias.join(","):a.alias;c.push(`alias:${l}`)}if(a.cwd)c.push(`cwd:${a.cwd}`);if(a.configFile)c.push(`configFile:${a.configFile}`);if(a.configDir)c.push(`configDir:${a.configDir}`);if("checkEnv"in a)c.push(`checkEnv:${a.checkEnv}`);return c.join("|")}getLocalDirectories(i,a){return Ki({cwd:i,configDir:a})}getAllSearchPaths(i,a,c,l){let u=[];return u.push(...this.getLocalSearchPaths(i,a,c,l)),u.push(...this.getHomeSearchPaths(i,a)),u.push(me(c,"package.json")),u}getLocalSearchPaths(i,a,c,l){let u=this.getLocalDirectories(c,l),f=[];for(let d of u)f.push(...this.fileLoader.generateConfigPaths(i,d,a));return f}getHomeSearchPaths(i,a){if(!i)return[];let c=[me(Ve(),".config",i),me(Ve(),".config"),Ve()],l=[];for(let u of c)l.push(...this.fileLoader.generateConfigPaths(i,u,a));return l}async loadConfigWithResult(i){return this.loadConfig(i)}}var Gr=new oi;async function ai(i){let a="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let l;if(c)l=await Gr.loadConfig(i);else l=await Gr.loadConfig({...i,defaultConfig:a,cache:{enabled:!0},performance:{enabled:!1}});return l?.config??a}catch(l){if(i.configFile)throw l;let u=l instanceof Error?l.name:"UnknownError",f=l instanceof Error?l.message:String(l);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||f.includes("config"))&&i.verbose)fe.warn("Unexpected error loading config, using defaults:",[l instanceof Error?l:Error(String(l))]);let h=c?{...i,defaultConfig:a}:{...i,defaultConfig:a,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await Gr.applyEnvironmentVariables(h.name||"",a,!0,h.verbose||!1))?.config??a;return a}}function ut(i,a,c=!1){let l=new kn,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(d,h=[]){let g={...d};for(let[m,b]of Object.entries(d)){let T=[...h,m],v=[`${u}_${T.join("_").toUpperCase()}`,`${u}_${T.map((k)=>k.toUpperCase()).join("")}`,`${u}_${T.map((k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],D,R;for(let k of v)if(D=br.env[k],D!==void 0){R=k;break}if(D!==void 0&&R)if(typeof b==="boolean")g[m]=["true","1","yes"].includes(D.toLowerCase());else if(typeof b==="number"){let k=Number(D);if(!Number.isNaN(k))g[m]=k}else if(Array.isArray(b))try{g[m]=JSON.parse(D)}catch{g[m]=D.split(",").map((k)=>k.trim())}else g[m]=D;else if(b&&typeof b==="object"&&!Array.isArray(b))g[m]=f(b,T)}return g}return f(a)}var ru=me(br.cwd(),"config"),nu=me(br.cwd(),"src/generated");function r(i=e.dialect){return i==="mysql"||i==="singlestore"||i==="vitess"}var bt={verbose:!0,snapshotDir:".qb",migrationDir:"database/migrations",dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},vitess:{sharded:!0},timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},pagination:{defaultPerPage:25,cursorColumn:"id"},aliasing:{relationColumnAliasFormat:"table_column"},relations:{foreignKeyFormat:"singularParent_id",maxDepth:10,maxEagerLoad:50,detectCycles:!0},transactionDefaults:{retries:2,isolation:"read committed",sqlStates:["40001","40P01"],backoff:{baseMs:50,factor:2,maxMs:2000,jitter:!0}},sql:{randomFunction:"RANDOM()",sharedLockSyntax:"FOR SHARE",jsonContainsMode:"operator"},features:{distinctOn:!0},debug:{captureText:!0},hooks:{},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0}},fi=new Set(["__proto__","constructor","prototype"]);function li(i){if(i===null||typeof i!=="object"||Array.isArray(i))return!1;let a=Object.getPrototypeOf(i);return a===Object.prototype||a===null}function xn(i,a,c=new Set){let l={...i};c.add(a);for(let u of Object.keys(a)){if(fi.has(u))continue;let f=a[u];if(li(f)&&!c.has(f)){let d=l[u];l[u]=xn(li(d)?d:{},f,c)}else l[u]=f}return c.delete(a),l}var za=Symbol.for("bun-query-builder.config"),e=globalThis[za]??=xn({},bt),Ha=Symbol.for("bun-query-builder.config-state"),$r=globalThis[Ha]??={explicit:new Set,fileLoaded:!1};function H(i){if(i)return i;let a=ci.env.DB_DIALECT||ci.env.DB_CONNECTION;if(a)return a;return e.dialect||"postgres"}function t(i){if(e.dialect==="postgres")return`$${i}`;return"?"}function s(i,a=1){if(i<=0)return"";if(e.dialect==="postgres"){let c=`$${a}`;for(let l=1;l<i;l++)c+=`, $${a+l}`;return c}return i===1?"?":`?${", ?".repeat(i-1)}`}async function Q(){if(!$r.fileLoaded){$r.fileLoaded=!0;let i=await ai({name:"query-builder",alias:"qb",defaultConfig:bt}),a={};for(let[c,l]of Object.entries(i??{}))if(!$r.explicit.has(c))a[c]=l;di(a)}return e}var pt=null,ui=new Set;function di(i){let a=xn(e,i),c=e;for(let l of Object.keys(a)){if(fi.has(l))continue;c[l]=a[l]}}function qe(i){if(i.dialect&&pt&&i.dialect!==pt){let a=`${pt}->${i.dialect}`;if(!ui.has(a))ui.add(a),console.warn(`[query-builder] Configuring dialect '${i.dialect}' overrides the previously configured dialect '${pt}'. Config is process-wide (setConfig, db.configure and query-builder.config.ts all write it); in-flight queries from the previous configuration may break. `+"Run conflicting connections in separate processes \u2014 see stacksjs/stacks#1862 #18.")}if(i.dialect)pt=i.dialect;for(let a of Object.keys(i))$r.explicit.add(a);di(i)}function yn(i){return i}var{SQL:hi}=globalThis.Bun;import{Database as Ga}from"bun:sqlite";import{mkdirSync as Ya}from"fs";import{dirname as Ja}from"path";import Ct from"process";var It=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"];function Lt(){let i=e.sqlite?.pragmas;return Array.isArray(i)?i:It}function G(i){for(let a of Lt())try{i.run(a)}catch{}}function kt(i){return i}function Qa(i){return i!==null&&typeof i==="object"?i:null}function gi(i,a){if(a.length===0||!/\$\d/.test(i))return{sql:i,params:a};let c=[],l="",u=0;for(let f=0;f<i.length;f++){let d=i[f];if(d==="'"||d==='"'||d==="`"){let h=Za(i,f,d);l+=i.slice(f,h),f=h-1;continue}if(d==="-"&&i[f+1]==="-"){let h=i.indexOf(`
62
+ `,f),g=h===-1?i.length:h;l+=i.slice(f,g),f=g-1;continue}if(d==="/"&&i[f+1]==="*"){let h=i.indexOf("*/",f+2),g=h===-1?i.length:h+2;l+=i.slice(f,g),f=g-1;continue}if(d==="$"){let h=/^\d+/.exec(i.slice(f+1))?.[0];if(h){let g=Number(h);if(u=Math.max(u,g),g>=1&&g<=a.length){c.push(a[g-1]),l+="?",f+=h.length;continue}}}l+=d}if(u>a.length)throw Error(`SQL references $${u} but only ${a.length} value${a.length===1?" was":"s were"} provided`);if(c.length===0)return{sql:i,params:a};return{sql:l,params:c}}function Za(i,a,c){for(let l=a+1;l<i.length;l++){if(i[l]!==c)continue;if(i[l+1]===c){l++;continue}return l+1}return i.length}class wi{db;constructor(i){if(i!==":memory:"&&!i.startsWith(":")){let a=Ja(i);if(a&&a!==".")Ya(a,{recursive:!0})}this.db=new Ga(i),G(this.db)}query(i,a=[]){let c=gi(i,a);return this.db.prepare(c.sql).all(...c.params)}run(i,a=[]){let c=gi(i,a);return this.db.prepare(c.sql).run(...c.params)}close(){this.db.close()}get database(){return this.db}}function mi(i){return{__raw:!0,value:i,toString:()=>i}}function yi(i){let a=i.trimStart();for(;;)if(a.startsWith("--")){let c=a.indexOf(`
63
+ `);a=c===-1?"":a.slice(c+1).trimStart()}else if(a.startsWith("/*")){let c=a.indexOf("*/");a=c===-1?"":a.slice(c+2).trimStart()}else return a}function Xa(i){let a=[],c="",l=!1,u=!1,f=!1,d=!1;for(let g=0;g<i.length;g++){let m=i[g],b=i[g+1];if(!l&&!u&&!d&&m==="-"&&b==="-"){f=!0,c+=m;continue}if(f&&(m===`
64
+ `||m==="\r")){f=!1,c+=m;continue}if(!l&&!u&&!f&&m==="/"&&b==="*"){d=!0,c+=m;continue}if(d&&m==="*"&&b==="/"){d=!1,c+=m+b,g++;continue}if(f||d){c+=m;continue}if(m==="'"&&!u){if(l&&b==="'"){c+=m+b,g++;continue}l=!l,c+=m;continue}if(m==='"'&&!l){u=!u,c+=m;continue}if(m===";"&&!l&&!u){let T=yi(c.trim());if(T)a.push(T);c="";continue}c+=m}let h=yi(c.trim());if(h)a.push(h);return a}function pi(i){let a=new wi(i);function c(f,...d){let h=f[0],g=[];for(let m=0;m<d.length;m++){let b=d[m],T=Qa(b);if(T&&typeof T.sql==="string"&&Array.isArray(T.values))h+=T.sql+(f[m+1]||""),g.push(...T.values);else if(T&&(T.__raw||T.raw)){let v=T.raw,D=T.__raw?T.value:typeof v==="string"?v:v();h+=D+(f[m+1]||"")}else if(Array.isArray(b)){let v=b.map(()=>"?").join(", ");h+=v+(f[m+1]||""),g.push(...b)}else h+=`?${f[m+1]||""}`,g.push(b)}return{sql:h,values:g,execute:()=>{try{let m=h.trim().toUpperCase();if(m.startsWith("SELECT")||m.startsWith("PRAGMA")||/\bRETURNING\b/.test(m)){let b=a.query(h,kt(g));return Promise.resolve(b)}else{let b=a.run(h,kt(g));return Promise.resolve(b)}}catch(m){return Promise.reject(m)}},raw:()=>h,toString:()=>h,cancel:()=>{}}}function l(f,...d){if(Array.isArray(f)&&"raw"in f)return c(f,...d);if(typeof f==="string")return mi(f);return c([""])}l.raw=(f)=>mi(f),l.unsafe=(f,d=[])=>{let h=()=>{try{let g=f.trim().toUpperCase();if(g.startsWith("SELECT")||g.startsWith("PRAGMA")||/\bRETURNING\b/.test(g)){let m=a.query(f,kt(d));return Promise.resolve(m)}else{let m=a.run(f,kt(d));return Promise.resolve(m)}}catch(g){return Promise.reject(g)}};return{sql:f,values:d,execute:h,then:(g,m)=>h().then(g,m),raw:()=>f,toString:()=>f,cancel:()=>{}}},l.close=()=>(a.close(),Promise.resolve()),l.query=(f,d)=>{try{let h=a.query(f,kt(d||[]));return Promise.resolve(h)}catch(h){return Promise.reject(h)}},l.file=async(f,d)=>{try{let{readFileSync:h}=await import("fs"),g=h(f,"utf-8"),m=Xa(g);for(let b of m){let T=b.trim();if(!T||T.startsWith("--"))continue;let v=T.toUpperCase();if(v.startsWith("SELECT")||v.startsWith("PRAGMA"))a.query(b);else a.run(b)}return Promise.resolve([])}catch(h){return Promise.reject(h)}};let u=0;return l.begin=async(f,d)=>{let h=typeof f==="function"?f:d;if(typeof h!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let g=u>0,m=`qb_sp_${u}`;if(g)a.run(`SAVEPOINT ${m}`);else a.run("BEGIN");u++;try{let b=await h(l);if(u--,g)a.run(`RELEASE SAVEPOINT ${m}`);else a.run("COMMIT");return b}catch(b){u--;try{if(g)a.run(`ROLLBACK TO SAVEPOINT ${m}`),a.run(`RELEASE SAVEPOINT ${m}`);else a.run("ROLLBACK")}catch{}throw b}},l.savepoint=l.begin,l.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},l._wrapper=a,l}function ec(i){let a=i.replace(/^(?:sqlite|sqlite3|file):/i,"");if(a===i)return i;return(a.startsWith("///")?a.slice(2):a.startsWith("//")?a.slice(2):a)||":memory:"}function Ce(i=e.database){let a=Ct.env.DB_DATABASE||i?.database||"";return String(a).replace(/^['"]|['"]$/g,"")}function tc(i,a){if((i==="postgres"||i==="mysql"||i==="singlestore"||i==="vitess")&&Ct.env.DB_CONNECTION===i){let m=Ct.env,b=(m.DB_DATABASE||a.database||"").replace(/^['"]|['"]$/g,""),T=m.DB_USERNAME||a.username,v=m.DB_PASSWORD??a.password??"",D=m.DB_HOST||a.host||"localhost",R=m.DB_PORT||a.port,k=i==="postgres"?"postgres":"mysql",E=m.DB_SSL==="true"||m.DB_SSL==="1"||a.ssl?"?ssl=true":"";return`${k}://${T}:${v}@${D}${R?`:${R}`:""}/${b}${E}`}if(a.url)return i==="sqlite"?ec(a.url):a.url;let{database:c,username:l,password:u,host:f="localhost",port:d,ssl:h}=a,g=h||Ct.env.DB_SSL==="true"||Ct.env.DB_SSL==="1"?"?ssl=true":"";switch(i){case"postgres":return`postgres://${l}:${u}@${f}${d?`:${d}`:""}/${c}${g}`;case"mysql":case"singlestore":case"vitess":return`mysql://${l}:${u}@${f}${d?`:${d}`:""}/${c}${g}`;case"sqlite":if(c===":memory:")return":memory:";return c||":memory:";default:throw Error(`Unsupported dialect: ${i}`)}}function bi(i){if(!i)return{};let a={},c=(l)=>Math.max(0,Math.round(l/1000));if(typeof i.max==="number"&&Number.isFinite(i.max))a.max=i.max;if(typeof i.idleTimeoutMs==="number"&&Number.isFinite(i.idleTimeoutMs))a.idleTimeout=c(i.idleTimeoutMs);if(typeof i.acquireTimeoutMs==="number"&&Number.isFinite(i.acquireTimeoutMs))a.connectionTimeout=c(i.acquireTimeoutMs);if(typeof i.maxLifetimeMs==="number"&&Number.isFinite(i.maxLifetimeMs))a.maxLifetime=c(i.maxLifetimeMs);return a}function rc(){let i=e.dialect,a=tc(i,e.database);try{if(i==="sqlite")return pi(a);let c=bi(e.database.pool);return Object.keys(c).length>0?new hi(a,c):new hi(a)}catch(c){if(console.error(`[query-builder] Failed to create database connection for dialect '${i}': ${c.message}`),i==="sqlite")return pi(":memory:");throw c}}var nt=null,Cn=null;function nc(){let i=e.database;return JSON.stringify({dialect:e.dialect,database:i.database,username:i.username,password:i.password,host:i.host,port:i.port,url:i.url,pool:bi(i.pool)})}function w(i=!1){let a=nc();if(i||nt!==null&&Cn!==a||!nt)Ti(),nt=rc(),Cn=a;return nt}function Ti(){let i=nt;return nt=null,Cn=null,i}async function sc(i){if(!i||typeof i.close!=="function")return;await i.close()}function bn(){sc(Ti()).catch((a)=>{console.error(`[query-builder] Failed to close database connection: ${a.message}`)})}async function We(i){try{return await i(w())}catch(a){if(a?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||a?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let c=w(!0);return await i(c)}throw a}}function ic(){return new Proxy(function(){},{get(i,a){let c=w(),l=c[a];if(typeof l==="function")return l.bind(c);return l},apply(i,a,c){return w()(...c)}})}var n=ic();function st(i){if(typeof i==="number")return{length:i};return i}function Mn(i){if(typeof i==="number")return{max:i};return i}function oc(i){return typeof i==="function"}function ac(i){return i.replace(/[A-Z]/g,(a)=>a.toLowerCase())}function vi(i,a){if(!a||typeof a.fractionDigits!=="number")return i;return Number(i.toFixed(a.fractionDigits))}function Oe(i,a={}){if(!i)return a;return new Proxy(i,{get(c,l){if(l in a)return a[l];let u=c[l];if(u!==void 0)return u;let f=c[ac(l)];if(oc(f))return f.bind(c);return}})}function wt(i){let a=(b)=>{let T=Array.isArray(b)?b:[],v=Math.floor(Math.random()*T.length);return T[v]},c=()=>i.string,l=()=>i.number,u=()=>i.random,f=Oe(i.string,{alpha:(b)=>c()?.alpha?.(st(b)),alphanumeric:(b)=>c()?.alphanumeric?.(st(b)),numeric:(b)=>c()?.numeric?.(st(b)),sample:(b)=>c()?.sample?.(st(b)),hexadecimal:(b)=>c()?.hexadecimal?.(st(b))}),d=Oe(i.number,{int:(b)=>l()?.int?.(Mn(b)),float:(b)=>{let T=Mn(b);return vi(Number(l()?.float?.(T)??0),T)}}),h=Oe(i.helpers,{arrayElement:a,arrayElements:(b,T)=>{let v=[...Array.isArray(b)?b:[]],D=typeof T==="number"?T:Math.max(1,Math.floor(Math.random()*v.length));for(let R=v.length-1;R>0;R-=1){let k=Math.floor(Math.random()*(R+1));[v[R],v[k]]=[v[k],v[R]]}return v.slice(0,Math.min(D,v.length))},shuffle:(b)=>{let T=[...Array.isArray(b)?b:[]];for(let v=T.length-1;v>0;v-=1){let D=Math.floor(Math.random()*(v+1));[T[v],T[D]]=[T[D],T[v]]}return T},maybe:(b,T)=>{let v=typeof T?.probability==="number"?T.probability:0.5;return Math.random()<v?b():void 0},slugify:(b)=>String(b??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),m={string:f,number:d,helpers:h,datatype:{boolean:(b)=>{let T=typeof b==="number"?b:b?.probability;if(typeof T==="number")return Math.random()<T;return Boolean(u()?.boolean?.())},number:(b)=>Number(l()?.int?.(Mn(b))??0),float:(b)=>vi(Number(l()?.float?.(b)??0),b),uuid:()=>crypto.randomUUID(),string:(b)=>String(c()?.alphanumeric?.({length:b??10})??""),hexadecimal:(b)=>String(c()?.hexadecimal?.(st(b))??""),array:(b)=>Array.from({length:b??3},()=>c()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:c()?.alphanumeric?.({length:8})})},location:Oe(i.address),address:Oe(i.address),vehicle:Oe(i.vehicle,{vrm:()=>i.vehicle?.registration?.()}),company:Oe(i.company,{catchPhrase:()=>i.company?.catchphrase?.(),buzzPhrase:()=>i.company?.bs?.()??i.company?.buzzword?.()})};return new Proxy(i,{get(b,T){if(T in m)return m[T];let v=b[T];if(v&&typeof v==="object")return Oe(v);return v}})}function Me(i){if(typeof i==="string")return{model:i};if(i&&typeof i==="object"&&typeof i.model==="string"){let a=i;return{model:a.model,foreignKey:a.foreignKey,onDelete:a.onDelete}}return null}function M(i){if(!i)return[];return(Array.isArray(i)?i:typeof i==="object"?Object.values(i):[]).map(Me).filter((c)=>c!==null)}function Ue(i){let a=String(i).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(a.endsWith("y")&&!/[aeou]y$/.test(a))return`${a.slice(0,-1)}ies`;if(a.endsWith("s")||a.endsWith("x")||a.endsWith("ch")||a.endsWith("sh"))return`${a}es`;return`${a}s`}function p(i){return typeof i?.table==="string"&&i.table.length>0?i.table:Ue(String(i?.name??""))}function Kt(i){return i.endsWith("s")?i.slice(0,-1):i}function Ft(i){if(i.endsWith("ies")&&i.length>3){let a=i.slice(0,-3),c=a[a.length-1];if(c&&!"aeiou".includes(c))return`${a}y`}if(i.endsWith("es")&&i.length>2){let a=i.slice(0,-2);if(a.endsWith("s")||a.endsWith("x")||a.endsWith("ch")||a.endsWith("sh"))return a}if(i.endsWith("s")&&!i.endsWith("ss")&&!i.endsWith("us")&&!i.endsWith("is"))return i.slice(0,-1);return i}function y(i){if(i==="none")return(a)=>a;if(i==="inflect")return Ft;return Kt}var Tt="1 = 0";function x(i){if(i.length===0)return"";let a=[];for(let c of i)if(c.conn==="OR"&&a.length>0)a[a.length-1].push(c);else a.push([c]);return a.map((c,l)=>{let u=c.map((d)=>d.sql).join(" OR "),f=c.length>1&&a.length>1?`(${u})`:u;return l===0?f:`${c[0].conn} ${f}`}).join(" ")}function o(i,a,c,l){if(a.length===0)return c?"1 = 1":"1 = 0";return`${i} ${c?"NOT IN":"IN"} (${l})`}function Tn(i,a){if(a!=="postgres")return i;let c="",l=0,u=0;while(u<i.length){let f=i[u];if(f==="'"){let d=Di(i,u,"'");c+=i.slice(u,d),u=d;continue}if(f==='"'){let d=Di(i,u,'"');c+=i.slice(u,d),u=d;continue}if(f==="$"){let d=i.slice(u).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(d){let h=i.indexOf(d,u+d.length),g=h===-1?i.length:h+d.length;c+=i.slice(u,g),u=g;continue}}if(f==="?"){l++,c+=`$${l}`,u++;continue}c+=f,u++}return c}function Di(i,a,c){let l=a+1;while(l<i.length){if(i[l]===c){if(i[l+1]===c){l+=2;continue}return l+1}l++}return i.length}function Re(i,a,c=Number.POSITIVE_INFINITY){let l=[],u=0,f=(d)=>d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||d===95;for(let d=0;d<i.length;d++){let h=i.charCodeAt(d);if(h===45&&i.charCodeAt(d+1)===45){let m=i.indexOf(`
65
+ `,d+2);if(m===-1)return l;d=m;continue}if(h===47&&i.charCodeAt(d+1)===42){let m=1,b=d+2;while(b<i.length&&m>0)if(i[b]==="/"&&i[b+1]==="*")m++,b+=2;else if(i[b]==="*"&&i[b+1]==="/")m--,b+=2;else b++;d=b-1;continue}if(h===39||h===34||h===96){let m=d+1;while(m<i.length){if(i.charCodeAt(m)===h){if(i.charCodeAt(m+1)===h){m+=2;continue}break}m++}d=m;continue}if(h===36){let m=/^\$(?:[A-Z_][A-Z0-9_]*)?\$/i.exec(i.slice(d));if(m){let b=i.indexOf(m[0],d+m[0].length);d=b===-1?i.length:b+m[0].length-1;continue}}if(h===40){u++;continue}if(h===41){u=Math.max(0,u-1);continue}if(u!==0)continue;if(d===0)continue;let g=h&-33;if(g<65||g>90)continue;if(f(i.charCodeAt(d-1)))continue;for(let{key:m,pattern:b}of a){b.lastIndex=d;let T=b.exec(i);if(!T)continue;if(l.push({key:m,start:d,length:T[0].length}),l.length>=c)return l;d+=T[0].length-1;break}}return l}function Ie(){let i=new Date().toISOString();return r(e.dialect)?i.slice(0,19).replace("T"," "):i}var Si=/^[A-Z_][A-Z0-9_]*$/i;function ke(i,a){if(typeof i!=="string"||i.length===0)throw TypeError(`[bun-query-builder] ${a}: identifier must be a non-empty string, got ${typeof i}`);if(i.length>64)throw TypeError(`[bun-query-builder] ${a}: identifier '${i}' exceeds 64 chars`);if(!Si.test(i))throw TypeError(`[bun-query-builder] ${a}: identifier '${i}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Mi(i,a){if(typeof i!=="string"||i.length===0)throw TypeError(`[bun-query-builder] ${a}: identifier must be a non-empty string, got ${typeof i}`);let c=i.split(".");if(c.length>2||c.some((l)=>l.length===0||l.length>64||!Si.test(l)))throw TypeError(`[bun-query-builder] ${a}: invalid ORDER BY column '${i}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}var kr=null,On=new Map;function cc(i,a){On.set(i,a),ot.clear()}function St(){On.clear(),ot.clear()}function ce(i){if(!kr)try{kr=import.meta.require("./chunk-wyr48f41.js").getModel}catch{kr=()=>{return}}return kr(i)??On.get(i)}var xr=new Map,lc=500;function $i(i){let a=xr.get(i);if(a!==void 0)return a;let c=0,l=i.replace(/\?/g,()=>`$${++c}`);if(xr.size>=lc)xr.clear();return xr.set(i,l),l}function Dt(i){if(i==null)return 0;if(typeof i.affectedRows==="number")return i.affectedRows;if(typeof i.count==="number")return i.count;if(Array.isArray(i))return i.length;return 0}function $t(i){if(i==null||typeof i!=="object")return null;if("insertId"in i&&i.insertId!=null)return i.insertId;if("lastInsertRowid"in i&&i.lastInsertRowid!=null)return i.lastInsertRowid;return null}class _n{sqliteDb;dialect="sqlite";constructor(i){this.sqliteDb=i}all(i,a){return Promise.resolve(this.sqliteDb.query(i).all(...a))}get(i,a){return Promise.resolve(this.sqliteDb.query(i).get(...a)??void 0)}run(i,a){let c=this.sqliteDb.run(i,a);return Promise.resolve({changes:c.changes,lastInsertId:c.lastInsertRowid})}insert(i,a){return this.run(i,a)}}class Ai{dialect;constructor(i){this.dialect=i}conn(){return w()}text(i){return this.dialect==="postgres"?$i(i):i}async all(i,a){let c=await this.conn().unsafe(this.text(i),a);return Array.isArray(c)?c:[]}async get(i,a){let c=await this.conn().unsafe(this.text(i),a);if(Array.isArray(c))return c[0]??void 0;return c??void 0}async run(i,a){let c=await this.conn().unsafe(this.text(i),a);return{changes:Dt(c),lastInsertId:$t(c)}}async insert(i,a,c){if(this.dialect==="postgres"){let f=await this.conn().unsafe(`${$i(i)} RETURNING ${c}`,a),d=Array.isArray(f)?f[0]:f;return{changes:1,lastInsertId:d?d[c]??null:null}}let l=await this.conn().unsafe(i,a),u=$t(l);if(u==null){let f=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);u=(Array.isArray(f)?f[0]:f)?.id??null}return{changes:Dt(l)||1,lastInsertId:u}}}var xe=null,Mr=!1,ye=null,it=null,Er=null,Cr=null;function wn(i){if(i.database instanceof Nn)xe=i.database,Mr=!1;else xe=new Nn(i.database||":memory:",{create:!0}),Mr=!0,G(xe);ye=null,it=null}function Sn(){let i=Mr,a=xe;if(xe=null,Mr=!1,ye=null,it=null,Er=null,Cr=null,i&&a)try{a.close()}catch{}}function B(){if(xe){if(!ye||it!==xe)ye=new _n(xe),it=xe,Er="sqlite",Cr=null;return ye}let i=e.dialect,a=e.database?.database??null;if(ye&&it===null&&Er===i&&Cr===a)return ye;if(it=null,Er=i,Cr=a,i==="sqlite"){let c=new Nn(a||":memory:",{create:!0});G(c),ye=new _n(c)}else ye=new Ai(i);return ye}function Dn(){let i=B();if(i.sqliteDb)return i.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${i.dialect}'. Use the async model API instead.`)}var Pe="deleted_at",An="__btm_rel__";function at(i){let a=i.traits;return Boolean(a?.useSoftDeletes||a?.softDeletable)}function je(i){let a=i.traits;return Boolean(a?.useTimestamps||a?.timestampable)}var ki=new WeakMap;function uc(i){let a=ki.get(i);if(a)return a;let c=new Set,l=i.belongsToMany;if(l){if(Array.isArray(l)){for(let u of l)if(typeof u==="string")c.add(u.toLowerCase());else if(u&&typeof u==="object"&&u.model)c.add(u.model.toLowerCase())}else if(typeof l==="object")for(let u of Object.keys(l))c.add(u)}return ki.set(i,c),c}function Ri(i){let a={};for(let[c,l]of Object.entries(i))a[I(c)]=l;return a}function fc(i){for(let a in i)if(I(a)!==a)return Ri(i);return i}function dc(i,a){if(i[a])return i[a];let c=I(a);if(i[c])return i[c];for(let l of Object.keys(i))if(I(l)===c)return i[l];return}class oe{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_relations={};constructor(i,a={}){this._definition=i,this._attributes=fc({...a}),this._original=null;let c=uc(i);if(c.size===0)return;let l=this;return new Proxy(this,{get(u,f,d){if(typeof f==="string"&&c.has(f)&&!(f in u))return()=>{let h=Ni(i,f);if(!h||h.type!=="belongsToMany")throw Error(`[orm] relation '${f}' did not resolve to a belongsToMany on '${i.name}'`);let g=ce(h.relatedModelName),m=g?.getDefinition?.()||g?.definition;if(!m)throw Error(`[orm] related model '${h.relatedModelName}' is not registered`);return new Et(l,i,h,m)};return Reflect.get(u,f,d)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(i){let a=this._definition.get?.[i];if(a)try{let c=a(this._attributes);if(c!==void 0)return c}catch{}return this._attributes[I(i)]}getAttribute(i){return this._attributes[I(i)]}getAttributes(){return{...this._attributes}}set(i,a){if(this._original===null)this._original={...this._attributes};this._attributes[I(i)]=a}only(i){let a={};for(let c of i)a[c]=this._attributes[I(c)];return a}except(i){let a=new Set(i.map((l)=>I(l))),c={};for(let l of Object.keys(this._attributes))if(!a.has(l))c[l]=this._attributes[l];return c}getRelation(i){return this._relations[i]}setRelation(i,a){this._relations[i]=a}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let i=this._definition.primaryKey||"id";return this._attributes[i]}isDirty(i){if(this._original===null)return!1;if(i){let a=I(i);return this._attributes[a]!==this._original[a]}return Object.keys(this._attributes).some((a)=>this._attributes[a]!==this._original[a])}isClean(i){return!this.isDirty(i)}getOriginal(i){return this.getOriginalAttributes()[I(i)]}getChanges(){if(this._original===null)return{};let i={};for(let a of Object.keys(this._attributes))if(this._attributes[a]!==this._original[a])i[a]=this._attributes[a];return i}fill(i){let a=this._definition.attributes;for(let[c,l]of Object.entries(i)){let u=dc(a,c),f=!u&&I(c).endsWith("_id");if(u?.fillable&&!u?.guarded||f){if(this._original===null)this._original={...this._attributes};this._attributes[I(c)]=l}}return this}forceFill(i){if(this._original===null)this._original={...this._attributes};let a=Ri(i);Object.assign(this._attributes,a);for(let c of Object.keys(a))this._forced.add(c);return this}async save(){let i=B(),a=this._definition.primaryKey||"id",c=this._definition.hooks,l=this._definition.set||{};for(let[u,f]of Object.entries(l))if(this.isDirty(u))this._attributes[I(u)]=f(this._attributes);if(this._attributes[a]){await c?.beforeUpdate?.(this,this.getChanges());let u=this.getChanges(),f=Object.keys(u);if(f.length>0){let d=f.map((g)=>`${g} = ?`).join(", "),h=[...Object.values(u),this._attributes[a]];if(je(this._definition)){let g=Ie();await i.run(`UPDATE ${this._definition.table} SET ${d}, updated_at = ? WHERE ${a} = ?`,[...Object.values(u),g,this._attributes[a]])}else await i.run(`UPDATE ${this._definition.table} SET ${d} WHERE ${a} = ?`,h)}await c?.afterUpdate?.(this)}else{let u=this._definition.attributes,f={};for(let[m,b]of Object.entries(u)){if(b.guarded&&!this._forced.has(I(m)))continue;let T=I(m);if(this._attributes[T]!==void 0)f[T]=this._attributes[T]}for(let m of Object.keys(this._attributes))if(m.endsWith("_id")&&m!==a&&!(m in f))f[m]=this._attributes[m];if(je(this._definition)){let m=Ie(),b=this._attributes.created_at;f.created_at=b===void 0||b===null?m:b,f.updated_at=m}if(this._definition.traits?.useUuid&&!f.uuid)f.uuid=crypto.randomUUID();await c?.beforeCreate?.(f);let d=Object.keys(f),h=d.map(()=>"?").join(", "),g=await i.insert(`INSERT INTO ${this._definition.table} (${d.join(", ")}) VALUES (${h})`,Object.values(f),a);for(let[m,b]of Object.entries(f))this._attributes[m]=b;if(g.lastInsertId!=null)this._attributes[a]=g.lastInsertId;await c?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update(i){return this.fill(i),this.save()}async fresh(){let i=B(),a=this._definition.primaryKey||"id",c=this._attributes[a];if(c==null)return null;let l=await i.get(`SELECT * FROM ${this._definition.table} WHERE ${a} = ?`,[c]);if(!l)return null;return new oe(this._definition,l)}async delete(){let i=B(),a=this._definition.primaryKey||"id",c=this._attributes[a],l=this._definition.hooks;if(!c)throw Error("Cannot delete a model without a primary key");if(await l?.beforeDelete?.(this),at(this._definition)){let u=Ie();await i.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${a} = ?`,[u,c]),this._attributes[Pe]=u}else await i.run(`DELETE FROM ${this._definition.table} WHERE ${a} = ?`,[c]);return await l?.afterDelete?.(this),!0}async restore(){if(!at(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let i=this._definition.primaryKey||"id",a=this._attributes[i];if(!a)throw Error("Cannot restore a model without a primary key");return await B().run(`UPDATE ${this._definition.table} SET ${Pe} = ? WHERE ${i} = ?`,[null,a]),this._attributes[Pe]=null,this._original=null,this}trashed(){return this._attributes[Pe]!=null}async refresh(){let i=B(),a=this._definition.primaryKey||"id",c=this._attributes[a];if(!c)throw Error("Cannot refresh a model without a primary key");let l=await i.get(`SELECT * FROM ${this._definition.table} WHERE ${a} = ?`,[c]);if(!l)return null;return this._attributes=l,this._original=null,this}replicate(){let i=this._definition.primaryKey||"id",a={...this._attributes};return delete a[i],delete a.uuid,delete a.created_at,delete a.updated_at,new oe(this._definition,a)}toArray(){let i={...this._attributes};for(let[a,c]of Object.entries(this._relations))if(Array.isArray(c))i[a]=c.map((l)=>l.toArray());else if(c)i[a]=c.toArray();else i[a]=null;return i}toJSON(){let i=new Set;for(let[c,l]of Object.entries(this._definition.attributes))if(l.hidden)i.add(c);let a={};for(let[c,l]of Object.entries(this._attributes))if(!i.has(c))a[c]=l;for(let[c,l]of Object.entries(this._relations))if(Array.isArray(l))a[c]=l.map((u)=>u.toJSON());else if(l)a[c]=l.toJSON();else a[c]=null;return a}}var xi=new Map,Ei=new Map,ot=new Map,hc=1000;function ge(i){return I(i)}function I(i){let a=xi.get(i);if(a!==void 0)return a;return a=i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),xi.set(i,a),a}function Be(i){let a=Ei.get(i);if(a!==void 0)return a;return a=Ue(i),Ei.set(i,a),a}var Sr=["hasMany","hasOne","belongsTo","belongsToMany"],gc=[...Sr,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Ci(i,a){let c=i[a];if(!c)return[];if(Array.isArray(c))return c.map((l)=>typeof l==="string"?l:String(l?.model??"")).filter(Boolean);if(typeof c==="object")return Object.keys(c);if(typeof c==="string")return[c];return[]}function mc(i,a){let c=i.name??i.table??"model",u=gc.filter((d)=>Ci(i,d).some((h)=>h.toLowerCase()===a.toLowerCase())).filter((d)=>!Sr.includes(d));if(u.length>0)return`[orm] '${c}' declares '${a}' as ${u.join("/")}, which eager loading does not support yet. Supported kinds: ${Sr.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let f=Sr.flatMap((d)=>Ci(i,d));return f.length>0?`[orm] '${c}' has no relation '${a}'. Available: ${f.join(", ")}.`:`[orm] '${c}' has no relation '${a}' \u2014 it declares no relations at all.`}function Ni(i,a){let{name:c,table:l}=i,u=i.primaryKey||"id";function f(k){if(!k)return null;if(Array.isArray(k)){for(let E of k){let S=typeof E==="string"?E:E?.model||"";if(S&&S.toLowerCase()===a.toLowerCase())return S}return null}if(typeof k==="object"){for(let[E,S]of Object.entries(k))if(E===a||E.toLowerCase()===a.toLowerCase())return typeof S==="string"?S:S?.model||S?.target||E}return null}function d(){let k=i.belongsTo;if(!k)return null;let E=a.toLowerCase(),S=(C)=>{if(typeof C==="string")return{model:C};if(C&&typeof C==="object"&&typeof C.model==="string")return{model:C.model,foreignKey:C.foreignKey};return null};if(Array.isArray(k)){for(let C of k){let N=S(C);if(N&&N.model.toLowerCase()===E)return N}return null}if(typeof k==="object"){for(let[C,N]of Object.entries(k))if(C===a||C.toLowerCase()===E)return S(N)}return null}function h(){let k=i.belongsToMany;if(!k)return null;if(Array.isArray(k)){for(let E of k)if(typeof E==="string"){if(E.toLowerCase()===a.toLowerCase())return{entry:E}}else if(E&&typeof E==="object"&&E.model){if(E.model.toLowerCase()===a.toLowerCase())return{entry:E}}return null}if(typeof k==="object"){for(let[E,S]of Object.entries(k))if(E===a||E.toLowerCase()===a.toLowerCase())return{entry:S}}return null}let g=f(i.hasMany);if(g){let E=ce(g)?.getTable?.()||Be(g),S=I(c)+"_id";return{type:"hasMany",relatedModelName:g,relatedTable:E,foreignKey:S,localKey:u}}let m=f(i.hasOne);if(m){let E=ce(m)?.getTable?.()||Be(m),S=I(c)+"_id";return{type:"hasOne",relatedModelName:m,relatedTable:E,foreignKey:S,localKey:u}}let b=d();if(b){let k=b.model,E=ce(k),S=E?.getTable?.()||Be(k),C=E?.getDefinition?.()?.primaryKey||"id",N=b.foreignKey||`${I(k)}_id`;return{type:"belongsTo",relatedModelName:k,relatedTable:S,foreignKey:N,localKey:C}}let T=h();if(T){let k=typeof T.entry==="object",E=k?T.entry.model:T.entry,C=ce(E)?.getTable?.()||Be(E),N=k?T.entry:null,V,q;if(N?.table)V=N.table;else if(N?.through){q=N.through;let re=ce(N.through);if(!re)throw Error(`[orm] belongsToMany relation '${a}' on '${c}' references unknown through model '${N.through}'. Make sure '${N.through}' is registered.`);V=re.getTable?.()||re.getDefinition?.()?.table||Be(N.through)}else{let re=Mt(l),pe=Mt(C);V=[re,pe].sort().join("_")}let ie=N?.foreignKey||`${Mt(l)}_id`,Ke=N?.relatedKey||`${Mt(C)}_id`,Ee=[];if(N?.pivot?.columns)for(let re of Object.keys(N.pivot.columns))Ee.push(re);if(q){let re=ce(q),pe=re?.getDefinition?.()||re?.definition,Ar=pe?.attributes??{},_i=pe?.primaryKey??"id";for(let lt of Object.keys(Ar)){if(lt===ie||lt===Ke||lt===_i)continue;if(!Ee.includes(lt))Ee.push(lt)}}return{type:"belongsToMany",relatedModelName:E,relatedTable:C,foreignKey:ie,localKey:u,pivotTable:V,pivotFkParent:ie,pivotFkRelated:Ke,pivotColumns:Ee,pivotModelName:q,pivotTimestamps:Boolean(N?.pivot?.timestamps)}}let v=(k,E)=>{if(!k||typeof k!=="object"||Array.isArray(k))return null;let S=k[a]??k[Object.keys(k).find((pe)=>pe.toLowerCase()===a.toLowerCase())??""];if(!S||typeof S!=="object")return null;let{through:C,target:N}=S;if(!C||!N)return null;let V=ce(C),q=V?.getDefinition?.()||V?.definition,ie=V?.getTable?.()||q?.table||Be(C),Ke=q?.primaryKey||"id",re=ce(N)?.getTable?.()||Be(N);return{type:E,relatedModelName:N,relatedTable:re,foreignKey:`${I(c)}_id`,localKey:u,throughTable:ie,throughForeignKey:`${I(c)}_id`,throughLocalKey:Ke,targetForeignKey:`${Mt(ie)}_id`}},D=v(i.hasManyThrough,"hasManyThrough");if(D)return D;let R=v(i.hasOneThrough,"hasOneThrough");if(R)return R;return null}function Rn(i,a){let c=new Set;for(let l of i){let u=l.get(a);if(u!=null)c.add(u)}return[...c]}function Mt(i){return y(e.relations?.singularizeStrategy)(i)}class Et{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(i,a,c,l){this._parent=i,this._parentDef=a,this._resolved=c,this._relatedDef=l}get parentId(){let i=this._parentDef.primaryKey||"id";return this._parent.get(i)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(i,a,c){if(c===void 0)this._wheres.push({sql:`${this.relatedTable}.${i} = ?`,params:[a]});else this._wheres.push({sql:`${this.relatedTable}.${i} ${String(a)} ?`,params:[c]});return this}wherePivot(i,a,c){if(c===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${i} = ?`,params:[a]});else this._pivotWheres.push({sql:`${this.pivotTable}.${i} ${String(a)} ?`,params:[c]});return this}wherePivotIn(i,a){if(!a.length)return this;let c=a.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${i} IN (${c})`,params:[...a]}),this}wherePivotNotIn(i,a){if(!a.length)return this;let c=a.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${i} NOT IN (${c})`,params:[...a]}),this}wherePivotNull(i){return this._pivotWheres.push({sql:`${this.pivotTable}.${i} IS NULL`,params:[]}),this}wherePivotNotNull(i){return this._pivotWheres.push({sql:`${this.pivotTable}.${i} IS NOT NULL`,params:[]}),this}orderBy(i,a="asc"){if(Mi(i,"orderBy(column)"),a!=="asc"&&a!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${a}'`);return this._orderBy.push(`${i} ${a.toUpperCase()}`),this}limit(i){if(!Number.isFinite(i)||i<0||!Number.isInteger(i))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${i}`);return this._limit=i,this}offset(i){if(!Number.isFinite(i)||i<0||!Number.isInteger(i))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${i}`);return this._offset=i,this}relatedSelectColumns(){let i=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),a=this._relatedDef.traits;if(a?.useTimestamps||a?.timestampable)i.add("created_at"),i.add("updated_at");if(a?.useSoftDeletes||a?.softDeletable)i.add("deleted_at");if(a?.useUuid)i.add("uuid");return[...i]}buildSelect(){let i=[],c=`SELECT ${this.relatedSelectColumns().map((l)=>`${this.relatedTable}.${l} AS ${An}${l}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;c+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,c+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,i.push(this.parentId);for(let l of this._pivotWheres)c+=` AND ${l.sql}`,i.push(...l.params);for(let l of this._wheres)c+=` AND ${l.sql}`,i.push(...l.params);if(this._orderBy.length>0)c+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)c+=` LIMIT ${this._limit}`;if(this._offset!==void 0)c+=` OFFSET ${this._offset}`;return{sql:c,params:i}}hydrateRows(i){let a=this.fkParent,c=this.fkRelated;return i.map((l)=>{let u={},f={};for(let[h,g]of Object.entries(l))if(h.startsWith(An))u[h.slice(An.length)]=g;else if(h!==a&&h!==c)f[h]=g;let d=new oe(this._relatedDef,u);return d.pivot=f,d})}async get(){let i=B(),{sql:a,params:c}=this.buildSelect(),l=await i.all(a,c);return this.hydrateRows(l)}async first(){return this._limit=1,(await this.get())[0]}async count(){let i=B(),a=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,c=[this.parentId];for(let u of this._pivotWheres)a+=` AND ${u.sql}`,c.push(...u.params);let l=await i.get(a,c);return Number(l?.count??0)}async exists(){return await this.count()>0}now(){return Ie()}async attach(i,a={}){let c=B(),l=Array.isArray(i)?i:[i];if(l.length===0)return 0;let u=this._resolved.pivotTimestamps?this.now():null,f=0;for(let d of l){let h={[this.fkParent]:this.parentId,[this.fkRelated]:d,...a};if(u){if(h.created_at===void 0)h.created_at=u;if(h.updated_at===void 0)h.updated_at=u}let g=Object.keys(h),m=g.map(()=>"?").join(", "),b=`INSERT INTO ${this.pivotTable} (${g.join(", ")}) VALUES (${m})`,T=g.map((v)=>h[v]);await c.run(b,T),f++}return f}async detach(i){let a=B(),c=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,l=[this.parentId];if(i!==void 0&&i!==null){let u=Array.isArray(i)?i:[i];if(u.length===0)return 0;let f=u.map(()=>"?").join(", ");c+=` AND ${this.fkRelated} IN (${f})`,l.push(...u)}return(await a.run(c,l)).changes}async updateExistingPivot(i,a){let c=B(),l={...a};if(this._resolved.pivotTimestamps&&l.updated_at===void 0)l.updated_at=this.now();let u=Object.keys(l);if(u.length===0)return 0;let f=u.map((g)=>`${g} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${f} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,h=[...u.map((g)=>l[g]),this.parentId,i];return(await c.run(d,h)).changes}async sync(i){let a=B(),c=new Map;for(let m of i)if(m!=null&&typeof m==="object"&&"id"in m){let{id:b,...T}=m;c.set(b,T)}else c.set(m,{});let l=await a.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),u=new Set(l.map((m)=>m[this.fkRelated])),f=[],d=[],h=[],g=[...u].filter((m)=>!c.has(m));if(g.length>0)await this.detach(g),d.push(...g);for(let[m,b]of c)if(!u.has(m))await this.attach(m,b),f.push(m);else if(Object.keys(b).length>0)await this.updateExistingPivot(m,b),h.push(m);return{attached:f,detached:d,updated:h}}async toggle(i){let a=B(),c=Array.isArray(i)?i:[i];if(c.length===0)return{attached:[],detached:[]};let l=c.map(()=>"?").join(", "),u=await a.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${l})`,[this.parentId,...c]),f=new Set(u.map((g)=>g[this.fkRelated])),d=c.filter((g)=>!f.has(g)),h=c.filter((g)=>f.has(g));if(d.length>0)await this.attach(d);if(h.length>0)await this.detach(h);return{attached:d,detached:h}}}class _{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(i){this._definition=i}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(i,a,c){if(c===void 0)this._wheres.push({column:i,operator:"=",value:a,boolean:"and"});else this._wheres.push({column:i,operator:a,value:c,boolean:"and"});return this}orWhere(i,a,c){if(c===void 0)this._wheres.push({column:i,operator:"=",value:a,boolean:"or"});else this._wheres.push({column:i,operator:a,value:c,boolean:"or"});return this}whereIn(i,a){return this._wheres.push({column:i,operator:"in",value:a,boolean:"and"}),this}orWhereIn(i,a){return this._wheres.push({column:i,operator:"in",value:a,boolean:"or"}),this}whereNotIn(i,a){return this._wheres.push({column:i,operator:"not in",value:a,boolean:"and"}),this}orWhereNotIn(i,a){return this._wheres.push({column:i,operator:"not in",value:a,boolean:"or"}),this}whereNull(i){return ke(i,"whereNull(column)"),this._wheres.push({column:i,operator:"=",value:null,boolean:"and"}),this}orWhereNull(i){return ke(i,"orWhereNull(column)"),this._wheres.push({column:i,operator:"=",value:null,boolean:"or"}),this}whereNotNull(i){return ke(i,"whereNotNull(column)"),this._wheres.push({column:i,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(i){return ke(i,"orWhereNotNull(column)"),this._wheres.push({column:i,operator:"!=",value:null,boolean:"or"}),this}whereLike(i,a){return this._wheres.push({column:i,operator:"like",value:a,boolean:"and"}),this}orWhereLike(i,a){return this._wheres.push({column:i,operator:"like",value:a,boolean:"or"}),this}whereNotLike(i,a){return this._wheres.push({column:i,operator:"not like",value:a,boolean:"and"}),this}orWhereNotLike(i,a){return this._wheres.push({column:i,operator:"not like",value:a,boolean:"or"}),this}whereRaw(i,...a){return this._wheres.push({raw:i,rawParams:a,boolean:"and"}),this}orWhereRaw(i,...a){return this._wheres.push({raw:i,rawParams:a,boolean:"or"}),this}whereGroup(i){return this._addGroup("and",i)}orWhereGroup(i){return this._addGroup("or",i)}_addGroup(i,a){let c=new _(this._definition);if(a(c),c._wheres.length===0)return this;let l=[],u=c.buildWhereClauses(l);if(!u)return this;return this._wheres.push({raw:`(${u})`,rawParams:l,boolean:i}),this}whereBetween(i,a){return ke(i,"whereBetween(column)"),this._wheres.push({column:i,operator:">=",value:a[0],boolean:"and"}),this._wheres.push({column:i,operator:"<=",value:a[1],boolean:"and"}),this}whereNotBetween(i,a){ke(i,"whereNotBetween(column)");let c=ge(i);return this._wheres.push({raw:`(${c} < ? OR ${c} > ?)`,rawParams:[a[0],a[1]],boolean:"and"}),this}when(i,a){if(i)return a(this);return this}orderBy(i,a="asc"){if(Mi(i,"orderBy(column)"),a!=="asc"&&a!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${a}'`);return this._orderBy.push({column:i,direction:a}),this}orderByDesc(i){return this.orderBy(i,"desc")}orderByAsc(i){return this.orderBy(i,"asc")}limit(i){return this._limit=i,this}take(i){return this.limit(i)}offset(i){return this._offset=i,this}skip(i){return this.offset(i)}select(...i){return this._select=i,this}with(...i){for(let a of i)if(!this._withRelations.includes(a))this._withRelations.push(a);return this}getWithRelations(){return this._withRelations}buildWhereClauses(i){let a=[];for(let c of this._wheres){let l;if(c.raw){if(l=c.raw,c.rawParams&&c.rawParams.length>0)i.push(...c.rawParams)}else if(c.value===null){let u=ge(c.column);l=c.operator==="="?`${u} IS NULL`:`${u} IS NOT NULL`}else if(c.operator==="in"||c.operator==="not in"){let u=c.value;l=o(ge(c.column),u,c.operator==="not in",u.map(()=>"?").join(", ")),i.push(...u)}else l=`${ge(c.column)} ${c.operator} ?`,i.push(c.value);a.push({conn:c.boolean==="or"?"OR":"AND",sql:l})}return x(a)}softDeleteClause(){if(this._trashed==="include"||!at(this._definition))return"";return this._trashed==="only"?`${Pe} IS NOT NULL`:`${Pe} IS NULL`}assertNoUnappliedClauses(i){let a=[];if(this._limit!==void 0)a.push("limit()");if(this._offset!==void 0)a.push("offset()");if(this._orderBy.length>0)a.push("orderBy()");if(a.length>0)throw TypeError(`[orm] ${i}() cannot apply ${a.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere(i){let a=this._wheres.length>0?this.buildWhereClauses(i):"",c=this.softDeleteClause();if(a&&c)return`(${a}) AND ${c}`;return a||c}buildQuery(){let i=[],c=`SELECT ${this._select.map((u)=>u==="*"?u:ge(u)).join(", ")} FROM ${this._definition.table}`,l=this.composeWhere(i);if(l)c+=` WHERE ${l}`;if(this._orderBy.length>0)c+=` ORDER BY ${this._orderBy.map((u)=>`${ge(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)c+=` LIMIT ${this._limit}`;if(this._offset!==void 0)c+=` OFFSET ${this._offset}`;return{sql:c,params:i}}toSql(){return this.buildQuery()}async eagerLoadRelations(i){if(i.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((a)=>this.eagerLoadRelation(a,i)))}async eagerLoadRelation(i,a){let c=B(),l=this._definition.primaryKey||"id",u=`${this._definition.name}:${i}`,f=ot.get(u);if(f===void 0){if(f=Ni(this._definition,i),ot.size>=hc)ot.clear();ot.set(u,f)}if(!f)throw Error(mc(this._definition,i));if(f.type==="hasMany"||f.type==="hasOne"){let d=Rn(a,l);if(d.length===0)return;let h=d.map(()=>"?").join(", "),g=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${f.foreignKey} IN (${h})`,d),m=ce(f.relatedModelName),b=m?.getDefinition?.()||m?.definition||this._definition;if(f.type==="hasMany"){let T=new Map;for(let v of g){let D=v[f.foreignKey];if(!T.has(D))T.set(D,[]);T.get(D).push(v)}for(let v of a){let D=T.get(v.get(l))||[];v.setRelation(i,D.map((R)=>new oe(b,R)))}}else{let T=new Map;for(let v of g){let D=v[f.foreignKey];if(!T.has(D))T.set(D,v)}for(let v of a){let D=T.get(v.get(l));v.setRelation(i,D?new oe(b,D):null)}}}if(f.type==="belongsTo"){let d=new Set;for(let D of a){let R=D._attributes[f.foreignKey];if(R!=null)d.add(R)}let h=[...d];if(h.length===0)return;let g=h.map(()=>"?").join(", "),m=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${f.localKey} IN (${g})`,h),b=ce(f.relatedModelName),T=b?.getDefinition?.()||b?.definition||this._definition,v=new Map;for(let D of m)v.set(D[f.localKey],D);for(let D of a){let R=D._attributes[f.foreignKey],k=v.get(R);D.setRelation(i,k?new oe(T,k):null)}}if(f.type==="belongsToMany"){let d=Rn(a,l);if(d.length===0)return;if(!f.pivotTable||!f.pivotFkParent||!f.pivotFkRelated)return;let h=d.map(()=>"?").join(", "),g=await c.all(`SELECT * FROM ${f.pivotTable} WHERE ${f.pivotFkParent} IN (${h})`,d);if(g.length===0){for(let C of a)C.setRelation(i,[]);return}let m=new Set;for(let C of g){let N=C[f.pivotFkRelated];if(N!=null)m.add(N)}let b=[...m],T=ce(f.relatedModelName),v=T?.getDefinition?.()||T?.definition||this._definition,D=v?.primaryKey||"id",R=[];if(b.length>0){let C=b.map(()=>"?").join(", ");R=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${D} IN (${C})`,b)}let k=new Map;for(let C of R)k.set(C[D],C);let E=new Map;for(let C of g){let N=C[f.pivotFkParent];if(!E.has(N))E.set(N,[]);E.get(N).push(C)}let S=new Set([f.pivotFkParent,f.pivotFkRelated]);for(let C of a){let N=C.get(l),q=(E.get(N)||[]).map((ie)=>{let Ke=k.get(ie[f.pivotFkRelated]);if(!Ke)return null;let Ee=new oe(v,Ke),re={};for(let[pe,Ar]of Object.entries(ie))if(!S.has(pe))re[pe]=Ar;return Ee.pivot=re,Ee}).filter((ie)=>ie!==null);C.setRelation(i,q)}}if(f.type==="hasManyThrough"||f.type==="hasOneThrough"){let d=Rn(a,l);if(d.length===0)return;let h=f.throughLocalKey||"id",g=d.map(()=>"?").join(", "),m=await c.all(`SELECT ${h}, ${f.throughForeignKey} FROM ${f.throughTable} WHERE ${f.throughForeignKey} IN (${g})`,d);if(m.length===0){for(let S of a)S.setRelation(i,f.type==="hasManyThrough"?[]:null);return}let b=new Map;for(let S of m)b.set(S[h],S[f.throughForeignKey]);let T=[...new Set(m.map((S)=>S[h]))],v=T.map(()=>"?").join(", "),D=await c.all(`SELECT * FROM ${f.relatedTable} WHERE ${f.targetForeignKey} IN (${v})`,T),R=ce(f.relatedModelName),k=R?.getDefinition?.()||R?.definition||this._definition,E=new Map;for(let S of D){let C=b.get(S[f.targetForeignKey]);if(C==null)continue;if(!E.has(C))E.set(C,[]);E.get(C).push(new oe(k,S))}for(let S of a){let C=E.get(S.get(l))||[];S.setRelation(i,f.type==="hasManyThrough"?C:C[0]??null)}}}async get(){let i=B(),{sql:a,params:c}=this.buildQuery(),u=(await i.all(a,c)).map((f)=>new oe(this._definition,f));if(this._withRelations.length>0)await this.eagerLoadRelations(u);return u}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let i=await this.first();if(!i)throw Error(`No ${this._definition.name} found`);return i}async last(){let i=this._definition.primaryKey||"id";return this._orderBy=[{column:i,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let i=B(),a=[],c=`SELECT COUNT(*) as count FROM ${this._definition.table}`,l=this.composeWhere(a);if(l)c+=` WHERE ${l}`;let u=await i.get(c,a);return Number(u?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let i=await this.get();if(i.length===0)throw Error(`No ${this._definition.name} found`);if(i.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return i[0]}async increment(i,a=1){ke(i,"increment(column)"),this.assertNoUnappliedClauses("increment");let c=B(),l=[a],u=ge(i),f=`UPDATE ${this._definition.table} SET ${u} = ${u} + ?`;if(je(this._definition))f+=", updated_at = ?",l.push(Ie());let d=this.composeWhere(l);if(d)f+=` WHERE ${d}`;return(await c.run(f,l)).changes}decrement(i,a=1){return this.increment(i,-a)}async chunk(i,a){let c=0;while(!0){let l=new _(this._definition);l._wheres=[...this._wheres],l._orderBy=[...this._orderBy],l._select=[...this._select],l._withRelations=[...this._withRelations],l._trashed=this._trashed,l._limit=i,l._offset=c*i;let u=await l.get();if(u.length===0)break;if(await a(u)===!1)break;if(u.length<i)break;c++}}async paginate(i=1,a=15){if(typeof i==="object"&&i!==null){let f=i;a=f.perPage??15,i=f.page??1}let c=await this.count(),l=Math.ceil(c/a);this._limit=a,this._offset=(i-1)*a;let u=await this.get();return{data:u,total:c,page:i,perPage:a,lastPage:l,hasMorePages:i<l,isEmpty:u.length===0,from:u.length>0?(i-1)*a+1:null,to:u.length>0?(i-1)*a+u.length:null,meta:{perPage:a,page:i,total:c,lastPage:l}}}async pluck(i){ke(i,"pluck(column)");let a=B(),c=[],l=ge(i),u=`SELECT ${l} FROM ${this._definition.table}`,f=this.composeWhere(c);if(f)u+=` WHERE ${f}`;if(this._orderBy.length>0)u+=` ORDER BY ${this._orderBy.map((h)=>`${ge(h.column)} ${h.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)u+=` LIMIT ${this._limit}`;if(this._offset!==void 0)u+=` OFFSET ${this._offset}`;return(await a.all(u,c)).map((h)=>h[l])}async aggregate(i,a){ke(a,`${i}(column)`);let c=B(),l=[],u=`SELECT ${i}(${ge(a)}) as v FROM ${this._definition.table}`,f=this.composeWhere(l);if(f)u+=` WHERE ${f}`;let h=(await c.get(u,l))?.v;if(h==null)return null;if(typeof h==="string"){let g=Number(h);return h.trim()!==""&&!Number.isNaN(g)?g:h}return h}max(i){return this.aggregate("MAX",i)}min(i){return this.aggregate("MIN",i)}async avg(i){return Number(await this.aggregate("AVG",i)??0)||0}async sum(i){return Number(await this.aggregate("SUM",i)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let i=B(),a=[],c=`DELETE FROM ${this._definition.table}`,l=this.composeWhere(a);if(l)c+=` WHERE ${l}`;return(await i.run(c,a)).changes}async update(i){this.assertNoUnappliedClauses("update");let a=B(),c=Object.entries(i),l=c.map(([h])=>`${ge(h)} = ?`).join(", "),u=c.map(([,h])=>h);if(je(this._definition))u.push(Ie());let f=`UPDATE ${this._definition.table} SET ${l}${je(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(u);if(d)f+=` WHERE ${d}`;return(await a.run(f,u)).changes}}function yc(i){let a={query:()=>new _(i),where(c,l,u){return new _(i).where(c,l,u)},orWhere(c,l,u){return new _(i).orWhere(c,l,u)},whereIn(c,l){return new _(i).whereIn(c,l)},whereNotIn(c,l){return new _(i).whereNotIn(c,l)},whereNull(c){return new _(i).whereNull(c)},whereNotNull(c){return new _(i).whereNotNull(c)},whereLike(c,l){return new _(i).whereLike(c,l)},orderBy(c,l="asc"){return new _(i).orderBy(c,l)},orderByDesc(c){return new _(i).orderByDesc(c)},select(...c){return new _(i).select(...c)},with(...c){return new _(i).with(...c)},limit:(c)=>new _(i).limit(c),take:(c)=>new _(i).take(c),skip:(c)=>new _(i).skip(c),withTrashed:()=>new _(i).withTrashed(),onlyTrashed:()=>new _(i).onlyTrashed(),async find(c){let l=B(),u=i.primaryKey||"id",f=at(i)?` AND ${Pe} IS NULL`:"",d=await l.get(`SELECT * FROM ${i.table} WHERE ${u} = ?${f}`,[c]);return d?new oe(i,d):void 0},async findOrFail(c){let l=await a.find(c);if(!l)throw Error(`${i.name} with id ${c} not found`);return l},async findMany(c){let l=B(),u=i.primaryKey||"id",f=at(i)?` AND ${Pe} IS NULL`:"";return(await l.all(`SELECT * FROM ${i.table} WHERE ${u} IN (${c.map(()=>"?").join(", ")})${f}`,c)).map((h)=>new oe(i,h))},all:()=>new _(i).get(),first:()=>new _(i).first(),firstOrFail:()=>new _(i).firstOrFail(),last:()=>new _(i).last(),count:()=>new _(i).count(),exists:()=>new _(i).exists(),doesntExist:()=>new _(i).doesntExist(),paginate:(c,l)=>new _(i).paginate(c,l),whereBetween(c,l){return new _(i).whereBetween(c,l)},whereNotBetween(c,l){return new _(i).whereNotBetween(c,l)},async create(c){let l=new oe(i,c);return await l.save(),l},async createMany(c){let l=[];for(let u of c)l.push(await this.create(u));return l},async updateOrCreate(c,l){let u=new _(i);for(let[d,h]of Object.entries(c))u=u.where(d,h);let f=await u.first();if(f)return await f.update(l),f;return this.create({...c,...l})},async firstOrCreate(c,l){let u=new _(i);for(let[d,h]of Object.entries(c))u=u.where(d,h);return await u.first()||this.create({...c,...l})},async destroy(c){let l=B(),u=i.primaryKey||"id";return(await l.run(`DELETE FROM ${i.table} WHERE ${u} = ?`,[c])).changes>0},remove(c){return this.destroy(c)},async truncate(){await B().run(`DELETE FROM ${i.table}`,[])},getDefinition:()=>i,getTable:()=>i.table,make(c={}){return new oe(i,c)},latest:(c="created_at")=>new _(i).orderByDesc(c),oldest:(c="created_at")=>new _(i).orderBy(c,"asc"),max:(c)=>new _(i).max(c),min:(c)=>new _(i).min(c),avg:(c)=>new _(i).avg(c),sum:(c)=>new _(i).sum(c),pluck(c){return new _(i).pluck(c)}};return new Proxy(a,{get(c,l){if(typeof l==="string"&&l.startsWith("where")&&l.length>5){let u=l.slice(5),f=u.charAt(0).toLowerCase()+u.slice(1);if(f in i.attributes||f==="id"||f===i.primaryKey)return(d)=>new _(i).where(f,d)}return Reflect.get(c,l)}})}function xt(i){let a=yc(i);if(i?.name)cc(i.name,a);return a}async function $n(i){let a=B(),c=I(i.primaryKey||"id"),l=[],u=new Set([c]);if(l.push(i.autoIncrement!==!1?`${c} INTEGER PRIMARY KEY AUTOINCREMENT`:`${c} INTEGER PRIMARY KEY`),i.traits?.useUuid)l.push("uuid TEXT UNIQUE"),u.add("uuid");for(let[f,d]of Object.entries(i.attributes)){let h=I(f);if(u.has(h))continue;u.add(h);let g=Pn(d.type),m=Ae(g);if(h.endsWith("_id")&&(g===void 0||A(g)))m="INTEGER";let b=`${h} ${m}`;if(d.unique)b+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let T=d.foreignKey;if(b+=` REFERENCES ${T.table}(${T.column??"id"})`,T.onDelete)b+=` ON DELETE ${T.onDelete.toUpperCase()}`;if(T.onUpdate)b+=` ON UPDATE ${T.onUpdate.toUpperCase()}`}l.push(b)}for(let f of M(i.belongsTo)){let d=f.foreignKey??`${I(f.model)}_id`;if(u.has(d))continue;u.add(d),l.push(`${d} INTEGER`)}if(je(i))for(let f of["created_at","updated_at"]){if(u.has(f))continue;u.add(f),l.push(`${f} TEXT`)}if(at(i)&&!u.has("deleted_at"))u.add("deleted_at"),l.push("deleted_at TEXT");await a.run(`CREATE TABLE IF NOT EXISTS ${i.table} (${l.join(", ")})`,[])}async function En(i,a,c){let l=B(),u=i.traits?.useSeeder,f=a??(typeof u==="object"&&u?u.count:10);if(!c)try{let d=await import("./chunk-0h2h0qf3.js");c=wt(d.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let d=0;d<f;d++){let h={};for(let[m,b]of Object.entries(i.attributes))if(b.factory)h[I(m)]=b.factory(c);if(je(i)){let m=Ie();h.created_at=m,h.updated_at=m}if(i.traits?.useUuid)h.uuid=crypto.randomUUID();let g=Object.keys(h);await l.run(`INSERT INTO ${i.table} (${g.join(", ")}) VALUES (${g.map(()=>"?").join(", ")})`,Object.values(h))}}var ct=new Map;function jt(i){return ct.get(i)}function qt(){return[...ct.values()]}function Wt(){return Object.fromEntries(ct)}function Ut(i){return ct.has(i)}function Vt(){ct.clear(),St()}function vt(i,a){return ct.set(i,a),a}function pc(){return typeof window<"u"&&typeof document<"u"}function Ht(i){let a;if(pc())a=Ne(i);else{let c=xt(i);a=Object.assign(c,{definition:i,getDefinition:()=>i,getTable:()=>i.table,getName:()=>i.name})}return vt(i.name,a),a}function Qt(i){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...i}}
66
+ export{r,bt,e,H,t,s,Q,qe,yn,It,Lt,G,Ce,w,bn,We,n,Ue,p,Kt,Ft,y,Tt,x,o,Tn,Re,A,Ae,wt,Me,M,St,Dt,$t,wn,Sn,Dn,Et,xt,$n,En,jt,qt,Wt,Ut,Vt,vt,Ht,Qt};