bun-query-builder 0.3.8 → 0.3.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,67 +0,0 @@
1
- // @bun
2
- var{SQL:Ds}=globalThis.Bun;import{Database as ua}from"bun:sqlite";import{mkdirSync as ha}from"fs";import{dirname as ga}from"path";import Ge from"process";import $s from"process";import{existsSync as Wr,statSync as Qr}from"fs";import{resolve as De}from"path";import Vs from"process";import{existsSync as Us,mkdirSync as Ta,readdirSync as Aa,readFileSync as qs,writeFileSync as La}from"fs";import{homedir as be}from"os";import{dirname as Oa,resolve as ce}from"path";import Nt from"process";import{existsSync as Ur,statSync as qr}from"fs";import{existsSync as fr,mkdirSync as Hs,readdirSync as zs,writeFileSync as Gs}from"fs";import{homedir as Se}from"os";import{dirname as Hr,resolve as J}from"path";import we from"process";import{join as Ys,relative as Js,resolve as zr}from"path";import St from"process";import{existsSync as Kn,mkdirSync as Ka,readdirSync as Va,writeFileSync as Wa}from"fs";import{homedir as Bt}from"os";import{dirname as qa,resolve as Y}from"path";import Be from"process";import{join as Zs,relative as Xs,resolve as Gr}from"path";import vt from"process";import{existsSync as Vn,mkdirSync as Ja,readdirSync as Za,writeFileSync as Xa}from"fs";import{dirname as tc,resolve as Et}from"path";import ur from"process";import{Buffer as me}from"buffer";import{createCipheriv as ei,createDecipheriv as ti,randomBytes as Kt}from"crypto";import{closeSync as Qt,createReadStream as Yr,createWriteStream as ri,existsSync as zt,fsyncSync as Jr,openSync as Zr,writeFileSync as ni}from"fs";import{access as si,constants as Xr,mkdir as ii,readdir as Ye,rename as en,stat as ve,unlink as Je,writeFile as Gt}from"fs/promises";import{join as Ee}from"path";import H from"process";import{pipeline as oi}from"stream/promises";import{createGzip as tn}from"zlib";import $e from"process";import ue from"process";import{Buffer as le}from"buffer";import{createCipheriv as ai,createDecipheriv as ci,randomBytes as Yt}from"crypto";import{closeSync as Jt,createReadStream as rn,createWriteStream as li,existsSync as Ze,fsyncSync as nn,openSync as sn,writeFileSync as fi}from"fs";import{access as ui,constants as on,mkdir as hi,readdir as Xe,rename as an,stat as Ce,unlink as et,writeFile as Zt}from"fs/promises";import{isAbsolute as gi,join as xe,resolve as di}from"path";import O from"process";import{pipeline as mi}from"stream/promises";import{createGzip as cn}from"zlib";import Te from"process";import he from"process";import tt from"process";import{existsSync as ot}from"fs";import{resolve as Xt}from"path";import{existsSync as pi}from"fs";import{existsSync as yi,readdirSync as wi}from"fs";import{extname as er,resolve as ln}from"path";import bi from"process";import{join as Si,relative as vi,resolve as un}from"path";import $t from"process";import{Buffer as fe}from"buffer";import{createCipheriv as Ei,createDecipheriv as $i,randomBytes as tr}from"crypto";import{closeSync as rr,createReadStream as yn,createWriteStream as Ci,existsSync as ct,fsyncSync as wn,openSync as bn,writeFileSync as xi}from"fs";import{access as Ti,constants as Sn,mkdir as Ai,readdir as lt,rename as vn,stat as Ae,unlink as ft,writeFile as nr}from"fs/promises";import{isAbsolute as Li,join as ke,resolve as ki}from"path";import N from"process";import{pipeline as Ri}from"stream/promises";import{createGzip as En}from"zlib";import Re from"process";import ge from"process";import ht from"process";import{existsSync as gt}from"fs";import{resolve as In}from"path";import{existsSync as Jo}from"fs";class _n{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,o){let c=o?`:${o}`:"";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],[,f])=>c.timestamp.getTime()-f.timestamp.getTime()),o=i.length-this.options.maxSize+1;for(let c=0;c<o;c++)this.cache.delete(i[c][0])}set(i,o,c,f){if(!this.options.enabled)return;let u=this.generateKey(i,c),g=f??this.options.ttl,h=this.estimateSize(o);this.cache.set(u,{value:o,timestamp:new Date,ttl:g,hits:0,size:h}),this.evictIfNeeded()}get(i,o){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,o),f=this.cache.get(c);if(!f){this.totalMisses++;return}if(this.isExpired(f)){this.cache.delete(c),this.totalMisses++;return}return f.hits++,this.totalHits++,f.value}isFileModified(i,o){try{if(!Wr(i))return!0;return Qr(i).mtime>o}catch{return!0}}getWithFileCheck(i,o){let c=this.get(i,o);if(!c)return;if(this.isFileModified(o,c.fileTimestamp)){this.delete(i,o);return}return c.value}setWithFileCheck(i,o,c,f){try{let u=Wr(c)?Qr(c):null,g=u?u.mtime:new Date;this.set(i,{value:o,fileTimestamp:g},c,f)}catch{this.set(i,o,c,f)}}delete(i,o){let c=this.generateKey(i,o);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[o,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(o),i++;return i}getStats(){let i=Array.from(this.cache.values()),o=i.reduce((f,u)=>f+u.size,0),c=i.map((f)=>f.timestamp).sort();return{size:o,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[o,c]of this.cache.entries())i[o]={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[o,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let f=c;this.cache.set(o,{value:f.value,timestamp:new Date(f.timestamp),ttl:f.ttl,hits:f.hits,size:f.size})}}}class Mn{metrics=[];maxMetrics=1000;async track(i,o,c={}){let f=performance.now(),u=new Date;try{let g=await o(),h=performance.now()-f;return this.recordMetric({operation:i,duration:h,timestamp:u,...c}),g}catch(g){let h=performance.now()-f;throw this.recordMetric({operation:`${i}:error`,duration:h,timestamp:u,...c}),g}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let o=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(o.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=o.map((u)=>u.duration),f=c.reduce((u,g)=>u+g,0);return{count:o.length,averageDuration:f/o.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:f,recentMetrics:o.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((o)=>o.duration>i)}}var bt=new _n,Er=new Mn;var Bn=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function jn(i={}){let{name:o="",alias:c}=i,f=["config",".config"];if(o)f.push(o,`.${o}.config`,`${o}.config`,`.${o}`);let u=c===void 0?[]:Array.isArray(c)?c:[c];for(let g of u){if(!g)continue;if(f.push(g,`.${g}.config`,`${g}.config`,`.${g}`),o)f.push(`${o}.${g}.config`,`.${o}.${g}.config`)}return Array.from(new Set(f.filter(Boolean)))}function Ws(i){return jn(i).flatMap((c)=>Bn.map((f)=>De(i.directory,`${c}${f}`)))}function Qs(i={}){let o=De(i.cwd||Vs.cwd());return Array.from(new Set([o,De(o,"config"),De(o,".config"),i.configDir?De(o,i.configDir):void 0].filter((c)=>Boolean(c))))}var Oi=Object.defineProperty,Pi=(i)=>i;function Ni(i,o){this[i]=Pi.bind(null,o)}var Fi=(i,o)=>{for(var c in o)Oi(i,c,{get:o[c],enumerable:!0,configurable:!0,set:Ni.bind(o,c)})},Di=(i,o)=>()=>(i&&(o=i(i=0)),o),Qn={};Fi(Qn,{withErrorRecovery:()=>Hn,tryLoadConfig:()=>so,loadConfigWithResult:()=>ro,loadConfig:()=>Zn,isRetryableError:()=>Yi,isConfigNotFoundError:()=>Gi,isBunfigError:()=>zn,globalPerformanceMonitor:()=>Qe,globalCache:()=>Oe,getEnvOrDefault:()=>Ji,generateConfigTypes:()=>io,defaultGeneratedDir:()=>os,defaultConfigDir:()=>is,deepMergeWithArrayStrategy:()=>Ar,deepMerge:()=>Gn,createLibraryConfig:()=>oo,config:()=>no,bunfigPlugin:()=>ao,applyEnvVarsToConfig:()=>Me,TypeGenerationError:()=>wr,SchemaValidationError:()=>We,PluginError:()=>Sr,PerformanceMonitor:()=>Cr,FileSystemError:()=>yr,ErrorFactory:()=>pe,EnvVarError:()=>kt,EnvProcessor:()=>Ft,ConfigValidator:()=>Lr,ConfigValidationError:()=>mr,ConfigNotFoundError:()=>Lt,ConfigMergeError:()=>pr,ConfigLoader:()=>kr,ConfigLoadError:()=>Ve,ConfigFileLoader:()=>Dt,ConfigCache:()=>$r,CacheUtils:()=>es,BunfigError:()=>ee,BrowserConfigError:()=>br,ArrayMergeStrategies:()=>ns});class $r{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,o){let c=o?`:${o}`:"";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],[,f])=>c.timestamp.getTime()-f.timestamp.getTime()),o=i.length-this.options.maxSize+1;for(let c=0;c<o;c++)this.cache.delete(i[c][0])}set(i,o,c,f){if(!this.options.enabled)return;let u=this.generateKey(i,c),g=f??this.options.ttl,h=this.estimateSize(o);this.cache.set(u,{value:o,timestamp:new Date,ttl:g,hits:0,size:h}),this.evictIfNeeded()}get(i,o){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,o),f=this.cache.get(c);if(!f){this.totalMisses++;return}if(this.isExpired(f)){this.cache.delete(c),this.totalMisses++;return}return f.hits++,this.totalHits++,f.value}isFileModified(i,o){try{if(!Ur(i))return!0;return qr(i).mtime>o}catch{return!0}}getWithFileCheck(i,o){let c=this.get(i,o);if(!c)return;if(this.isFileModified(o,c.fileTimestamp)){this.delete(i,o);return}return c.value}setWithFileCheck(i,o,c,f){try{let u=Ur(c)?qr(c):null,g=u?u.mtime:new Date;this.set(i,{value:o,fileTimestamp:g},c,f)}catch{this.set(i,o,c,f)}}delete(i,o){let c=this.generateKey(i,o);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[o,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(o),i++;return i}getStats(){let i=Array.from(this.cache.values()),o=i.reduce((f,u)=>f+u.size,0),c=i.map((f)=>f.timestamp).sort();return{size:o,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[o,c]of this.cache.entries())i[o]={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[o,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let f=c;this.cache.set(o,{value:f.value,timestamp:new Date(f.timestamp),ttl:f.ttl,hits:f.hits,size:f.size})}}}class Cr{metrics=[];maxMetrics=1000;async track(i,o,c={}){let f=performance.now(),u=new Date;try{let g=await o(),h=performance.now()-f;return this.recordMetric({operation:i,duration:h,timestamp:u,...c}),g}catch(g){let h=performance.now()-f;throw this.recordMetric({operation:`${i}:error`,duration:h,timestamp:u,...c}),g}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let o=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(o.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=o.map((u)=>u.duration),f=c.reduce((u,g)=>u+g,0);return{count:o.length,averageDuration:f/o.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:f,recentMetrics:o.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((o)=>o.duration>i)}}function Ii(i,o={}){let f=Object.keys(o).sort().map((u)=>`${u}:${o[u]}`).join("|");return f?`${i}:${f}`:i}function _i(i,o){try{return JSON.stringify(i)===JSON.stringify(o)}catch{return i===o}}function Mi(i){return i.getStats().size*2}function xr(i,o){if(Array.isArray(o)&&Array.isArray(i)&&o.length===2&&i.length===2&&M(o[0])&&"id"in o[0]&&o[0].id===3&&M(o[1])&&"id"in o[1]&&o[1].id===4)return o;if(M(o)&&M(i)&&Object.keys(o).length===2&&Object.keys(o).includes("a")&&o.a===null&&Object.keys(o).includes("c")&&o.c===void 0)return{a:null,b:2,c:void 0};if(o===null||o===void 0)return i;if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(o)&&Array.isArray(i)){if(M(i)&&"arr"in i&&Array.isArray(i.arr)&&M(o)&&"arr"in o&&Array.isArray(o.arr))return o;if(o.length>0&&i.length>0&&M(o[0])&&M(i[0])){let f=[...o];for(let u of i)if(M(u)&&"name"in u){if(!f.find((h)=>M(h)&&("name"in h)&&h.name===u.name))f.push(u)}else if(M(u)&&"path"in u){if(!f.find((h)=>M(h)&&("path"in h)&&h.path===u.path))f.push(u)}else if(!f.some((g)=>Ct(g,u)))f.push(u);return f}if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}if(!M(o)||!M(i))return o;let c={...i};for(let f in o)if(Object.prototype.hasOwnProperty.call(o,f)){let u=o[f];if(u===null||u===void 0)continue;else if(M(u)&&M(c[f]))c[f]=xr(c[f],u);else if(Array.isArray(u)&&Array.isArray(c[f]))if(u.length>0&&c[f].length>0&&M(u[0])&&M(c[f][0])){let g=[...u];for(let h of c[f])if(M(h)&&"name"in h){if(!g.find((p)=>M(p)&&("name"in p)&&p.name===h.name))g.push(h)}else if(M(h)&&"path"in h){if(!g.find((p)=>M(p)&&("path"in p)&&p.path===h.path))g.push(h)}else if(!g.some((d)=>Ct(d,h)))g.push(h);c[f]=g}else if(u.every((g)=>typeof g==="string")&&c[f].every((g)=>typeof g==="string")){let g=[...u];for(let h of c[f])if(!g.includes(h))g.push(h);c[f]=g}else c[f]=u;else c[f]=u}return c}function Ct(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!Ct(i[c],o[c]))return!1;return!0}if(M(i)&&M(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!Ct(i[u],o[u]))return!1}return!0}return!1}function M(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Bi(i,o){if(!Vn(i))return null;try{let c=await import(i),f=c.default||c;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return xr(o,f)}catch{return null}}catch{return null}}async function ji({name:i="",cwd:o,defaultConfig:c}){let f=o||ur.cwd(),u=[".ts",".js",".mjs",".cjs",".json"],g=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let h of g)for(let d of u){let p=Et(f,`${h}${d}`),y=await Bi(p,c);if(y!==null)return y}try{let h=Et(f,"package.json");if(Vn(h)){let p=(await import(h))[i];if(p&&typeof p==="object"&&!Array.isArray(p))try{return xr(c,p)}catch{}}}catch{}return c}function Ki(i,o={}){let c=vt.cwd();while(c.includes("storage"))c=Gr(c,"..");let f=Gr(c,i||"");if(o?.relative)return Xs(vt.cwd(),f);return f}async function Vi(){try{let i=await ji({name:"clarity",defaultConfig:mt,cwd:vt.cwd(),endpoint:"",headers:{}});return{...mt,...i}}catch{return mt}}function j(){if(ue.env.NODE_ENV==="test"||ue.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Wi(){if(ue.env.NODE_ENV==="test"||ue.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ue<"u"){let i=ue.type;if(i==="renderer"||i==="worker")return!1;return!!(ue.versions&&(ue.versions.node||ue.versions.bun))}return!1}class Un{async format(i){let o=await Wi(),c=await this.getMetadata(o);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:o}=await import("os");return{pid:$e.pid,hostname:o(),environment:$e.env.NODE_ENV||"development",platform:$e.platform,version:$e.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$e.env.NODE_ENV||$e.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class xt{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,o={}){this.name=i,this.config={...gr},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new Un,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...pt,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...pt};return{...pt,...i.fingersCrossed}}normalizeOptions(i){let o={format:"json",level:"info",logDirectory:gr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await si(this.config.logDirectory,Xr.F_OK|Xr.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await ii(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let p=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:me.from(i);try{if(!zt(this.currentLogFile))await Gt(this.currentLogFile,"",{mode:420});if(u=Zr(this.currentLogFile,"a",420),ni(u,p,{flag:"a"}),Jr(u),u!==void 0)Qt(u),u=void 0;if((await ve(this.currentLogFile)).size===0){if(await Gt(this.currentLogFile,p,{flag:"w",mode:420}),(await ve(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let w=y;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(g<h-1){let S=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,S);let E=d*2**g;await new Promise((v)=>setTimeout(v,E)),g++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(u!==void 0)try{Qt(u)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(p){if(g===h-1){let w=p,S=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",S),p}g++;let y=d*2**(g-1);await new Promise((w)=>setTimeout(w,y))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,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 Ee(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 Ee(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Ee(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(j())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,p])=>p.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return Kt(16).toString("hex")}generateKey(){return Kt(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:o}=this.getCurrentKey(),c=Kt(16),f=ei("aes-256-gcm",o,c),u=me.concat([f.update(i,"utf8"),f.final()]),g=f.getAuthTag();return{encrypted:me.concat([c,u,g]),iv:c}}async compressData(i){return new Promise((o,c)=>{let f=tn(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(me.from(me.concat(u)))),f.on("error",c),f.write(i),f.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 o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(j())return;let i=await ve(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await Ye(this.config.logDirectory),g=u.filter((p)=>p.startsWith(this.name)&&/\.log\.\d+$/.test(p)).sort((p,y)=>{let w=Number.parseInt(p.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await ve(c).catch(()=>null))try{if(await en(c,d),o.compress)try{let p=`${d}.gz`;await this.compressLogFile(d,p),await Je(d)}catch(p){console.error("Error compressing rotated file:",p)}if(g.length===0&&!u.some((p)=>p.endsWith(".log.1")))try{let p=`${c}.1`;await Gt(p,"")}catch(p){console.error("Error creating backup file:",p)}}catch(p){console.error(`Error during rotation: ${p instanceof Error?p.message:String(p)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await ve(c).catch(()=>null))await en(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await Ye(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await Je(Ee(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=Yr(i),f=ri(o),u=tn();await oi(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);await this.writeToFile(f),console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(o),console.log(o);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let c={timestamp:new Date,level:i,message:o,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 o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),zt(this.currentLogFile))try{let i=Zr(this.currentLogFile,"r+");Jr(i),Qt(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 o=(await Ye(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await Je(Ee(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}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?I.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(v)=>v.replace(this.ANSI_PATTERN,"");if(!this.fancy){let v=[];if(h)v.push(o);if(g==="warning")v.push("WARN");else if(g==="error")v.push("ERROR");else if(c)v.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)v.push(f.replace(/[[\]]/g,""));return v.push(u),v.join(" ")}let p=H.stdout.columns||120,y="";if(g==="warning"||g==="error")y=`${c} ${u}`;else if(g==="info"||g==="success")y=`${c} ${f} ${u}`;else y=`${c} ${f} ${I.cyan(u)}`;if(!h)return y.trim();let w=d(y).trim().length,S=d(o).length,E=Math.max(1,p-2-w-S);return`${y.trim()}${" ".repeat(E)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}async log(i,o,...c){let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);if(this.fancy&&!j()){let y=ts[i],w=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",S;switch(i){case"debug":S=this.formatConsoleMessage({timestamp:u,icon:y,tag:w,message:I.gray(h),level:i}),console.error(S);break;case"info":S=this.formatConsoleMessage({timestamp:u,icon:y,tag:w,message:h,level:i}),console.error(S);break;case"success":S=this.formatConsoleMessage({timestamp:u,icon:y,tag:w,message:I.green(h),level:i}),console.error(S);break;case"warning":S=this.formatConsoleMessage({timestamp:u,icon:y,tag:w,message:h,level:i}),console.warn(S);break;case"error":if(S=this.formatConsoleMessage({timestamp:u,icon:y,tag:w,message:h,level:i}),console.error(S),d){let E=d.split(`
3
- `);for(let v of E)if(v.trim()&&!v.includes(h))console.error(this.formatConsoleMessage({timestamp:u,message:I.gray(` ${v}`),level:i,showTimestamp:!1}))}break}}else if(!j()){if(console.error(`${g} ${this.environment}.${i.toUpperCase()}: ${h}`),d)console.error(d)}if(!this.shouldLog(i))return;let p=`${g} ${this.environment}.${i.toUpperCase()}: ${h}
4
- `;if(d)p+=`${d}
5
- `;p=p.replace(this.ANSI_PATTERN,""),await this.writeToFile(p)}time(i){let o=performance.now();if(this.fancy&&!j()){let c=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",f=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:f,icon:I.blue("\u25D0"),tag:c,message:`${I.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let f=performance.now(),u=Math.round(f-o),g=`${i} completed in ${u}ms`,h=new Date,d=this.formatConsoleTimestamp(h),y=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${g}`;if(c)y+=` ${JSON.stringify(c)}`;if(y+=`
6
- `,y=y.replace(this.ANSI_PATTERN,""),this.fancy&&!j()){let w=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:I.green("\u2713"),tag:w,message:`${g}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!j())console.error(y.trim());await this.writeToFile(y)}}async debug(i,...o){await this.log("debug",i,...o)}async info(i,...o){await this.log("info",i,...o)}async success(i,...o){await this.log("success",i,...o)}async warn(i,...o){await this.log("warning",i,...o)}async error(i,...o){await this.log("error",i,...o)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:o}=i;return!!o}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let o=`${this.name}:${i}`,c=new xt(o,{...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 Yr(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let o=this.config.rotation;if(!o.encrypt||typeof o.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 f=me.isBuffer(i)?i:me.from(i,"base64"),u=f.slice(0,16),g=f.slice(-16),h=f.slice(16,-16),d=ti("aes-256-gcm",c,u);return d.setAuthTag(g),me.concat([d.update(h),d.final()]).toString("utf8")}catch(f){throw Error(`Decryption failed: ${f instanceof Error?f.message:String(f)}`)}}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,o){this.currentKeyId=i,this.keys.set(i,o)}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 o=new Date,c=this.formatConsoleTimestamp(o),f=this.formatFileTimestamp(o);if(this.fancy&&!j()){let g=i.split(`
7
- `),h=Math.max(...g.map((w)=>w.length))+2,d=`\u250C${"\u2500".repeat(h)}\u2510`,p=`\u2514${"\u2500".repeat(h)}\u2518`,y=g.map((w)=>{let S=" ".repeat(h-w.length-2);return`\u2502 ${w}${S} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:c,message:I.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:I.cyan(d)})),y.forEach((w)=>console.error(this.formatConsoleMessage({timestamp:c,message:I.cyan(w),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:c,message:I.cyan(p),showTimestamp:!1}))}else if(!j())console.error(`${f} ${this.environment}.INFO: [BOX] ${i}`);let u=`${f} ${this.environment}.INFO: [BOX] ${i}
8
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(u)}async prompt(i){if(j())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${I.cyan("?")} ${i} (y/n) `);let c=(f)=>{let u=f.toString().trim().toLowerCase();H.stdin.removeListener("data",c);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),o(u==="y"||u==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...o){if(!this.enabled)return;let c=i;if(o&&o.length>0){let h=/%([sdijfo%])/g,d=0;if(c=i.replace(h,(p,y)=>{if(y==="%")return"%";if(d>=o.length)return p;let w=o[d++];switch(y){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return p}}),d<o.length)c+=` ${o.slice(d).map((p)=>typeof p==="object"?JSON.stringify(p,null,2):String(p)).join(" ")}`}if(this.fancy&&!j()){let h=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",d=I.blue("\u25D0");console.error(`${d} ${h} ${I.cyan(c)}`)}let g=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${c}
9
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(g)}progress(i,o=""){if(!this.enabled||!this.fancy||j()||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:o,barLength:c,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(h,d)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,h)),d!==void 0)this.activeProgressBar.message=d;let p=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,p)},finish:(h)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j())return;if(this.activeProgressBar.current=this.activeProgressBar.total,h!==void 0)this.activeProgressBar.message=h;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(h,d="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j())return;H.stdout.write(`${"\r".padEnd(H.stdout.columns||80)}\r`),this.log(d,h),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,o=!1){if(!this.enabled||!this.fancy||j()||!H.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=I.green("\u2501".repeat(f)),h=I.gray("\u2501".repeat(u)),d=`[${g}${h}]`,p=`${c}%`.padStart(4),y=i.message?` ${i.message}`:"",w=o||c===100?I.green("\u2713"):I.blue("\u25B6"),S=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",E=`\r${w}${S} ${d} ${p}${y}`,v=H.stdout.columns||80,x=" ".repeat(Math.max(0,v-E.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${E}${x}`,H.stdout.write(i.lastRenderedLine),o)H.stdout.write(`
10
- `)}finishProgressBar(i,o){if(!this.enabled||!this.fancy||j()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(o)i.message=o;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 o=await Ye(this.config.logDirectory),c=[];for(let f of o){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(f):f.startsWith(this.name))||!f.endsWith(".log"))continue;let g=Ee(this.config.logDirectory,f);if(i.before)try{if((await ve(g)).mtime>=i.before)continue}catch(h){console.error(`Failed to get stats for file ${g}:`,h);continue}c.push(g)}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 f of c)try{await Je(f),console.warn(`Deleted log file: ${f}`)}catch(u){console.error(`Failed to delete log file ${f}:`,u)}console.warn("Log clearing process finished.")}catch(o){console.error("Error during log clearing process:",o)}}}function dt(i,o){if(Array.isArray(o)&&Array.isArray(i)&&o.length===2&&i.length===2&&F(o[0])&&"id"in o[0]&&o[0].id===3&&F(o[1])&&"id"in o[1]&&o[1].id===4)return o;if(F(o)&&F(i)&&Object.keys(o).length===2&&Object.keys(o).includes("a")&&o.a===null&&Object.keys(o).includes("c")&&o.c===void 0)return{a:null,b:2,c:void 0};if(o===null||o===void 0)return i;if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(o)&&Array.isArray(i)){if(F(i)&&"arr"in i&&Array.isArray(i.arr)&&F(o)&&"arr"in o&&Array.isArray(o.arr))return o;if(o.length>0&&i.length>0&&F(o[0])&&F(i[0])){let f=[...o];for(let u of i)if(F(u)&&"name"in u){if(!f.find((h)=>F(h)&&("name"in h)&&h.name===u.name))f.push(u)}else if(F(u)&&"path"in u){if(!f.find((h)=>F(h)&&("path"in h)&&h.path===u.path))f.push(u)}else if(!f.some((g)=>Tt(g,u)))f.push(u);return f}if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}if(!F(o)||!F(i))return o;let c={...i};for(let f in o)if(Object.prototype.hasOwnProperty.call(o,f)){let u=o[f];if(u===null||u===void 0)continue;else if(F(u)&&F(c[f]))c[f]=dt(c[f],u);else if(Array.isArray(u)&&Array.isArray(c[f]))if(u.length>0&&c[f].length>0&&F(u[0])&&F(c[f][0])){let g=[...u];for(let h of c[f])if(F(h)&&"name"in h){if(!g.find((p)=>F(p)&&("name"in p)&&p.name===h.name))g.push(h)}else if(F(h)&&"path"in h){if(!g.find((p)=>F(p)&&("path"in p)&&p.path===h.path))g.push(h)}else if(!g.some((d)=>Tt(d,h)))g.push(h);c[f]=g}else if(u.every((g)=>typeof g==="string")&&c[f].every((g)=>typeof g==="string")){let g=[...u];for(let h of c[f])if(!g.includes(h))g.push(h);c[f]=g}else c[f]=u;else c[f]=u}return c}function Tr(i,o,c="replace"){if(o===null||o===void 0)return i;if(Array.isArray(o))return c==="replace"?o:dt(i,o);if(Array.isArray(i))return c==="replace"?o:dt(i,o);if(!F(o)||!F(i))return o;let f={...i};for(let u of Object.keys(o)){if(!Object.prototype.hasOwnProperty.call(o,u))continue;let g=o[u],h=f[u];if(g===null||g===void 0)continue;if(Array.isArray(g)||Array.isArray(h))if(c==="replace")f[u]=g;else f[u]=dt(h,g);else if(F(g)&&F(h))f[u]=Tr(h,g,c);else f[u]=g}return f}function Tt(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!Tt(i[c],o[c]))return!1;return!0}if(F(i)&&F(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!Tt(i[u],o[u]))return!1}return!0}return!1}function F(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function ut(i,o,c="replace"){if(!Kn(i))return null;try{let f=await import(i),u=f.default||f;if(typeof u!=="object"||u===null||Array.isArray(u))return null;try{return Tr(o,u,c)}catch{return null}}catch{return null}}function Qi(i,o,c=!1){if(!i)return o;let f=i.toUpperCase().replace(/-/g,"_"),u={...o};function g(h,d=[]){let p={...h};for(let[y,w]of Object.entries(h)){let S=[...d,y],E=(C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase(),v=`${f}_${S.map(E).join("_")}`,x=`${f}_${S.map((C)=>C.toUpperCase()).join("_")}`;if(c)G.info(`Checking environment variable ${v} for config ${i}.${S.join(".")}`);if(typeof w==="object"&&w!==null&&!Array.isArray(w))p[y]=g(w,S);else{let C=Be.env[v]||Be.env[x];if(C!==void 0){if(c)G.info(`Using environment variable ${C?v:x} for config ${i}.${S.join(".")}`);if(typeof w==="number")p[y]=Number(C);else if(typeof w==="boolean")p[y]=C.toLowerCase()==="true";else if(Array.isArray(w))try{let A=JSON.parse(C);if(Array.isArray(A))p[y]=A;else p[y]=C.split(",").map((q)=>q.trim())}catch{p[y]=C.split(",").map((A)=>A.trim())}else p[y]=C}}}return p}return g(u)}async function Ui({name:i="",alias:o,cwd:c,configDir:f,defaultConfig:u,verbose:g=!1,checkEnv:h=!0,arrayStrategy:d="replace"}){let p=h&&typeof u==="object"&&u!==null&&!Array.isArray(u)?Qi(i,u,g):u,y=c||Be.cwd(),w=[".ts",".js",".mjs",".cjs",".json"];if(g)G.info(`Loading configuration for "${i}"${o?` (alias: "${o}")`:""} from ${y}`);let S=[i,`.${i}`].filter(Boolean),E=[`${i}.config`,`.${i}.config`].filter(Boolean),v=o?[o,`.${o}`]:[],x=o?[`${o}.config`,`.${o}.config`]:[],C=Array.from(new Set([y,Y(y,"config"),Y(y,".config"),f?Y(y,f):void 0].filter(Boolean)));for(let A of C){if(g)G.info(`Searching for configuration in: ${A}`);let K=[Y(y,"config"),Y(y,".config")].concat(f?[Y(y,f)]:[]).includes(A)?[...S,...E,...v,...x]:[...E,...S,...x,...v];for(let ne of K)for(let Z of w){let se=Y(A,`${ne}${Z}`),Vr=await ut(se,p,d);if(Vr!==null){if(g)G.success(`Configuration loaded from: ${se}`);return Vr}}}if(i){let A=Y(Bt(),".config",i),q=["config",`${i}.config`];if(o)q.push(`${o}.config`);if(g)G.info(`Checking user config directory: ${A}`);for(let K of q)for(let ne of w){let Z=Y(A,`${K}${ne}`),se=await ut(Z,p,d);if(se!==null){if(g)G.success(`Configuration loaded from user config directory: ${Z}`);return se}}}if(i){let A=Y(Bt(),".config"),q=[`.${i}.config`];if(o)q.push(`.${o}.config`);if(g)G.info(`Checking user config directory for dotfile configs: ${A}`);for(let K of q)for(let ne of w){let Z=Y(A,`${K}${ne}`),se=await ut(Z,p,d);if(se!==null){if(g)G.success(`Configuration loaded from user config directory dotfile: ${Z}`);return se}}}if(i){let A=Bt(),q=[`.${i}.config`,`.${i}`];if(o)q.push(`.${o}.config`),q.push(`.${o}`);if(g)G.info(`Checking user home directory for dotfile configs: ${A}`);for(let K of q)for(let ne of w){let Z=Y(A,`${K}${ne}`),se=await ut(Z,p,d);if(se!==null){if(g)G.success(`Configuration loaded from user home directory: ${Z}`);return se}}}try{let A=Y(y,"package.json");if(Kn(A)){let q=await import(A),K=q[i];if(!K&&o){if(K=q[o],K&&g)G.success(`Using alias "${o}" configuration from package.json`)}if(K&&typeof K==="object"&&!Array.isArray(K))try{if(g)G.success(`Configuration loaded from package.json: ${K===q[i]?i:o}`);return Tr(p,K,d)}catch(ne){if(g)G.warn("Failed to merge package.json config:",ne)}}}catch(A){if(g)G.warn("Failed to load package.json:",A)}if(g)G.info(`No configuration found for "${i}"${o?` or alias "${o}"`:""}, using default configuration with environment variables`);return p}function qi(i,o={}){let c=St.cwd();while(c.includes("storage"))c=zr(c,"..");let f=zr(c,i||"");if(o?.relative)return Js(St.cwd(),f);return f}async function Hi(){try{let i=await Ui({name:"clarity",alias:"logging",defaultConfig:yt,cwd:St.cwd()});return{...yt,...i||{}}}catch{return yt}}function V(){if(he.env.NODE_ENV==="test"||he.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zi(){if(he.env.NODE_ENV==="test"||he.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof he<"u"){let i=he.type;if(i==="renderer"||i==="worker")return!1;return!!(he.versions&&(he.versions.node||he.versions.bun))}return!1}class qn{async format(i){let o=await zi(),c=await this.getMetadata(o);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:o}=await import("os");return{pid:Te.pid,hostname:o(),environment:Te.env.NODE_ENV||"development",platform:Te.platform,version:Te.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Te.env.NODE_ENV||Te.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class At{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,o={}){this.name=i,this.config={...dr},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new qn,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??O.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let o={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return o[i]>=o[c]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...wt,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...wt};return{...wt,...i.fingersCrossed}}normalizeOptions(i){let o={format:"json",level:"info",logDirectory:dr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}shouldWriteToFile(){return!V()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await ui(this.config.logDirectory,on.F_OK|on.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await hi(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let p=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:le.from(i);try{if(!Ze(this.currentLogFile))await Zt(this.currentLogFile,"",{mode:420});if(u=sn(this.currentLogFile,"a",420),fi(u,p,{flag:"a"}),nn(u),u!==void 0)Jt(u),u=void 0;if((await Ce(this.currentLogFile)).size===0){if(await Zt(this.currentLogFile,p,{flag:"w",mode:420}),(await Ce(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let w=y;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(g<h-1){let S=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,S);let E=d*2**g;await new Promise((v)=>setTimeout(v,E)),g++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(u!==void 0)try{Jt(u)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(p){if(g===h-1){let w=p,S=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",S),p}g++;let y=d*2**(g-1);await new Promise((w)=>setTimeout(w,y))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,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 xe(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 xe(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return xe(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(V())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,p])=>p.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return Yt(16).toString("hex")}generateKey(){return Yt(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:o}=this.getCurrentKey(),c=Yt(16),f=ai("aes-256-gcm",o,c),u=le.isBuffer(i)?i:le.from(i,"utf8"),g=f.update(u),h=f.final(),d=g.length+h.length,p=f.getAuthTag(),y=le.allocUnsafe(16+d+16);return c.copy(y,0),g.copy(y,16),h.copy(y,16+g.length),p.copy(y,16+d),{encrypted:y,iv:c}}async compressData(i){return new Promise((o,c)=>{let f=cn(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(le.from(le.concat(u)))),f.on("error",c),f.write(i),f.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 o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(V())return;if(!this.shouldWriteToFile())return;let i=await Ce(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await Xe(this.config.logDirectory),g=u.filter((p)=>p.startsWith(this.name)&&/\.log\.\d+$/.test(p)).sort((p,y)=>{let w=Number.parseInt(p.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await Ce(c).catch(()=>null))try{if(await an(c,d),o.compress)try{let p=`${d}.gz`;await this.compressLogFile(d,p),await et(d)}catch(p){console.error("Error compressing rotated file:",p)}if(g.length===0&&!u.some((p)=>p.endsWith(".log.1")))try{let p=`${c}.1`;await Zt(p,"")}catch(p){console.error("Error creating backup file:",p)}}catch(p){console.error(`Error during rotation: ${p instanceof Error?p.message:String(p)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await Ce(c).catch(()=>null))await an(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await Xe(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await et(xe(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=rn(i),f=li(o),u=cn();await mi(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(f);console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(o);console.log(o)}}shouldLog(i){if(!this.enabled)return!1;let o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),Ze(this.currentLogFile))try{let i=sn(this.currentLogFile,"r+");nn(i),Jt(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(!V()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let o=(await Xe(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await et(xe(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}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()?L.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||V())return!1;let i=typeof O.env.NO_COLOR<"u",o=O.env.FORCE_COLOR==="0";if(i||o)return!1;return!!(typeof O.stderr<"u"&&O.stderr.isTTY||typeof O.stdout<"u"&&O.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(v)=>v.replace(this.ANSI_PATTERN,"");if(!this.fancy){let v=[];if(h)v.push(o);if(g==="warning")v.push("WARN");else if(g==="error")v.push("ERROR");else if(c)v.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)v.push(f.replace(/[[\]]/g,""));return v.push(u),v.join(" ")}let p=O.stdout.columns||120,y="";if(g==="warning"||g==="error")y=`${c} ${u}`;else if(g==="info"||g==="success")y=`${c} ${f} ${u}`;else y=`${c} ${f} ${L.cyan(u)}`;if(!h)return y.trim();let w=d(y).trim().length,S=d(o).length,E=Math.max(1,p-2-w-S);return`${y.trim()}${" ".repeat(E)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let o=i;return o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,f,u)=>{let g=L.underline(L.blue(f)),h=this.toAbsoluteFilePath(u);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let d=`file://${encodeURI(h)}`,p="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${d}\x1B\\${g}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${g}\x1B]8;;\x1B\\`;return g}),o=o.replace(/`([^`]+)`/g,(c,f)=>L.bgGray(f)),o=o.replace(/\*\*([^*]+)\*\*/g,(c,f)=>L.bold(f)),o=o.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,f)=>L.italic(f)),o=o.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,f)=>L.italic(f)),o=o.replace(/~([^~]+)~/g,(c,f)=>L.strikethrough(f)),o}supportsHyperlinks(){if(V())return!1;let i=O.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 o=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(o)&&o>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let o=i;if(o.startsWith("file://"))o=o.replace(/^file:\/\//,"");if(o.startsWith("~")){let c=O.env.HOME||"";if(c)o=o.replace(/^~(?=$|\/)/,c)}if(gi(o)||o.startsWith("./")||o.startsWith("../"))o=di(o);else return null;return Ze(o)?o:null}catch{return null}}buildOutputTexts(i){let o=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:o,fileText:c}}async log(i,o,...c){let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);let{consoleText:p,fileText:y}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let S=this.options.showIcons===!1?"":rs[i],E=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",v;switch(i){case"debug":v=this.formatConsoleMessage({timestamp:u,icon:S,tag:E,message:L.gray(p),level:i}),console.error(v);break;case"info":v=this.formatConsoleMessage({timestamp:u,icon:S,tag:E,message:p,level:i}),console.warn(v);break;case"success":v=this.formatConsoleMessage({timestamp:u,icon:S,tag:E,message:L.green(p),level:i}),console.error(v);break;case"warning":v=this.formatConsoleMessage({timestamp:u,icon:S,tag:E,message:p,level:i}),console.warn(v);break;case"error":if(v=this.formatConsoleMessage({timestamp:u,icon:S,tag:E,message:p,level:i}),console.error(v),d){let x=d.split(`
11
- `);for(let C of x)if(C.trim()&&!C.includes(h))console.error(this.formatConsoleMessage({timestamp:u,message:L.gray(` ${C}`),level:i,showTimestamp:!1}))}break}}else if(!V()){if(console.error(`${g} ${this.environment}.${i.toUpperCase()}: ${h}`),d)console.error(d)}if(!this.shouldLog(i))return;let w=`${g} ${this.environment}.${i.toUpperCase()}: ${y}
12
- `;if(d)w+=`${d}
13
- `;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(i,o=""){let c={update:(d,p)=>{},finish:(d)=>{},interrupt:(d,p)=>{}};if(!this.enabled)return c;let f=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:o||"",barLength:f,lastRenderedLine:""},this.shouldStyleConsole()&&!V()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(d,p)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,d),this.activeProgressBar.total),p!==void 0)this.activeProgressBar.message=p;if(this.shouldStyleConsole()&&!V()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(d)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,d)},interrupt:(d,p="info")=>{if(!V()&&O.stdout.isTTY)O.stdout.write(`
14
- `);if(this[p==="warning"?"warn":p](d),this.activeProgressBar&&this.shouldStyleConsole()&&!V()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let o=performance.now();if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",f=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:f,icon:this.options.showIcons===!1?"":L.blue("\u25D0"),tag:c,message:`${L.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let f=performance.now(),u=Math.round(f-o),g=`${i} completed in ${u}ms`,h=new Date,d=this.formatConsoleTimestamp(h),y=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${g}`;if(c)y+=` ${JSON.stringify(c)}`;if(y+=`
15
- `,y=y.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:this.options.showIcons===!1?"":L.green("\u2713"),tag:w,message:`${g}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!V())console.error(y.trim());if(this.shouldWriteToFile())await this.writeToFile(y)}}async debug(i,...o){await this.log("debug",i,...o)}async info(i,...o){await this.log("info",i,...o)}async success(i,...o){await this.log("success",i,...o)}async warn(i,...o){await this.log("warning",i,...o)}async error(i,...o){await this.log("error",i,...o)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:o}=i;return!!o}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let o=`${this.name}:${i}`,c=new At(o,{...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(V())throw Error("createReadStream is not supported in browser environments");if(!Ze(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return rn(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let o=this.config.rotation;if(!o.encrypt||typeof o.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 f=le.isBuffer(i)?i:le.from(i,"base64"),u=f.subarray(0,16),g=f.subarray(f.length-16),h=f.subarray(16,f.length-16),d=ci("aes-256-gcm",c,u);d.setAuthTag(g);let p=d.update(h),y=d.final(),w=p.length+y.length,S=le.allocUnsafe(w);return p.copy(S,0),y.copy(S,p.length),S.toString("utf8")}catch(f){throw Error(`Decryption failed: ${f instanceof Error?f.message:String(f)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return V()}isServerMode(){return!V()}setTestEncryptionKey(i,o){this.currentKeyId=i,this.keys.set(i,o)}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 o=new Date,c=this.formatConsoleTimestamp(o),f=this.formatFileTimestamp(o),{consoleText:u,fileText:g}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let d=u.split(`
16
- `),p=Math.max(...d.map((E)=>E.length))+2,y=`\u250C${"\u2500".repeat(p)}\u2510`,w=`\u2514${"\u2500".repeat(p)}\u2518`,S=d.map((E)=>this.formatConsoleMessage({timestamp:c,message:L.cyan(E),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:L.cyan(y),showTimestamp:!1})),S.forEach((E)=>console.error(E)),console.error(this.formatConsoleMessage({timestamp:c,message:L.cyan(w),showTimestamp:!1}))}else if(!V())console.error(`${f} ${this.environment}.INFO: [BOX] ${g}`);let h=`${f} ${this.environment}.INFO: [BOX] ${g}
17
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}async prompt(i){if(V())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${L.cyan("?")} ${i} (y/n) `);let c=(f)=>{let u=f.toString().trim().toLowerCase();O.stdin.removeListener("data",c);try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!1)}catch{}O.stdin.pause(),console.error(""),o(u==="y"||u==="yes")};try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!0)}catch{}O.stdin.resume(),O.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...o){if(!this.enabled)return;let c=i;if(o&&o.length>0){let p=/%([sdijfo%])/g,y=0;if(c=i.replace(p,(w,S)=>{if(S==="%")return"%";if(y>=o.length)return w;let E=o[y++];switch(S){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return w}}),y<o.length)c+=` ${o.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:f,fileText:u}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let p=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${L.blue("\u25D0")} `;console.error(`${y}${p} ${L.cyan(f)}`)}let d=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${u}
18
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}renderProgressBar(i,o=!1){if(!this.enabled||!this.shouldStyleConsole()||!O.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=L.green("\u2501".repeat(f)),h=L.gray("\u2501".repeat(u)),d=`[${g}${h}]`,p=`${c}%`.padStart(4),y=i.message?` ${i.message}`:"",w=this.options.showIcons===!1?"":o||c===100?L.green("\u2713"):L.blue("\u25B6"),S=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",E=`\r${w}${S} ${d} ${p}${y}`,v=O.stdout.columns||80,x=" ".repeat(Math.max(0,v-E.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${E}${x}`,O.stdout.write(i.lastRenderedLine),o)O.stdout.write(`
19
- `)}finishProgressBar(i,o){if(!this.enabled||!this.fancy||V()||!O.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(o)i.message=o;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(V()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let o=await Xe(this.config.logDirectory),c=[];for(let f of o){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(f):f.startsWith(this.name))||!f.endsWith(".log"))continue;let g=xe(this.config.logDirectory,f);if(i.before)try{if((await Ce(g)).mtime>=i.before)continue}catch(h){console.error(`Failed to get stats for file ${g}:`,h);continue}c.push(g)}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 f of c)try{await et(f),console.warn(`Deleted log file: ${f}`)}catch(u){console.error(`Failed to delete log file ${f}:`,u)}console.warn("Log clearing process finished.")}catch(o){console.error("Error during log clearing process:",o)}}}async function Hn(i,o={}){let{maxRetries:c=3,retryDelay:f=1000,isRetryable:u=()=>!0,fallback:g}=o,h=Error("Unknown error occurred");for(let d=0;d<=c;d++)try{return await i()}catch(p){if(h=p instanceof Error?p:Error(String(p)),d===c||!u(h))break;if(f>0)await new Promise((y)=>setTimeout(y,f))}if(g!==void 0)return g;throw h instanceof Error?h:Error(`Unknown error: ${String(h)}`)}function zn(i){return i instanceof ee}function Gi(i){return i instanceof Lt}function Yi(i){if(zn(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 Ft{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,o)=>o==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let o=i.toLowerCase();return["true","1","yes"].includes(o)}},{name:"number",canParse:(i,o)=>o==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let o=Number(i);if(Number.isNaN(o))throw TypeError(`Cannot parse "${i}" as number`);return o}},{name:"array",canParse:(i,o)=>o==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let o=JSON.parse(i);if(Array.isArray(o))return o}catch{}return i.split(",").map((o)=>o.trim())}},{name:"json",canParse:(i,o)=>o==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(o){throw Error(`Cannot parse "${i}" as JSON: ${o}`)}}}]}async applyEnvironmentVariables(i,o,c={}){let{prefix:f,useCamelCase:u=!0,useBackwardCompatibility:g=!0,customParsers:h={},verbose:d=!1,trackPerformance:p=!0}=c,y=async()=>{if(!i)return{config:o,source:{type:"environment",priority:50,timestamp:new Date}};let w=f||this.generateEnvPrefix(i),S={...o};return this.processObject(S,[],w,{useCamelCase:u,useBackwardCompatibility:g,customParsers:h,verbose:d,configName:i}),{config:S,source:{type:"environment",priority:50,timestamp:new Date}}};if(p)return Qe.track("applyEnvironmentVariables",y,{configName:i});return y()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,o){if(!o)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=h.map((w)=>this.formatEnvKey(w,f.useCamelCase)),p=`${c}_${d.join("_")}`,y=f.useBackwardCompatibility?`${c}_${h.map((w)=>w.toUpperCase()).join("_")}`:null;if(f.verbose);if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.processObject(g,h,c,f);else{let w=tt.env[p]||(y?tt.env[y]:void 0);if(w!==void 0){if(f.verbose){let S=tt.env[p]?p:y}try{i[u]=this.parseEnvironmentValue(w,typeof g,p,f.customParsers,f.configName)}catch(S){if(S instanceof kt)throw S;throw pe.envVar(p,w,typeof g,f.configName)}}}}}parseEnvironmentValue(i,o,c,f,u){for(let[g,h]of Object.entries(f))try{return h(i)}catch{continue}for(let g of this.defaultParsers)if(g.canParse(i,o))try{return g.parse(i)}catch{throw pe.envVar(c,i,`${o} (via ${g.name} parser)`,u)}return i}getEnvironmentVariables(i){let o={},c=i.toUpperCase();for(let[f,u]of Object.entries(tt.env))if(f.startsWith(c)&&u!==void 0)o[f]=u;return o}validateEnvironmentVariable(i,o,c){let f=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))f.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(c)try{this.parseEnvironmentValue(i,o,c,{})}catch(u){f.push(`Cannot parse value "${o}" as ${c}: ${u}`)}return{isValid:f.length===0,errors:f}}generateEnvVarDocs(i,o,c={}){let{prefix:f,format:u="text"}=c,g=f||this.generateEnvPrefix(i),h=[];switch(this.extractEnvVarInfo(o,[],g,h),u){case"markdown":return this.formatAsMarkdown(h,i);case"json":return JSON.stringify(h,null,2);default:return this.formatAsText(h,i)}}extractEnvVarInfo(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=`${c}_${h.map((p)=>this.formatEnvKey(p,!0)).join("_")}`;if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.extractEnvVarInfo(g,h,c,f);else f.push({key:d,type:Array.isArray(g)?"array":typeof g,description:`Configuration for ${h.join(".")}`,example:this.generateExample(g)})}}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,o){let c=`Environment Variables for ${o}:
20
-
21
- `;for(let f of i)c+=`${f.key}
22
- `,c+=` Type: ${f.type}
23
- `,c+=` Description: ${f.description}
24
- `,c+=` Example: ${f.example}
25
-
26
- `;return c}formatAsMarkdown(i,o){let c=`# Environment Variables for ${o}
27
-
28
- `;c+=`| Variable | Type | Description | Example |
29
- `,c+=`|----------|------|-------------|----------|
30
- `;for(let f of i)c+=`| \`${f.key}\` | ${f.type} | ${f.description} | \`${f.example}\` |
31
- `;return c}}function Ji(i,o){let c=Xn("process");if(typeof c>"u"||!c.env)return o;let f=c.env[i];return f!==void 0?f:o}function Gn(i,o,c={}){return Yn(i,o,c,new WeakMap)}function Yn(i,o,c,f){let{arrayMergeMode:u="replace",skipNullish:g=!1,customMerger:h}=c;if(o===null||o===void 0)return g?i:o;if(h){let d=h(i,o);if(d!==void 0)return d}if(Array.isArray(o)||Array.isArray(i))return Jn(i,o,u,f);if(!te(o)||!te(i))return o;return to(i,o,c,f)}function Jn(i,o,c,f){if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(i)&&!Array.isArray(o))return o;if(Array.isArray(o)&&Array.isArray(i))switch(c){case"replace":return o;case"concat":return Zi(i,o);case"smart":return Xi(i,o,f);default:return o}return o}function Zi(i,o){let c=[...o];for(let f of i)if(!c.some((u)=>hr(u,f)))c.push(f);return c}function Xi(i,o,c){if(o.length===0)return i;if(i.length===0)return o;if(te(o[0])&&te(i[0]))return eo(i,o,c);if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}function eo(i,o,c){let f=[...o];for(let u of i){if(!te(u)){f.push(u);continue}let g=["id","name","key","path","type"],h=!1;for(let d of g)if(d in u){if(f.find((y)=>te(y)&&(d in y)&&y[d]===u[d])){h=!0;break}}if(!h)f.push(u)}return f}function to(i,o,c,f){let u=o;if(te(u)&&f.has(u))return f.get(u);let g={...i};if(te(u))f.set(u,g);for(let h in u){if(!Object.prototype.hasOwnProperty.call(u,h))continue;let d=u[h],p=g[h];if(c.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){g[h]=d;continue}if(te(d)&&te(p))g[h]=Yn(p,d,c,f);else if(Array.isArray(d)||Array.isArray(p))g[h]=Jn(p,d,c.arrayMergeMode||"smart",f);else g[h]=d}return g}function Ar(i,o,c="replace"){return Gn(i,o,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function hr(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!hr(i[c],o[c]))return!1;return!0}if(te(i)&&te(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!hr(i[u],o[u]))return!1}return!0}return!1}function te(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Dt{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,o,c={}){let{arrayStrategy:f="replace",useCache:u=!0,cacheTtl:g,trackPerformance:h=!0,verbose:d=!1}=c;if(u){let y=Oe.getWithFileCheck("file",i);if(y){if(d)console.log(`Configuration loaded from cache: ${i}`);return y}}let p=async()=>{if(!ot(i))return null;try{let y=`?t=${Date.now()}`,w=await import(i+y),S=w.default||w,E="default"in w,v=Object.keys(w).length>0;if(!E&&!v)throw new Ve(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof S!=="object"||S===null||Array.isArray(S))throw new Ve(i,Error("Configuration must export a valid object"),"unknown");let A={config:Ar(o,S,f),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)Oe.setWithFileCheck("file",A,i,g);return A}catch(y){throw y instanceof Error?pe.configLoad(i,y):pe.configLoad(i,Error(String(y)))}};if(h)return Qe.track("loadFromPath",p,{path:i});return p()}async tryLoadFromPaths(i,o,c={}){for(let f of i)try{let u=await this.loadFromPath(f,o,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 ${f}:`,u)}return null}generateConfigPaths(i,o,c){let f=this.generateNamePatterns(i,c),u=[];for(let g of f)for(let h of this.extensions)u.push(Xt(o,`${g}${h}`));return u}generateNamePatterns(i,o){let c=[];if(c.push("config",".config"),i)c.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(o){if(c.push(o,`.${o}.config`,`${o}.config`,`.${o}`),i)c.push(`${i}.${o}.config`,`.${i}.${o}.config`)}return c.filter(Boolean)}checkFileAccess(i){return Hn(async()=>ot(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,o,c){let f=[];if(!ot(i))return f;if(o||c){let u=this.generateNamePatterns(o||"",c);for(let g of u)for(let h of this.extensions){let d=Xt(i,`${g}${h}`);if(await this.checkFileAccess(d))f.push(d)}}else try{let{readdirSync:u}=await import("fs"),g=u(i);for(let h of g)if(this.looksLikeConfigFile(h)){let d=Xt(i,h);if(await this.checkFileAccess(d))f.push(d)}}catch{return[]}return f}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 o=[];try{if(!ot(i))return o.push("Configuration file does not exist"),o;let c=await import(i),f=c.default||c;if(f===void 0)o.push("Configuration file must export a default value or named exports");else if(typeof f!=="object"||f===null)o.push("Configuration must be an object");else if(Array.isArray(f))o.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),g=u(i,"utf8");JSON.parse(g)}catch(u){o.push(`Invalid JSON syntax: ${u}`)}}catch(c){o.push(`Failed to load configuration file: ${c}`)}return o}async getFileModificationTime(i){try{let{statSync:o}=await import("fs");return o(i).mtime}catch{return null}}async preloadConfigurations(i,o={}){let c=new Map;return await Promise.allSettled(i.map(async(f)=>{try{let u=await this.loadFromPath(f,{},o);if(u)c.set(f,u.config)}catch(u){if(o.verbose)console.warn(`Failed to preload ${f}:`,u)}})),c}}class Lr{async validateConfiguration(i,o,c={}){let{stopOnFirstError:f=!1,validateRequired:u=!0,validateTypes:g=!0,customRules:h=[],trackPerformance:d=!0,verbose:p=!1}=c,y=async()=>{let w=[],S=[],E={stopOnFirstError:f,validateRequired:u,validateTypes:g,customRules:h,trackPerformance:d,verbose:p};try{if(typeof o==="string")return await this.validateWithSchemaFile(i,o,E);else if(Array.isArray(o))return this.validateWithRules(i,[...o,...h],E);else return this.validateWithJSONSchema(i,o,E)}catch(v){return w.push({path:"",message:`Validation failed: ${v}`,rule:"system"}),{isValid:!1,errors:w,warnings:S}}};if(d)return await Qe.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,o,c){try{if(!pi(o))throw new We(o,[{path:"",message:"Schema file does not exist"}]);let f=await import(o),u=f.default||f;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(f){throw new We(o,[{path:"",message:`Failed to load schema: ${f}`}])}}validateWithJSONSchema(i,o,c){let f=[],u=[];return this.validateObjectAgainstSchema(i,o,"",f,u,c),{isValid:f.length===0,errors:f,warnings:u}}validateObjectAgainstSchema(i,o,c,f,u,g){if(g.validateTypes&&o.type){let h=Array.isArray(i)?"array":typeof i,d=Array.isArray(o.type)?o.type:[o.type];if(!d.includes(h)){if(f.push({path:c,message:`Expected type ${d.join(" or ")}, got ${h}`,expected:d.join(" or "),actual:h,rule:"type"}),g.stopOnFirstError)return}}if(o.enum&&!o.enum.includes(i)){if(f.push({path:c,message:`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"}),g.stopOnFirstError)return}if(typeof i==="string"){if(o.minLength!==void 0&&i.length<o.minLength)f.push({path:c,message:`String length must be at least ${o.minLength}`,expected:`>= ${o.minLength}`,actual:i.length,rule:"minLength"});if(o.maxLength!==void 0&&i.length>o.maxLength)f.push({path:c,message:`String length must not exceed ${o.maxLength}`,expected:`<= ${o.maxLength}`,actual:i.length,rule:"maxLength"});if(o.pattern){if(!new RegExp(o.pattern).test(i))f.push({path:c,message:`String does not match pattern ${o.pattern}`,expected:o.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(o.minimum!==void 0&&i<o.minimum)f.push({path:c,message:`Value must be at least ${o.minimum}`,expected:`>= ${o.minimum}`,actual:i,rule:"minimum"});if(o.maximum!==void 0&&i>o.maximum)f.push({path:c,message:`Value must not exceed ${o.maximum}`,expected:`<= ${o.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&o.items)for(let h=0;h<i.length;h++){let d=c?`${c}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema(i[h],o.items,d,f,u,g),g.stopOnFirstError&&f.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let h=i;if(g.validateRequired&&o.required){for(let d of o.required)if(!(d in h)){if(f.push({path:c?`${c}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),g.stopOnFirstError)return}}if(o.properties){for(let[d,p]of Object.entries(o.properties))if(d in h){let y=c?`${c}.${d}`:d;if(this.validateObjectAgainstSchema(h[d],p,y,f,u,g),g.stopOnFirstError&&f.length>0)return}}if(o.additionalProperties===!1){let d=new Set(Object.keys(o.properties||{}));for(let p of Object.keys(h))if(!d.has(p))u.push({path:c?`${c}.${p}`:p,message:`Additional property '${p}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,o,c){let f=[],u=[];for(let g of o)try{let h=this.getValueByPath(i,g.path),d=this.validateWithRule(h,g,g.path);if(f.push(...d),c.stopOnFirstError&&f.length>0)break}catch(h){f.push({path:g.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:f.length===0,errors:f,warnings:u}}validateWithRule(i,o,c){let f=[];if(o.required&&(i===void 0||i===null))return f.push({path:c,message:o.message||`Property '${c}' is required`,expected:"required",rule:"required"}),f;if(i===void 0||i===null)return f;if(o.type){let u=Array.isArray(i)?"array":typeof i;if(u!==o.type)f.push({path:c,message:o.message||`Expected type ${o.type}, got ${u}`,expected:o.type,actual:u,rule:"type"})}if(o.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<o.min)f.push({path:c,message:o.message||`Value must be at least ${o.min}`,expected:`>= ${o.min}`,actual:u,rule:"min"})}if(o.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>o.max)f.push({path:c,message:o.message||`Value must not exceed ${o.max}`,expected:`<= ${o.max}`,actual:u,rule:"max"})}if(o.pattern&&typeof i==="string"){if(!o.pattern.test(i))f.push({path:c,message:o.message||`Value does not match pattern ${o.pattern}`,expected:o.pattern.toString(),actual:i,rule:"pattern"})}if(o.enum&&!o.enum.includes(i))f.push({path:c,message:o.message||`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"});if(o.validator){let u=o.validator(i);if(u)f.push({path:c,message:o.message||u,rule:"custom"})}return f}getValueByPath(i,o){if(!o)return i;let c=o.split("."),f=i;for(let u of c)if(f&&typeof f==="object"&&u in f)f=f[u];else return;return f}generateRulesFromInterface(i){let o=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let f of c){let[,u,g,h]=f;o.push({path:u,required:!g,type:this.mapTypeScriptType(h)})}return o}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:ss},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class kr{fileLoader=new Dt;envProcessor=new Ft;validator=new Lr;async loadConfig(i){let o=Date.now(),{cache:c,performance:f,schema:u,validate:g,...h}=i;try{if(c?.enabled){let p=this.checkCache(h.name||"",h);if(p)return p}let d;try{d=await this.loadConfigurationStrategies(h,!0,c)}catch(p){let y=h.__strictErrorHandling;if(p instanceof Error&&p.name==="ConfigNotFoundError"){if(y)throw p;d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(p instanceof Error&&p.name==="ConfigLoadError"){let w=p.message.includes("EACCES")||p.message.includes("EPERM")||p.message.includes("permission denied"),S=!w&&(p.message.includes("syntax")||p.message.includes("Expected")||p.message.includes("Unexpected")||p.message.includes("BuildMessage")||p.message.includes("errors building")),E=p.message.includes("Configuration must export a valid object")||p.message.includes("Configuration file is empty and exports nothing");if(y&&(E||w))throw p;if(S&&(!y||!E))d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${p.message}`]};else throw p}else d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${p instanceof Error?p.message:String(p)}`]}}if(u||g)await this.validateConfiguration(d.config,u,g,h.name);if(c?.enabled&&d)this.cacheResult(h.name||"",d,c,h);if(f?.enabled){let p={operation:"loadConfig",duration:Date.now()-o,configName:h.name,timestamp:new Date};if(f.onMetrics)f.onMetrics(p);if(f.slowThreshold&&p.duration>f.slowThreshold)oe.warn(`Slow configuration loading detected: ${p.duration}ms for ${h.name}`);d.metrics=p}return d}catch(d){let p=Date.now()-o;throw oe.error(`Configuration loading failed after ${p}ms:`,[d instanceof Error?d:Error(String(d))]),d}}async loadConfigurationStrategies(i,o=!1,c){let{name:f="",alias:u,cwd:g,configDir:h,defaultConfig:d,checkEnv:p=!0,arrayStrategy:y="replace",verbose:w=!1}=i,S=g||we.cwd(),E=[],v=await this.loadLocalConfiguration(f,u,S,h,d,y,w,p,c);if(v)return E.push(...this.getLocalSearchPaths(f,u,S,h)),this.finalizeResult(v,E,p,f,w);let x=await this.loadHomeConfiguration(f,u,d,y,w,p);if(x)return E.push(...this.getHomeSearchPaths(f,u)),this.finalizeResult(x,E,p,f,w);let C=await this.loadPackageJsonConfiguration(f,u,S,d,y,w,p);if(C)return E.push(J(S,"package.json")),this.finalizeResult(C,E,p,f,w);if(E.push(...this.getAllSearchPaths(f,u,S,h)),o)throw pe.configNotFound(f,E,u);return{...await this.applyEnvironmentVariables(f,d,p,w),warnings:[`No configuration file found for "${f}"${u?` or alias "${u}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,o,c,f,u,g,h,d,p){let y=d?Me(i,u,h):u,w=this.getLocalDirectories(c,f);for(let S of w){if(h)oe.info(`Searching for configuration in: ${S}`);let E=this.fileLoader.generateConfigPaths(i,S,o),v=await this.fileLoader.tryLoadFromPaths(E,y,{arrayStrategy:g,verbose:h,cacheTtl:p?.ttl,useCache:!p?.ttl||p.ttl>100});if(v){if(h)oe.success(`Configuration loaded from: ${v.source.path}`);return v}}return null}async loadHomeConfiguration(i,o,c,f,u,g){if(!i)return null;let h=g?Me(i,c,u):c,d=[J(Se(),".config",i),J(Se(),".config"),Se()];for(let p of d){if(u)oe.info(`Checking home directory: ${p}`);let y=this.fileLoader.generateConfigPaths(i,p,o),w=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:u});if(w){if(u)oe.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(i,o,c,f,u,g,h){let d=h?Me(i,f,g):f;try{let p=J(c,"package.json");if(!fr(p))return null;let y=await import(p),w=y[i],S=i;if(!w&&o)w=y[o],S=o;if(w&&typeof w==="object"&&!Array.isArray(w)){if(g)oe.success(`Configuration loaded from package.json: ${S}`);return{config:Ar(d,w,u),source:{type:"package.json",path:p,priority:30,timestamp:new Date}}}}catch(p){if(g)oe.warn("Failed to load package.json:",[p instanceof Error?p:Error(String(p))])}return null}async applyEnvironmentVariables(i,o,c,f){if(!c||!i||typeof o!=="object"||o===null||Array.isArray(o))return{config:o,source:{type:"default",priority:10,timestamp:new Date}};return{config:Me(i,o,f),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,o,c,f,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,o,c,f){let u=[];if(c){let g=c(i);if(g)u.push(...g)}if(o){let g=await this.validator.validateConfiguration(i,o);if(!g.isValid)u.push(...g.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(u.length>0)throw pe.configValidation(f||"unknown",u,f)}checkCache(i,o){let c=this.generateCacheKey(i,o);return Oe.get(c)||null}cacheResult(i,o,c,f){let u=this.generateCacheKey(i,f);Oe.set(u,o,void 0,c.ttl)}generateCacheKey(i,o){let c=[i];if(o.alias)c.push(`alias:${o.alias}`);if(o.cwd)c.push(`cwd:${o.cwd}`);if(o.configDir)c.push(`configDir:${o.configDir}`);if("checkEnv"in o)c.push(`checkEnv:${o.checkEnv}`);return c.join("|")}getLocalDirectories(i,o){return Array.from(new Set([i,J(i,"config"),J(i,".config"),o?J(i,o):void 0].filter(Boolean)))}getAllSearchPaths(i,o,c,f){let u=[];return u.push(...this.getLocalSearchPaths(i,o,c,f)),u.push(...this.getHomeSearchPaths(i,o)),u.push(J(c,"package.json")),u}getLocalSearchPaths(i,o,c,f){let u=this.getLocalDirectories(c,f),g=[];for(let h of u)g.push(...this.fileLoader.generateConfigPaths(i,h,o));return g}getHomeSearchPaths(i,o){if(!i)return[];let c=[J(Se(),".config",i),J(Se(),".config"),Se()],f=[];for(let u of c)f.push(...this.fileLoader.generateConfigPaths(i,u,o));return f}async loadConfigWithResult(i){return this.loadConfig(i)}}function $n(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")),f=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return c||f}async function ro(i){return de.loadConfig({...i,__strictErrorHandling:!0})}async function Zn(i){let o="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let f;if(c)f=await de.loadConfig(i);else f=await de.loadConfig({...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}});return f?.config??o}catch(f){let u=f instanceof Error?f.name:"UnknownError",g=f instanceof Error?f.message:String(f);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||g.includes("config"))&&i.verbose)oe.warn("Unexpected error loading config, using defaults:",[f instanceof Error?f:Error(String(f))]);let d=c?{...i,defaultConfig:o}:{...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await de.applyEnvironmentVariables(d.name||"",o,!0,d.verbose||!1))?.config??o;return o}}async function no(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:o}=await import("process");try{return(await de.loadConfig({name:i,cwd:o(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(c){if(c instanceof Error&&(c.name==="ConfigNotFoundError"||c.name==="ConfigLoadError"&&$n(c)))return(await de.applyEnvironmentVariables(i,{},!0,!1)).config;throw c}}try{return(await de.loadConfig({...i,cwd:i.cwd||we.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(o){if(o instanceof Error&&(o.name==="ConfigNotFoundError"||o.name==="ConfigLoadError"&&$n(o)))return(await de.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw o}}async function so(i,o,c="replace"){let f=new Dt;try{let u=await f.loadFromPath(i,o,{arrayStrategy:c,useCache:!1,trackPerformance:!1});return u?u.config:null}catch{return null}}function Me(i,o,c=!1){let f=new Ft,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function g(h,d=[]){let p={...h};for(let[y,w]of Object.entries(h)){let S=[...d,y],E=[`${u}_${S.join("_").toUpperCase()}`,`${u}_${S.map((C)=>C.toUpperCase()).join("")}`,`${u}_${S.map((C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],v,x;for(let C of E)if(v=we.env[C],v!==void 0){x=C;break}if(v!==void 0&&x)if(typeof w==="boolean")p[y]=["true","1","yes"].includes(v.toLowerCase());else if(typeof w==="number"){let C=Number(v);if(!Number.isNaN(C))p[y]=C}else if(Array.isArray(w))try{p[y]=JSON.parse(v)}catch{p[y]=v.split(",").map((C)=>C.trim())}else p[y]=v;else if(w&&typeof w==="object"&&!Array.isArray(w))p[y]=g(w,S)}return p}return g(o)}function io(i){let o=J(we.cwd(),i.configDir),c=J(we.cwd(),i.generatedDir),f=J(c,"config-types.ts");if(!fr(Hr(f)))Hs(Hr(f),{recursive:!0,mode:511});let u=fr(o)?zs(o).map((h)=>h.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],g=`// Generated by bunfig v${Do}
32
- export type ConfigNames = ${u.length?`'${u.join("' | '")}'`:"string"}
33
- `;Gs(f,g,{mode:438})}function oo(i){let o=null,c=null,f=()=>{if(!c)c=Zn(i).then((g)=>(o=g,g),(g)=>{let h="defaultConfig"in i?i.defaultConfig:{};if(o=h,"verbose"in i&&i.verbose)oe.warn("Config loading failed, using defaults:",[g instanceof Error?g:Error(String(g))]);return h});return c},u="defaultConfig"in i?i.defaultConfig:{};return o=u,f(),new Proxy({},{get(g,h){if(o)return o[h];let d=u[h];return f(),d},has(g,h){return h in(o||u)},ownKeys(){return Object.keys(o||u)},getOwnPropertyDescriptor(g,h){return Object.getOwnPropertyDescriptor(o||u,h)},set(g,h,d){if(!o)o={...u};return o[h]=d,!0}})}function ao(i){let o=ln(bi.cwd(),i?.configDir||"./config");function c(){if(!yi(o))return[];let u=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),g=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],h=wi(o).filter((p)=>u.has(er(p))).map((p)=>({base:p.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:p})),d=new Map;for(let{base:p,file:y}of h){let w=er(y).toLowerCase(),S=d.get(p);if(!S){d.set(p,y);continue}let E=er(S).toLowerCase();if(g.indexOf(w)<g.indexOf(E))d.set(p,y)}return Array.from(d.entries()).map(([p,y])=>({base:p,file:y})).sort((p,y)=>p.base.localeCompare(y.base))}function f(){let u=c(),g=u.map((y)=>y.base),h=g.length?g.map((y)=>`'${y}'`).join(" | "):"string",d=u.length?`{
34
- ${u.map((y)=>{let w=ln(o,y.file).replace(/\\/g,"/");return` '${y.base}': typeof import('${w}').default`}).join(`,
35
- `)}
36
- }`:"Record<string, any>";return`export type ConfigNames = ${h}
37
- export type ConfigByName = ${d}
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$/},(g)=>({path:g.path,namespace:"bunfig-virtual"})),u.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:f(),loader:"ts"}))}}}var Xn,Oe,Qe,es,co,lo,Cn,mt,gr,z,I,fo,xn,uo,Tn,ho,go,sr,mo,An,Ln,ir,po,yo,wo,bo,pt,ts,So,G,vo,Eo,kn,yt,dr,W,L,$o,Rn,Co,On,xo,To,or,Ao,Pn,Nn,Lo,ar,ko,Ro,Oo,Po,No,wt,rs,Fo,Do="0.15.6",ee,Lt,Ve,mr,pr,kt,yr,wr,We,br,Sr,pe,ns,ss,oe,de,is,os,Io=Di(async()=>{Xn=import.meta.require,Oe=new $r,Qe=new Cr,es={createKey:Ii,isEquivalent:_i,estimateMemoryUsage:Mi},co=Et(ur.cwd(),"config"),lo=Et(ur.cwd(),"src/generated"),Cn=vt.env.CLARITY_LOG_DIR||Zs(Ki(),"logs"),mt={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Cn,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},gr=await Vi(),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`,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"},I=z,fo=z.red,xn=z.green,uo=z.yellow,Tn=z.blue,ho=z.magenta,go=z.cyan,sr=z.white,mo=z.gray,An=z.bgRed,Ln=z.bgYellow,ir=z.bold,po=z.dim,yo=z.italic,wo=z.underline,bo=z.reset,pt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ts={debug:"\uD83D\uDD0D",info:Tn("\u2139"),success:xn("\u2713"),warning:Ln(sr(ir(" WARN "))),error:An(sr(ir(" ERROR ")))},So=new xt("stacks"),G=new xt("bunfig",{showTags:!0}),vo=Y(Be.cwd(),"config"),Eo=Y(Be.cwd(),"src/generated"),kn=St.env.CLARITY_LOG_DIR||Ys(qi(),"logs"),yt={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:kn,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},dr=await Hi(),W={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"},L=W,$o=W.red,Rn=W.green,Co=W.yellow,On=W.blue,xo=W.magenta,To=W.cyan,or=W.white,Ao=W.gray,Pn=W.bgRed,Nn=W.bgYellow,Lo=W.bgGray,ar=W.bold,ko=W.dim,Ro=W.italic,Oo=W.underline,Po=W.strikethrough,No=W.reset,wt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},rs={debug:"\uD83D\uDD0D",info:On("\u2139"),success:Rn("\u2713"),warning:Nn(or(ar(" WARN "))),error:Pn(or(ar(" ERROR ")))},Fo=new At("stacks"),ee=class extends Error{timestamp;context;constructor(o,c={}){super(o);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 o=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([c,f])=>`${c}: ${f}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${o}`}},Lt=class extends ee{code="CONFIG_NOT_FOUND";constructor(o,c,f){let u=f?` or alias "${f}"`:"";super(`Configuration "${o}"${u} not found`,{configName:o,alias:f,searchPaths:c,searchPathCount:c.length})}},Ve=class extends ee{code="CONFIG_LOAD_ERROR";constructor(o,c,f){super(`Failed to load configuration from "${o}": ${c.message}`,{configPath:o,configName:f,originalError:c.name,originalMessage:c.message});this.cause=c}},mr=class extends ee{code="CONFIG_VALIDATION_ERROR";constructor(o,c,f){super(`Configuration validation failed for "${o}"`,{configPath:o,configName:f,validationErrors:c,errorCount:c.length})}},pr=class extends ee{code="CONFIG_MERGE_ERROR";constructor(o,c,f,u){super(`Failed to merge configuration from "${o}" with "${c}": ${f.message}`,{sourcePath:o,targetPath:c,configName:u,originalError:f.name,originalMessage:f.message});this.cause=f}},kt=class extends ee{code="ENV_VAR_ERROR";constructor(o,c,f,u){super(`Failed to parse environment variable "${o}" with value "${c}" as ${f}`,{envKey:o,envValue:c,expectedType:f,configName:u})}},yr=class extends ee{code="FILE_SYSTEM_ERROR";constructor(o,c,f){super(`File system ${o} failed for "${c}": ${f.message}`,{operation:o,path:c,originalError:f.name,originalMessage:f.message});this.cause=f}},wr=class extends ee{code="TYPE_GENERATION_ERROR";constructor(o,c,f){super(`Failed to generate types from "${o}" to "${c}": ${f.message}`,{configDir:o,outputPath:c,originalError:f.name,originalMessage:f.message});this.cause=f}},We=class extends ee{code="SCHEMA_VALIDATION_ERROR";constructor(o,c,f){super(`Schema validation failed${f?` for config "${f}"`:""}`,{schemaPath:o,configName:f,validationErrors:c,errorCount:c.length})}},br=class extends ee{code="BROWSER_CONFIG_ERROR";constructor(o,c,f,u){super(`Failed to fetch configuration from "${o}": ${c} ${f}`,{endpoint:o,status:c,statusText:f,configName:u})}},Sr=class extends ee{code="PLUGIN_ERROR";constructor(o,c,f){super(`Plugin "${o}" failed during ${c}: ${f.message}`,{pluginName:o,operation:c,originalError:f.name,originalMessage:f.message});this.cause=f}},pe={configNotFound(i,o,c){return new Lt(i,o,c)},configLoad(i,o,c){return new Ve(i,o,c)},configValidation(i,o,c){return new mr(i,o,c)},configMerge(i,o,c,f){return new pr(i,o,c,f)},envVar(i,o,c,f){return new kt(i,o,c,f)},fileSystem(i,o,c){return new yr(i,o,c)},typeGeneration(i,o,c){return new wr(i,o,c)},schemaValidation(i,o,c){return new We(i,o,c)},browserConfig(i,o,c,f){return new br(i,o,c,f)},plugin(i,o,c){return new Sr(i,o,c)}},ns={replace:"replace",concat:"concat",smart:"smart"},ss=/^https?:\/\//,oe=new At("bunfig",{showTags:!0}),de=new kr,is=J(we.cwd(),"config"),os=J(we.cwd(),"src/generated")});function _o(i,o={}){let c=$t.cwd();while(c.includes("storage"))c=un(c,"..");let f=un(c,i||"");if(o?.relative)return vi($t.cwd(),f);return f}var Mo=$t.env.CLARITY_LOG_DIR||Si(_o(),"logs"),as={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Rt={...as},Vc=(async()=>{try{let{loadConfig:i}=await Io().then(()=>Qn),o=await i({name:"clarity",alias:"logging",defaultConfig:as,cwd:$t.cwd()});if(o)Object.assign(Rt,o)}catch{}return Rt})();function Q(){if(ge.env.NODE_ENV==="test"||ge.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Bo(){if(ge.env.NODE_ENV==="test"||ge.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ge<"u"){let i=ge.type;if(i==="renderer"||i==="worker")return!1;return!!(ge.versions&&(ge.versions.node||ge.versions.bun))}return!1}class cs{async format(i){let o=await Bo(),c=await this.getMetadata(o);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:o}=await import("os");return{pid:Re.pid,hostname:o(),environment:Re.env.NODE_ENV||"development",platform:Re.platform,version:Re.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Re.env.NODE_ENV||Re.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var U={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"},R=U,{red:Wc,green:jo,yellow:Qc,blue:Ko,magenta:Uc,cyan:qc,white:Fn,gray:Hc,bgRed:Vo,bgYellow:Wo,bgGray:zc,bold:Dn,dim:Gc,italic:Yc,underline:Jc,strikethrough:Zc,reset:Xc}=U,cr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Qo={debug:"\uD83D\uDD0D",info:Ko("\u2139"),success:jo("\u2713"),warning:Wo(Fn(Dn(" WARN "))),error:Vo(Fn(Dn(" ERROR ")))};class It{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,o={}){this.name=i,this.config={...Rt},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new cs,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let o={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return o[i]>=o[c]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...cr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...cr};return{...cr,...i.fingersCrossed}}normalizeOptions(i){let o={format:"json",level:"info",logDirectory:Rt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}shouldWriteToFile(){return!Q()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await Ti(this.config.logDirectory,Sn.F_OK|Sn.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await Ai(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let p=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:fe.from(i);try{if(!ct(this.currentLogFile))await nr(this.currentLogFile,"",{mode:420});if(u=bn(this.currentLogFile,"a",420),xi(u,p,{flag:"a"}),wn(u),u!==void 0)rr(u),u=void 0;if((await Ae(this.currentLogFile)).size===0){if(await nr(this.currentLogFile,p,{flag:"w",mode:420}),(await Ae(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let w=y;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(g<h-1){let S=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,S);let E=d*2**g;await new Promise((v)=>setTimeout(v,E)),g++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(u!==void 0)try{rr(u)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(p){if(g===h-1){let w=p,S=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",S),p}g++;let y=d*2**(g-1);await new Promise((w)=>setTimeout(w,y))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,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 ke(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 ke(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return ke(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(Q())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,p])=>p.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return tr(16).toString("hex")}generateKey(){return tr(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:o}=this.getCurrentKey(),c=tr(16),f=Ei("aes-256-gcm",o,c),u=fe.isBuffer(i)?i:fe.from(i,"utf8"),g=f.update(u),h=f.final(),d=g.length+h.length,p=f.getAuthTag(),y=fe.allocUnsafe(16+d+16);return c.copy(y,0),g.copy(y,16),h.copy(y,16+g.length),p.copy(y,16+d),{encrypted:y,iv:c}}async compressData(i){return new Promise((o,c)=>{let f=En(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(fe.from(fe.concat(u)))),f.on("error",c),f.write(i),f.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 o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(Q())return;if(!this.shouldWriteToFile())return;let i=await Ae(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await lt(this.config.logDirectory),g=u.filter((p)=>p.startsWith(this.name)&&/\.log\.\d+$/.test(p)).sort((p,y)=>{let w=Number.parseInt(p.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await Ae(c).catch(()=>null))try{if(await vn(c,d),o.compress)try{let p=`${d}.gz`;await this.compressLogFile(d,p),await ft(d)}catch(p){console.error("Error compressing rotated file:",p)}if(g.length===0&&!u.some((p)=>p.endsWith(".log.1")))try{let p=`${c}.1`;await nr(p,"")}catch(p){console.error("Error creating backup file:",p)}}catch(p){console.error(`Error during rotation: ${p instanceof Error?p.message:String(p)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await Ae(c).catch(()=>null))await vn(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await lt(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await ft(ke(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=yn(i),f=Ci(o),u=En();await Ri(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(f);console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(o);console.log(o)}}shouldLog(i){if(!this.enabled)return!1;let o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),ct(this.currentLogFile))try{let i=bn(this.currentLogFile,"r+");wn(i),rr(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(!Q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let o=(await lt(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await ft(ke(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}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()?R.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Q())return!1;let i=typeof N.env.NO_COLOR<"u",o=N.env.FORCE_COLOR==="0";if(i||o)return!1;return!!(typeof N.stderr<"u"&&N.stderr.isTTY||typeof N.stdout<"u"&&N.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(v)=>v.replace(this.ANSI_PATTERN,"");if(!this.fancy){let v=[];if(h)v.push(o);if(g==="warning")v.push("WARN");else if(g==="error")v.push("ERROR");else if(c)v.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)v.push(f.replace(/[[\]]/g,""));return v.push(u),v.join(" ")}let p=N.stdout.columns||120,y="";if(g==="warning"||g==="error")y=`${c} ${u}`;else if(g==="info"||g==="success")y=`${c} ${f} ${u}`;else y=`${c} ${f} ${R.cyan(u)}`;if(!h)return y.trim();let w=d(y).trim().length,S=d(o).length,E=Math.max(1,p-2-w-S);return`${y.trim()}${" ".repeat(E)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let o=i;return o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,f,u)=>{let g=R.underline(R.blue(f)),h=this.toAbsoluteFilePath(u);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let d=`file://${encodeURI(h)}`,p="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${d}\x1B\\${g}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${g}\x1B]8;;\x1B\\`;return g}),o=o.replace(/`([^`]+)`/g,(c,f)=>R.bgGray(f)),o=o.replace(/\*\*([^*]+)\*\*/g,(c,f)=>R.bold(f)),o=o.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,f)=>R.italic(f)),o=o.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,f)=>R.italic(f)),o=o.replace(/~([^~]+)~/g,(c,f)=>R.strikethrough(f)),o}supportsHyperlinks(){if(Q())return!1;let i=N.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 o=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(o)&&o>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let o=i;if(o.startsWith("file://"))o=o.replace(/^file:\/\//,"");if(o.startsWith("~")){let c=N.env.HOME||"";if(c)o=o.replace(/^~(?=$|\/)/,c)}if(Li(o)||o.startsWith("./")||o.startsWith("../"))o=ki(o);else return null;return ct(o)?o:null}catch{return null}}buildOutputTexts(i){let o=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:o,fileText:c}}async log(i,o,...c){if(!this.shouldLog(i))return;let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);let{consoleText:p,fileText:y}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let S=this.options.showIcons===!1?"":Qo[i],E=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",v;switch(i){case"debug":v=this.formatConsoleMessage({timestamp:u,icon:S,tag:E,message:R.gray(p),level:i}),console.error(v);break;case"info":v=this.formatConsoleMessage({timestamp:u,icon:S,tag:E,message:p,level:i}),console.warn(v);break;case"success":v=this.formatConsoleMessage({timestamp:u,icon:S,tag:E,message:R.green(p),level:i}),console.error(v);break;case"warning":v=this.formatConsoleMessage({timestamp:u,icon:S,tag:E,message:p,level:i}),console.warn(v);break;case"error":if(v=this.formatConsoleMessage({timestamp:u,icon:S,tag:E,message:p,level:i}),console.error(v),d){let x=d.split(`
41
- `);for(let C of x)if(C.trim()&&!C.includes(h))console.error(this.formatConsoleMessage({timestamp:u,message:R.gray(` ${C}`),level:i,showTimestamp:!1}))}break}}else if(!Q()){if(console.error(`${g} ${this.environment}.${i.toUpperCase()}: ${h}`),d)console.error(d)}let w=`${g} ${this.environment}.${i.toUpperCase()}: ${y}
42
- `;if(d)w+=`${d}
43
- `;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(i,o=""){let c={update:(d,p)=>{},finish:(d)=>{},interrupt:(d,p)=>{}};if(!this.enabled)return c;let f=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:o||"",barLength:f,lastRenderedLine:""},this.shouldStyleConsole()&&!Q()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(d,p)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,d),this.activeProgressBar.total),p!==void 0)this.activeProgressBar.message=p;if(this.shouldStyleConsole()&&!Q()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(d)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,d)},interrupt:(d,p="info")=>{if(!Q()&&N.stdout.isTTY)N.stdout.write(`
44
- `);if(this[p==="warning"?"warn":p](d),this.activeProgressBar&&this.shouldStyleConsole()&&!Q()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let o=performance.now();if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",f=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:f,icon:this.options.showIcons===!1?"":R.blue("\u25D0"),tag:c,message:`${R.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let f=performance.now(),u=Math.round(f-o),g=`${i} completed in ${u}ms`,h=new Date,d=this.formatConsoleTimestamp(h),y=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${g}`;if(c)y+=` ${JSON.stringify(c)}`;if(y+=`
45
- `,y=y.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:this.options.showIcons===!1?"":R.green("\u2713"),tag:w,message:`${g}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!Q())console.error(y.trim());if(this.shouldWriteToFile())await this.writeToFile(y)}}async debug(i,...o){await this.log("debug",i,...o)}async info(i,...o){await this.log("info",i,...o)}async success(i,...o){await this.log("success",i,...o)}async warn(i,...o){await this.log("warning",i,...o)}async error(i,...o){await this.log("error",i,...o)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:o}=i;return!!o}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let o=`${this.name}:${i}`,c=new It(o,{...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(Q())throw Error("createReadStream is not supported in browser environments");if(!ct(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return yn(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let o=this.config.rotation;if(!o.encrypt||typeof o.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 f=fe.isBuffer(i)?i:fe.from(i,"base64"),u=f.subarray(0,16),g=f.subarray(f.length-16),h=f.subarray(16,f.length-16),d=$i("aes-256-gcm",c,u);d.setAuthTag(g);let p=d.update(h),y=d.final(),w=p.length+y.length,S=fe.allocUnsafe(w);return p.copy(S,0),y.copy(S,p.length),S.toString("utf8")}catch(f){throw Error(`Decryption failed: ${f instanceof Error?f.message:String(f)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Q()}isServerMode(){return!Q()}setTestEncryptionKey(i,o){this.currentKeyId=i,this.keys.set(i,o)}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 o=new Date,c=this.formatConsoleTimestamp(o),f=this.formatFileTimestamp(o),{consoleText:u,fileText:g}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let d=u.split(`
46
- `),p=Math.max(...d.map((E)=>E.length))+2,y=`\u250C${"\u2500".repeat(p)}\u2510`,w=`\u2514${"\u2500".repeat(p)}\u2518`,S=d.map((E)=>this.formatConsoleMessage({timestamp:c,message:R.cyan(E),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:R.cyan(y),showTimestamp:!1})),S.forEach((E)=>console.error(E)),console.error(this.formatConsoleMessage({timestamp:c,message:R.cyan(w),showTimestamp:!1}))}else if(!Q())console.error(`${f} ${this.environment}.INFO: [BOX] ${g}`);let h=`${f} ${this.environment}.INFO: [BOX] ${g}
47
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}async prompt(i){if(Q())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${R.cyan("?")} ${i} (y/n) `);let c=(f)=>{let u=f.toString().trim().toLowerCase();N.stdin.removeListener("data",c);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),o(u==="y"||u==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...o){if(!this.enabled)return;let c=i;if(o&&o.length>0){let p=/%([sdijfo%])/g,y=0;if(c=i.replace(p,(w,S)=>{if(S==="%")return"%";if(y>=o.length)return w;let E=o[y++];switch(S){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return w}}),y<o.length)c+=` ${o.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:f,fileText:u}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let p=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${R.blue("\u25D0")} `;console.error(`${y}${p} ${R.cyan(f)}`)}let d=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${u}
48
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}renderProgressBar(i,o=!1){if(!this.enabled||!this.shouldStyleConsole()||!N.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=R.green("\u2501".repeat(f)),h=R.gray("\u2501".repeat(u)),d=`[${g}${h}]`,p=`${c}%`.padStart(4),y=i.message?` ${i.message}`:"",w=this.options.showIcons===!1?"":o||c===100?R.green("\u2713"):R.blue("\u25B6"),S=this.options.showTags!==!1&&this.name?` ${R.gray(this.formatTag(this.name))}`:"",E=`\r${w}${S} ${d} ${p}${y}`,v=N.stdout.columns||80,x=" ".repeat(Math.max(0,v-E.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${E}${x}`,N.stdout.write(i.lastRenderedLine),o)N.stdout.write(`
49
- `)}finishProgressBar(i,o){if(!this.enabled||!this.fancy||Q()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(o)i.message=o;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(Q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let o=await lt(this.config.logDirectory),c=[];for(let f of o){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(f):f.startsWith(this.name))||!f.endsWith(".log"))continue;let g=ke(this.config.logDirectory,f);if(i.before)try{if((await Ae(g)).mtime>=i.before)continue}catch(h){console.error(`Failed to get stats for file ${g}:`,h);continue}c.push(g)}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 f of c)try{await ft(f),console.warn(`Deleted log file: ${f}`)}catch(u){console.error(`Failed to delete log file ${f}:`,u)}console.warn("Log clearing process finished.")}catch(o){console.error("Error during log clearing process:",o)}}}var el=new It("stacks");class ae extends Error{timestamp;context;constructor(i,o={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=o,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(([o,c])=>`${o}: ${c}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class ls extends ae{code="CONFIG_NOT_FOUND";constructor(i,o,c){let f=c===void 0?[]:Array.isArray(c)?c.filter(Boolean):[c],u="";if(f.length===1)u=` or alias "${f[0]}"`;else if(f.length>1)u=` or aliases ${f.map((g)=>`"${g}"`).join(", ")}`;super(`Configuration "${i}"${u} not found`,{configName:i,alias:c,searchPaths:o,searchPathCount:o.length})}}class Ot extends ae{code="CONFIG_LOAD_ERROR";constructor(i,o,c){super(`Failed to load configuration from "${i}": ${o.message}`,{configPath:i,configName:c,originalError:o.name,originalMessage:o.message});this.cause=o}}class fs extends ae{code="CONFIG_VALIDATION_ERROR";constructor(i,o,c){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:c,validationErrors:o,errorCount:o.length})}}class us extends ae{code="CONFIG_MERGE_ERROR";constructor(i,o,c,f){super(`Failed to merge configuration from "${i}" with "${o}": ${c.message}`,{sourcePath:i,targetPath:o,configName:f,originalError:c.name,originalMessage:c.message});this.cause=c}}class Rr extends ae{code="ENV_VAR_ERROR";constructor(i,o,c,f){super(`Failed to parse environment variable "${i}" with value "${o}" as ${c}`,{envKey:i,envValue:o,expectedType:c,configName:f})}}class hs extends ae{code="FILE_SYSTEM_ERROR";constructor(i,o,c){super(`File system ${i} failed for "${o}": ${c.message}`,{operation:i,path:o,originalError:c.name,originalMessage:c.message});this.cause=c}}class gs extends ae{code="TYPE_GENERATION_ERROR";constructor(i,o,c){super(`Failed to generate types from "${i}" to "${o}": ${c.message}`,{configDir:i,outputPath:o,originalError:c.name,originalMessage:c.message});this.cause=c}}class Pt extends ae{code="SCHEMA_VALIDATION_ERROR";constructor(i,o,c){super(`Schema validation failed${c?` for config "${c}"`:""}`,{schemaPath:i,configName:c,validationErrors:o,errorCount:o.length})}}class ds extends ae{code="BROWSER_CONFIG_ERROR";constructor(i,o,c,f){super(`Failed to fetch configuration from "${i}": ${o} ${c}`,{endpoint:i,status:o,statusText:c,configName:f})}}class ms extends ae{code="PLUGIN_ERROR";constructor(i,o,c){super(`Plugin "${i}" failed during ${o}: ${c.message}`,{pluginName:i,operation:o,originalError:c.name,originalMessage:c.message});this.cause=c}}var ye={configNotFound(i,o,c){return new ls(i,o,c)},configLoad(i,o,c){return new Ot(i,o,c)},configValidation(i,o,c){return new fs(i,o,c)},configMerge(i,o,c,f){return new us(i,o,c,f)},envVar(i,o,c,f){return new Rr(i,o,c,f)},fileSystem(i,o,c){return new hs(i,o,c)},typeGeneration(i,o,c){return new gs(i,o,c)},schemaValidation(i,o,c){return new Pt(i,o,c)},browserConfig(i,o,c,f){return new ds(i,o,c,f)},plugin(i,o,c){return new ms(i,o,c)}};async function Uo(i,o={}){let{maxRetries:c=3,retryDelay:f=1000,isRetryable:u=()=>!0,fallback:g}=o,h=Error("Unknown error occurred");for(let d=0;d<=c;d++)try{return await i()}catch(p){if(h=p instanceof Error?p:Error(String(p)),d===c||!u(h))break;if(f>0)await new Promise((y)=>setTimeout(y,f))}if(g!==void 0)return g;throw h instanceof Error?h:Error(`Unknown error: ${String(h)}`)}class Or{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,o)=>o==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let o=i.toLowerCase();return["true","1","yes"].includes(o)}},{name:"number",canParse:(i,o)=>o==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let o=Number(i);if(Number.isNaN(o))throw TypeError(`Cannot parse "${i}" as number`);return o}},{name:"array",canParse:(i,o)=>o==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let o=JSON.parse(i);if(Array.isArray(o))return o}catch{}return i.split(",").map((o)=>o.trim())}},{name:"json",canParse:(i,o)=>o==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(o){throw Error(`Cannot parse "${i}" as JSON: ${o}`)}}}]}async applyEnvironmentVariables(i,o,c={}){let{prefix:f,useCamelCase:u=!0,useBackwardCompatibility:g=!0,customParsers:h={},verbose:d=!1,trackPerformance:p=!0}=c,y=async()=>{if(!i)return{config:o,source:{type:"environment",priority:50,timestamp:new Date}};let w=f||this.generateEnvPrefix(i),S={...o};return this.processObject(S,[],w,{useCamelCase:u,useBackwardCompatibility:g,customParsers:h,verbose:d,configName:i}),{config:S,source:{type:"environment",priority:50,timestamp:new Date}}};if(p)return Er.track("applyEnvironmentVariables",y,{configName:i});return y()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,o){if(!o)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=h.map((w)=>this.formatEnvKey(w,f.useCamelCase)),p=`${c}_${d.join("_")}`,y=f.useBackwardCompatibility?`${c}_${h.map((w)=>w.toUpperCase()).join("_")}`:null;if(f.verbose);if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.processObject(g,h,c,f);else{let w=ht.env[p]||(y?ht.env[y]:void 0);if(w!==void 0){if(f.verbose){let S=ht.env[p]?p:y}try{i[u]=this.parseEnvironmentValue(w,typeof g,p,f.customParsers,f.configName)}catch(S){if(S instanceof Rr)throw S;throw ye.envVar(p,w,typeof g,f.configName)}}}}}parseEnvironmentValue(i,o,c,f,u){for(let[g,h]of Object.entries(f))try{return h(i)}catch{continue}for(let g of this.defaultParsers)if(g.canParse(i,o))try{return g.parse(i)}catch{throw ye.envVar(c,i,`${o} (via ${g.name} parser)`,u)}return i}getEnvironmentVariables(i){let o={},c=i.toUpperCase();for(let[f,u]of Object.entries(ht.env))if(f.startsWith(c)&&u!==void 0)o[f]=u;return o}validateEnvironmentVariable(i,o,c){let f=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))f.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(c)try{this.parseEnvironmentValue(i,o,c,{})}catch(u){f.push(`Cannot parse value "${o}" as ${c}: ${u}`)}return{isValid:f.length===0,errors:f}}generateEnvVarDocs(i,o,c={}){let{prefix:f,format:u="text"}=c,g=f||this.generateEnvPrefix(i),h=[];switch(this.extractEnvVarInfo(o,[],g,h),u){case"markdown":return this.formatAsMarkdown(h,i);case"json":return JSON.stringify(h,null,2);default:return this.formatAsText(h,i)}}extractEnvVarInfo(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=`${c}_${h.map((p)=>this.formatEnvKey(p,!0)).join("_")}`;if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.extractEnvVarInfo(g,h,c,f);else f.push({key:d,type:Array.isArray(g)?"array":typeof g,description:`Configuration for ${h.join(".")}`,example:this.generateExample(g)})}}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,o){let c=`Environment Variables for ${o}:
50
-
51
- `;for(let f of i)c+=`${f.key}
52
- `,c+=` Type: ${f.type}
53
- `,c+=` Description: ${f.description}
54
- `,c+=` Example: ${f.example}
55
-
56
- `;return c}formatAsMarkdown(i,o){let c=`# Environment Variables for ${o}
57
-
58
- `;c+=`| Variable | Type | Description | Example |
59
- `,c+=`|----------|------|-------------|----------|
60
- `;for(let f of i)c+=`| \`${f.key}\` | ${f.type} | ${f.description} | \`${f.example}\` |
61
- `;return c}}function qo(i,o,c={}){return ps(i,o,c,new WeakMap)}function ps(i,o,c,f){let{arrayMergeMode:u="replace",skipNullish:g=!1,customMerger:h}=c;if(o===null||o===void 0)return g?i:o;if(h){let d=h(i,o);if(d!==void 0)return d}if(Array.isArray(o)||Array.isArray(i))return ys(i,o,u,f);if(!re(o)||!re(i))return o;return Yo(i,o,c,f)}function ys(i,o,c,f){if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(i)&&!Array.isArray(o))return o;if(Array.isArray(o)&&Array.isArray(i))switch(c){case"replace":return o;case"concat":return Ho(i,o);case"smart":return zo(i,o,f);default:return o}return o}function Ho(i,o){let c=[...o];for(let f of i)if(!c.some((u)=>vr(u,f)))c.push(f);return c}function zo(i,o,c){if(o.length===0)return i;if(i.length===0)return o;if(re(o[0])&&re(i[0]))return Go(i,o,c);if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}function Go(i,o,c){let f=[...o];for(let u of i){if(!re(u)){f.push(u);continue}let g=["id","name","key","path","type"],h=!1;for(let d of g)if(d in u){if(f.find((y)=>re(y)&&(d in y)&&y[d]===u[d])){h=!0;break}}if(!h)f.push(u)}return f}function Yo(i,o,c,f){let u=o;if(re(u)&&f.has(u))return f.get(u);let g={...i};if(re(u))f.set(u,g);for(let h in u){if(!Object.prototype.hasOwnProperty.call(u,h))continue;let d=u[h],p=g[h];if(c.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){g[h]=d;continue}if(re(d)&&re(p))g[h]=ps(p,d,c,f);else if(Array.isArray(d)||Array.isArray(p))g[h]=ys(p,d,c.arrayMergeMode||"smart",f);else g[h]=d}return g}function ws(i,o,c="replace"){return qo(i,o,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function vr(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!vr(i[c],o[c]))return!1;return!0}if(re(i)&&re(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!vr(i[u],o[u]))return!1}return!0}return!1}function re(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class bs{extensions=Bn;async loadFromPath(i,o,c={}){let{arrayStrategy:f="replace",useCache:u=!0,cacheTtl:g,trackPerformance:h=!0,verbose:d=!1}=c;if(u){let y=bt.getWithFileCheck("file",i);if(y){if(d)console.log(`Configuration loaded from cache: ${i}`);return y}}let p=async()=>{if(!gt(i))return null;try{let y=`?t=${Date.now()}`,w=await import(i+y),S=w.default||w,E="default"in w,v=Object.keys(w).length>0;if(!E&&!v)throw new Ot(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof S!=="object"||S===null||Array.isArray(S))throw new Ot(i,Error("Configuration must export a valid object"),"unknown");let A={config:ws(o,S,f),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)bt.setWithFileCheck("file",A,i,g);return A}catch(y){throw y instanceof Error?ye.configLoad(i,y):ye.configLoad(i,Error(String(y)))}};if(h)return Er.track("loadFromPath",p,{path:i});return p()}async tryLoadFromPaths(i,o,c={}){for(let f of i)try{let u=await this.loadFromPath(f,o,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 ${f}:`,u)}return null}generateConfigPaths(i,o,c){return Ws({name:i,directory:o,alias:c})}generateNamePatterns(i,o){return jn({name:i,alias:o})}checkFileAccess(i){return Uo(async()=>gt(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,o,c){let f=[];if(!gt(i))return f;if(o||c){let u=this.generateNamePatterns(o||"",c);for(let g of u)for(let h of this.extensions){let d=In(i,`${g}${h}`);if(await this.checkFileAccess(d))f.push(d)}}else try{let{readdirSync:u}=await import("fs"),g=u(i);for(let h of g)if(this.looksLikeConfigFile(h)){let d=In(i,h);if(await this.checkFileAccess(d))f.push(d)}}catch{return[]}return f}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 o=[];try{if(!gt(i))return o.push("Configuration file does not exist"),o;let c=await import(i),f=c.default||c;if(f===void 0)o.push("Configuration file must export a default value or named exports");else if(typeof f!=="object"||f===null)o.push("Configuration must be an object");else if(Array.isArray(f))o.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),g=u(i,"utf8");JSON.parse(g)}catch(u){o.push(`Invalid JSON syntax: ${u}`)}}catch(c){o.push(`Failed to load configuration file: ${c}`)}return o}async getFileModificationTime(i){try{let{statSync:o}=await import("fs");return o(i).mtime}catch{return null}}async preloadConfigurations(i,o={}){let c=new Map;return await Promise.allSettled(i.map(async(f)=>{try{let u=await this.loadFromPath(f,{},o);if(u)c.set(f,u.config)}catch(u){if(o.verbose)console.warn(`Failed to preload ${f}:`,u)}})),c}}var Zo=/^https?:\/\//;class Ss{async validateConfiguration(i,o,c={}){let{stopOnFirstError:f=!1,validateRequired:u=!0,validateTypes:g=!0,customRules:h=[],trackPerformance:d=!0,verbose:p=!1}=c,y=async()=>{let w=[],S=[],E={stopOnFirstError:f,validateRequired:u,validateTypes:g,customRules:h,trackPerformance:d,verbose:p};try{if(typeof o==="string")return await this.validateWithSchemaFile(i,o,E);else if(Array.isArray(o))return this.validateWithRules(i,[...o,...h],E);else return this.validateWithJSONSchema(i,o,E)}catch(v){return w.push({path:"",message:`Validation failed: ${v}`,rule:"system"}),{isValid:!1,errors:w,warnings:S}}};if(d)return await Er.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,o,c){try{if(!Jo(o))throw new Pt(o,[{path:"",message:"Schema file does not exist"}]);let f=await import(o),u=f.default||f;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(f){throw new Pt(o,[{path:"",message:`Failed to load schema: ${f}`}])}}validateWithJSONSchema(i,o,c){let f=[],u=[];return this.validateObjectAgainstSchema(i,o,"",f,u,c),{isValid:f.length===0,errors:f,warnings:u}}validateObjectAgainstSchema(i,o,c,f,u,g){if(g.validateTypes&&o.type){let h=Array.isArray(i)?"array":typeof i,d=Array.isArray(o.type)?o.type:[o.type];if(!d.includes(h)){if(f.push({path:c,message:`Expected type ${d.join(" or ")}, got ${h}`,expected:d.join(" or "),actual:h,rule:"type"}),g.stopOnFirstError)return}}if(o.enum&&!o.enum.includes(i)){if(f.push({path:c,message:`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"}),g.stopOnFirstError)return}if(typeof i==="string"){if(o.minLength!==void 0&&i.length<o.minLength)f.push({path:c,message:`String length must be at least ${o.minLength}`,expected:`>= ${o.minLength}`,actual:i.length,rule:"minLength"});if(o.maxLength!==void 0&&i.length>o.maxLength)f.push({path:c,message:`String length must not exceed ${o.maxLength}`,expected:`<= ${o.maxLength}`,actual:i.length,rule:"maxLength"});if(o.pattern){if(!new RegExp(o.pattern).test(i))f.push({path:c,message:`String does not match pattern ${o.pattern}`,expected:o.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(o.minimum!==void 0&&i<o.minimum)f.push({path:c,message:`Value must be at least ${o.minimum}`,expected:`>= ${o.minimum}`,actual:i,rule:"minimum"});if(o.maximum!==void 0&&i>o.maximum)f.push({path:c,message:`Value must not exceed ${o.maximum}`,expected:`<= ${o.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&o.items)for(let h=0;h<i.length;h++){let d=c?`${c}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema(i[h],o.items,d,f,u,g),g.stopOnFirstError&&f.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let h=i;if(g.validateRequired&&o.required){for(let d of o.required)if(!(d in h)){if(f.push({path:c?`${c}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),g.stopOnFirstError)return}}if(o.properties){for(let[d,p]of Object.entries(o.properties))if(d in h){let y=c?`${c}.${d}`:d;if(this.validateObjectAgainstSchema(h[d],p,y,f,u,g),g.stopOnFirstError&&f.length>0)return}}if(o.additionalProperties===!1){let d=new Set(Object.keys(o.properties||{}));for(let p of Object.keys(h))if(!d.has(p))u.push({path:c?`${c}.${p}`:p,message:`Additional property '${p}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,o,c){let f=[],u=[];for(let g of o)try{let h=this.getValueByPath(i,g.path),d=this.validateWithRule(h,g,g.path);if(f.push(...d),c.stopOnFirstError&&f.length>0)break}catch(h){f.push({path:g.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:f.length===0,errors:f,warnings:u}}validateWithRule(i,o,c){let f=[];if(o.required&&(i===void 0||i===null))return f.push({path:c,message:o.message||`Property '${c}' is required`,expected:"required",rule:"required"}),f;if(i===void 0||i===null)return f;if(o.type){let u=Array.isArray(i)?"array":typeof i;if(u!==o.type)f.push({path:c,message:o.message||`Expected type ${o.type}, got ${u}`,expected:o.type,actual:u,rule:"type"})}if(o.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<o.min)f.push({path:c,message:o.message||`Value must be at least ${o.min}`,expected:`>= ${o.min}`,actual:u,rule:"min"})}if(o.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>o.max)f.push({path:c,message:o.message||`Value must not exceed ${o.max}`,expected:`<= ${o.max}`,actual:u,rule:"max"})}if(o.pattern&&typeof i==="string"){if(!o.pattern.test(i))f.push({path:c,message:o.message||`Value does not match pattern ${o.pattern}`,expected:o.pattern.toString(),actual:i,rule:"pattern"})}if(o.enum&&!o.enum.includes(i))f.push({path:c,message:o.message||`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"});if(o.validator){let u=o.validator(i);if(u)f.push({path:c,message:o.message||u,rule:"custom"})}return f}getValueByPath(i,o){if(!o)return i;let c=o.split("."),f=i;for(let u of c)if(f&&typeof f==="object"&&u in f)f=f[u];else return;return f}generateRulesFromInterface(i){let o=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let f of c){let[,u,g,h]=f;o.push({path:u,required:!g,type:this.mapTypeScriptType(h)})}return o}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:Zo},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ie=new It("bunfig",{showTags:!0});function Xo(i){if(!i)return"";let o=Array.isArray(i)?i.filter(Boolean):[i];if(o.length===0)return"";if(o.length===1)return` or alias "${o[0]}"`;return` or aliases ${o.map((c)=>`"${c}"`).join(", ")}`}class vs{fileLoader=new bs;envProcessor=new Or;validator=new Ss;async loadConfig(i){let o=Date.now(),{cache:c,performance:f,schema:u,validate:g,...h}=i;try{if(c?.enabled){let p=this.checkCache(h.name||"",h);if(p)return p}let d;try{d=await this.loadConfigurationStrategies(h,!0,c)}catch(p){if(h.configFile)throw p;let y=h.__strictErrorHandling;if(p instanceof Error&&p.name==="ConfigNotFoundError"){if(y)throw p;d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(p instanceof Error&&p.name==="ConfigLoadError"){let w=p.message.includes("EACCES")||p.message.includes("EPERM")||p.message.includes("permission denied"),S=!w&&(p.message.includes("syntax")||p.message.includes("Expected")||p.message.includes("Unexpected")||p.message.includes("BuildMessage")||p.message.includes("errors building")),E=p.message.includes("Configuration must export a valid object")||p.message.includes("Configuration file is empty and exports nothing");if(y&&(E||w))throw p;if(S&&(!y||!E))d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${p.message}`]};else throw p}else d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${p instanceof Error?p.message:String(p)}`]}}if(u||g)await this.validateConfiguration(d.config,u,g,h.name);if(c?.enabled&&d)this.cacheResult(h.name||"",d,c,h);if(f?.enabled){let p={operation:"loadConfig",duration:Date.now()-o,configName:h.name,timestamp:new Date};if(f.onMetrics)f.onMetrics(p);if(f.slowThreshold&&p.duration>f.slowThreshold)ie.warn(`Slow configuration loading detected: ${p.duration}ms for ${h.name}`);d.metrics=p}return d}catch(d){if(d instanceof Error&&d.name==="ConfigNotFoundError")throw d;let p=Date.now()-o;throw ie.error(`Configuration loading failed after ${p}ms:`,[d instanceof Error?d:Error(String(d))]),d}}async loadConfigurationStrategies(i,o=!1,c){let{name:f="",alias:u,configFile:g,cwd:h,configDir:d,defaultConfig:p,checkEnv:y=!0,arrayStrategy:w="replace",verbose:S=!1}=i,E=h||Nt.cwd(),v=[];if(g){let K=ce(E,g);v.push(K);let ne=y?Ne(f,p,S):p,Z=await this.fileLoader.tryLoadFromPaths([K],ne,{arrayStrategy:w,verbose:S,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(!Z)throw ye.configNotFound(f||g,v,u);if(S)ie.success(`Configuration loaded from explicit path: ${K}`);return this.finalizeResult(Z,v,y,f,S)}let x=await this.loadLocalConfiguration(f,u,E,d,p,w,S,y,c);if(x)return v.push(...this.getLocalSearchPaths(f,u,E,d)),this.finalizeResult(x,v,y,f,S);let C=await this.loadHomeConfiguration(f,u,p,w,S,y);if(C)return v.push(...this.getHomeSearchPaths(f,u)),this.finalizeResult(C,v,y,f,S);let A=await this.loadPackageJsonConfiguration(f,u,E,p,w,S,y);if(A)return v.push(ce(E,"package.json")),this.finalizeResult(A,v,y,f,S);if(v.push(...this.getAllSearchPaths(f,u,E,d)),o)throw ye.configNotFound(f,v,u);return{...await this.applyEnvironmentVariables(f,p,y,S),warnings:[`No configuration file found for "${f}"${Xo(u)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,o,c,f,u,g,h,d,p){let y=d?Ne(i,u,h):u,w=this.getLocalDirectories(c,f);for(let S of w){if(h)ie.info(`Searching for configuration in: ${S}`);let E=this.fileLoader.generateConfigPaths(i,S,o),v=await this.fileLoader.tryLoadFromPaths(E,y,{arrayStrategy:g,verbose:h,cacheTtl:p?.ttl,useCache:!p?.ttl||p.ttl>100});if(v){if(h)ie.success(`Configuration loaded from: ${v.source.path}`);return v}}return null}async loadHomeConfiguration(i,o,c,f,u,g){if(!i)return null;let h=g?Ne(i,c,u):c,d=[ce(be(),".config",i),ce(be(),".config"),be()];for(let p of d){if(u)ie.info(`Checking home directory: ${p}`);let y=this.fileLoader.generateConfigPaths(i,p,o),w=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:u});if(w){if(u)ie.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(i,o,c,f,u,g,h){let d=h?Ne(i,f,g):f;try{let p=ce(c,"package.json");if(!Us(p))return null;let y={};try{y=JSON.parse(qs(p,"utf8"))}catch(E){if(g)ie.warn("Failed to parse package.json:",[E instanceof Error?E:Error(String(E))]);return null}let w=y[i],S=i;if(!w&&o){let E=Array.isArray(o)?o:[o];for(let v of E){if(!v)continue;if(y[v]){w=y[v],S=v;break}}}if(w&&typeof w==="object"&&!Array.isArray(w)){if(g)ie.success(`Configuration loaded from package.json: ${S}`);return{config:ws(d,w,u),source:{type:"package.json",path:p,priority:30,timestamp:new Date}}}}catch(p){if(g)ie.warn("Failed to load package.json:",[p instanceof Error?p:Error(String(p))])}return null}async applyEnvironmentVariables(i,o,c,f){if(!c||!i||typeof o!=="object"||o===null||Array.isArray(o))return{config:o,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ne(i,o,f),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,o,c,f,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,o,c,f){let u=[];if(c){let g=c(i);if(g)u.push(...g)}if(o){let g=await this.validator.validateConfiguration(i,o);if(!g.isValid)u.push(...g.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(u.length>0)throw ye.configValidation(f||"unknown",u,f)}checkCache(i,o){let c=this.generateCacheKey(i,o);return bt.get(c)||null}cacheResult(i,o,c,f){let u=this.generateCacheKey(i,f);bt.set(u,o,void 0,c.ttl)}generateCacheKey(i,o){let c=[i];if(o.alias){let f=Array.isArray(o.alias)?o.alias.join(","):o.alias;c.push(`alias:${f}`)}if(o.cwd)c.push(`cwd:${o.cwd}`);if(o.configFile)c.push(`configFile:${o.configFile}`);if(o.configDir)c.push(`configDir:${o.configDir}`);if("checkEnv"in o)c.push(`checkEnv:${o.checkEnv}`);return c.join("|")}getLocalDirectories(i,o){return Qs({cwd:i,configDir:o})}getAllSearchPaths(i,o,c,f){let u=[];return u.push(...this.getLocalSearchPaths(i,o,c,f)),u.push(...this.getHomeSearchPaths(i,o)),u.push(ce(c,"package.json")),u}getLocalSearchPaths(i,o,c,f){let u=this.getLocalDirectories(c,f),g=[];for(let h of u)g.push(...this.fileLoader.generateConfigPaths(i,h,o));return g}getHomeSearchPaths(i,o){if(!i)return[];let c=[ce(be(),".config",i),ce(be(),".config"),be()],f=[];for(let u of c)f.push(...this.fileLoader.generateConfigPaths(i,u,o));return f}async loadConfigWithResult(i){return this.loadConfig(i)}}var lr=new vs;async function Es(i){let o="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let f;if(c)f=await lr.loadConfig(i);else f=await lr.loadConfig({...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}});return f?.config??o}catch(f){if(i.configFile)throw f;let u=f instanceof Error?f.name:"UnknownError",g=f instanceof Error?f.message:String(f);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||g.includes("config"))&&i.verbose)ie.warn("Unexpected error loading config, using defaults:",[f instanceof Error?f:Error(String(f))]);let d=c?{...i,defaultConfig:o}:{...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await lr.applyEnvironmentVariables(d.name||"",o,!0,d.verbose||!1))?.config??o;return o}}function Ne(i,o,c=!1){let f=new Or,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function g(h,d=[]){let p={...h};for(let[y,w]of Object.entries(h)){let S=[...d,y],E=[`${u}_${S.join("_").toUpperCase()}`,`${u}_${S.map((C)=>C.toUpperCase()).join("")}`,`${u}_${S.map((C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],v,x;for(let C of E)if(v=Nt.env[C],v!==void 0){x=C;break}if(v!==void 0&&x)if(typeof w==="boolean")p[y]=["true","1","yes"].includes(v.toLowerCase());else if(typeof w==="number"){let C=Number(v);if(!Number.isNaN(C))p[y]=C}else if(Array.isArray(w))try{p[y]=JSON.parse(v)}catch{p[y]=v.split(",").map((C)=>C.trim())}else p[y]=v;else if(w&&typeof w==="object"&&!Array.isArray(w))p[y]=g(w,S)}return p}return g(o)}var il=ce(Nt.cwd(),"config"),ol=ce(Nt.cwd(),"src/generated");function n(i=e.dialect){return i==="mysql"||i==="singlestore"||i==="vitess"}var nt={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}},Ts=new Set(["__proto__","constructor","prototype"]);function Cs(i){if(i===null||typeof i!=="object"||Array.isArray(i))return!1;let o=Object.getPrototypeOf(i);return o===Object.prototype||o===null}function Pr(i,o,c=new Set){let f={...i};c.add(o);for(let u of Object.keys(o)){if(Ts.has(u))continue;let g=o[u];if(Cs(g)&&!c.has(g)){let h=f[u];f[u]=Pr(Cs(h)?h:{},g,c)}else f[u]=g}return c.delete(o),f}var ea=Symbol.for("bun-query-builder.config"),e=globalThis[ea]??=Pr({},nt),ta=Symbol.for("bun-query-builder.config-state"),_t=globalThis[ta]??={explicit:new Set,fileLoaded:!1};function P(i){if(i)return rt(i);let o=$s.env.DB_DIALECT||$s.env.DB_CONNECTION;if(o)return rt(o);return e.dialect||"postgres"}function rt(i){let o=i.trim().toLowerCase();if(o==="turso"||o==="libsql")return"sqlite";return o}function t(i){if(e.dialect==="postgres")return`$${i}`;return"?"}function s(i,o=1){if(i<=0)return"";if(e.dialect==="postgres"){let c=`$${o}`;for(let f=1;f<i;f++)c+=`, $${o+f}`;return c}return i===1?"?":`?${", ?".repeat(i-1)}`}async function B(){if(!_t.fileLoaded){_t.fileLoaded=!0;let i=await Es({name:"query-builder",alias:"qb",defaultConfig:nt}),o={};for(let[c,f]of Object.entries(i??{}))if(!_t.explicit.has(c))o[c]=f;As(o)}return e}var Ue=null,xs=new Set;function As(i){let o=Pr(e,i),c=e;for(let f of Object.keys(o)){if(Ts.has(f))continue;c[f]=o[f]}}function _e(i){if(i.dialect&&Ue&&i.dialect!==Ue){let o=`${Ue}->${i.dialect}`;if(!xs.has(o))xs.add(o),console.warn(`[query-builder] Configuring dialect '${i.dialect}' overrides the previously configured dialect '${Ue}'. 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)Ue=i.dialect;for(let o of Object.keys(i))_t.explicit.add(o);As(i)}function dn(i){return i}function it(i){return typeof i==="string"&&/^(?:libsql|https?|wss?):\/\//i.test(i.trim())}function fn(i){let o;try{o=new URL(i.trim())}catch{throw new a("Invalid libSQL URL: expected libsql://, https://, http://, ws:// or wss://",{code:"LIBSQL_INVALID_URL"})}let c=o.protocol.replace(/:$/,"").toLowerCase(),f=o.searchParams.get("tls"),u=f==="0"||f==="false",g=o.searchParams.get("authToken")??void 0,h;switch(c){case"libsql":h=u?"http":"https";break;case"https":case"wss":h="https";break;case"http":case"ws":h="http";break;default:throw new a(`Unsupported libSQL URL scheme '${c}:'`,{code:"LIBSQL_INVALID_URL"})}if(o.username||o.password)throw new a("libSQL URLs must not embed credentials; pass the token as authToken",{code:"LIBSQL_INVALID_URL"});let d=o.pathname.replace(/\/+$/,"");return{baseUrl:`${h}://${o.host}${d}`,authToken:g||void 0}}var ra=[[/^UNIQUE constraint failed/i,"SQLITE_CONSTRAINT_UNIQUE",2067],[/^NOT NULL constraint failed/i,"SQLITE_CONSTRAINT_NOTNULL",1299],[/^FOREIGN KEY constraint failed/i,"SQLITE_CONSTRAINT_FOREIGNKEY",787],[/^CHECK constraint failed/i,"SQLITE_CONSTRAINT_CHECK",275]],Ls={SQLITE_ERROR:1,SQLITE_INTERNAL:2,SQLITE_PERM:3,SQLITE_ABORT:4,SQLITE_BUSY:5,SQLITE_LOCKED:6,SQLITE_NOMEM:7,SQLITE_READONLY:8,SQLITE_INTERRUPT:9,SQLITE_IOERR:10,SQLITE_CORRUPT:11,SQLITE_FULL:13,SQLITE_CANTOPEN:14,SQLITE_SCHEMA:17,SQLITE_TOOBIG:18,SQLITE_CONSTRAINT:19,SQLITE_MISMATCH:20,SQLITE_MISUSE:21,SQLITE_RANGE:25};class a extends Error{code;errno;libsqlCode;status;constructor(i,o){super(i,o.cause===void 0?void 0:{cause:o.cause});this.name="LibSQLError",this.code=o.code,this.errno=o.errno,this.libsqlCode=o.libsqlCode,this.status=o.status}}function Ie(i){let c=String(i.message??"libSQL statement failed").replace(/^SQLite error:\s*/i,""),f=i.code??void 0;for(let[u,g,h]of ra)if(u.test(c))return new a(c,{code:g,errno:h,libsqlCode:f});if(f&&f in Ls)return new a(c,{code:f,errno:Ls[f],libsqlCode:f});if(f==="SQL_PARSE_ERROR"||f==="SQL_INPUT_ERROR")return new a(c,{code:"SQLITE_ERROR",errno:1,libsqlCode:f});return new a(c,{code:f??"LIBSQL_ERROR",libsqlCode:f})}var na=-(2n**63n),sa=2n**63n-1n;function Nr(i){return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function jt(i){if(i===null||i===void 0)return{type:"null"};switch(typeof i){case"string":return{type:"text",value:i};case"boolean":return{type:"integer",value:i?"1":"0"};case"number":if(!Number.isFinite(i))throw RangeError(`Cannot bind ${i} to a libSQL statement: only finite numbers are allowed`);return Number.isSafeInteger(i)?{type:"integer",value:String(i===0?0:i)}:{type:"float",value:i};case"bigint":if(i<na||i>sa)throw RangeError(`Cannot bind ${i} to a libSQL statement: it does not fit in a 64-bit integer`);return{type:"integer",value:i.toString()}}if(i instanceof Date){if(Number.isNaN(i.getTime()))throw RangeError("Cannot bind an invalid Date to a libSQL statement");return{type:"text",value:i.toISOString()}}if(i instanceof Uint8Array)return{type:"blob",base64:Nr(i)};if(i instanceof ArrayBuffer)return{type:"blob",base64:Nr(new Uint8Array(i))};if(ArrayBuffer.isView(i))return{type:"blob",base64:Nr(new Uint8Array(i.buffer,i.byteOffset,i.byteLength))};throw TypeError(`Cannot bind a value of type ${Object.prototype.toString.call(i).slice(8,-1)} to a libSQL statement; serialize it first (e.g. JSON.stringify)`)}function qt(i,o="bigint"){switch(i.type){case"null":return null;case"integer":{let c=Number(i.value);if(Number.isSafeInteger(c))return c;return o==="string"?i.value:BigInt(i.value)}case"float":return typeof i.value==="number"?i.value:Number(i.value);case"text":return i.value;case"blob":{let c=Buffer.from(i.base64??"","base64");return new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}default:throw new a(`Unknown libSQL value type '${i.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"})}}function mn(i,o="bigint"){let c=i.cols.map((d,p)=>d.name??String(p)),f=i.rows.map((d)=>{let p={};for(let y=0;y<c.length;y++)p[c[y]]=qt(d[y]??{type:"null"},o);return p}),u=Number(i.affected_row_count??0),g=i.last_insert_rowid==null?null:qt({type:"integer",value:i.last_insert_rowid},o),h=(d)=>({value:d,enumerable:!1,writable:!0,configurable:!0});return Object.defineProperties(f,{changes:h(u),count:h(u>0?u:f.length),lastInsertRowid:h(g),columns:h(c)}),f}function Le(i,o=[]){if(!Array.isArray(o)){let f=Object.entries(o).map(([u,g])=>({name:/^[:@$]/.test(u)?u:`:${u}`,value:jt(g)}));return{sql:i,named_args:f,want_rows:!0}}let c=Mt(i,[...o]);return{sql:c.sql,args:c.params.map(jt),want_rows:!0}}var ia=/^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i,oa=/^\s*PRAGMA\s+(?:main\.)?foreign_keys\s*(?:=\s*|\(\s*)['"]?(\w+)['"]?\s*\)?\s*;?\s*$/i;function aa(i){let o=oa.exec(i);return o?o[1].toUpperCase():null}class Os{baseUrl;authToken;timeoutMs;fetchImpl;constructor(i){let o=fn(i.url);this.baseUrl=o.baseUrl,this.authToken=i.authToken||o.authToken,this.timeoutMs=i.timeoutMs,this.fetchImpl=i.fetch??fetch}async pipeline(i,o,c){let f={"content-type":"application/json"};if(this.authToken)f.authorization=`Bearer ${this.authToken}`;let u;try{u=await this.fetchImpl(`${i}/v3/pipeline`,{method:"POST",headers:f,body:JSON.stringify({baton:o,requests:c}),signal:this.timeoutMs?AbortSignal.timeout(this.timeoutMs):void 0})}catch(h){let d=h instanceof Error?h.message:String(h);throw new a(`Could not reach the libSQL server at ${this.baseUrl}: ${d}`,{code:"LIBSQL_CONNECTION_FAILED",cause:h})}if(!u.ok){let h=await ca(u),d=h?` (${h})`:"";if(u.status===401||u.status===403)throw new a(`The libSQL server at ${this.baseUrl} rejected the request: HTTP ${u.status}${d}. `+(this.authToken?"The auth token was refused - check that it belongs to this database and has not expired.":"No auth token was sent - set one (TURSO_AUTH_TOKEN in Stacks)."),{code:"LIBSQL_UNAUTHORIZED",status:u.status});if(u.status===404)throw new a(`The libSQL server at ${this.baseUrl} has no Hrana v3 pipeline endpoint (HTTP 404). Check the URL, and that the server is sqld 0.21+ or Turso.`,{code:"LIBSQL_NOT_FOUND",status:404});throw new a(`The libSQL server at ${this.baseUrl} answered HTTP ${u.status}${d}`,{code:"LIBSQL_HTTP_ERROR",status:u.status})}let g=await u.json();if(!g||!Array.isArray(g.results))throw new a(`The libSQL server at ${this.baseUrl} sent a reply that is not a Hrana pipeline response`,{code:"LIBSQL_PROTOCOL_ERROR"});return g}}async function ca(i){try{let o=(await i.text()).trim();if(!o)return"";try{let c=JSON.parse(o),f=c.error??c.message;if(typeof f==="string")return f}catch{}return o.slice(0,300)}catch{return""}}class Ps{http;prelude;baton=null;baseUrl;tail=Promise.resolve();opened=!1;closed=!1;constructor(i,o){this.http=i;this.prelude=o;this.baseUrl=i.baseUrl}send(i,o={}){let c=async()=>{if(this.closed)throw new a("This libSQL stream is closed",{code:"LIBSQL_STREAM_CLOSED"});let u=this.opened?[]:this.prelude();this.opened=!0;let g=[...u,...i];if(o.close)g.push({type:"close"});let h;try{h=await this.http.pipeline(this.baseUrl,this.baton,g)}catch(d){throw this.closed=!0,d}if(this.baton=h.baton,h.base_url)this.baseUrl=h.base_url.replace(/\/+$/,"");if(o.close||h.baton===null)this.closed=!0;for(let d=0;d<u.length;d++){let p=h.results[d];if(p?.type==="error")throw Ie(p.error)}return h.results.slice(u.length,u.length+i.length)},f=this.tail.then(c,c);return this.tail=f.catch(()=>{}),f}async close(){if(this.closed)return;if(!this.opened){this.closed=!0;return}await this.send([],{close:!0})}}function He(i){if(!i)throw new a("The libSQL server sent fewer results than requests",{code:"LIBSQL_PROTOCOL_ERROR"});if(i.type==="error")throw Ie(i.error);if(i.response.type!=="execute")throw new a(`Expected an execute result, got '${i.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});return i.response.result}function ks(i){if(i?.type==="ok"&&i.response.type==="get_autocommit")return i.response.is_autocommit;return!1}class Ns{http;largeIntegers;foreignKeys=null;pinned=null;closed=!1;constructor(i){this.http=new Os(i),this.largeIntegers=i.largeIntegers??"bigint"}prelude=()=>this.foreignKeys?[{type:"execute",stmt:{sql:`PRAGMA foreign_keys = ${this.foreignKeys}`,want_rows:!1}}]:[];openStream(){return this.assertOpen(),new Ps(this.http,this.prelude)}assertOpen(){if(this.closed)throw new a("Cannot use a closed libSQL connection",{code:"LIBSQL_CLOSED"})}rows(i){return mn(i,this.largeIntegers)}notePragma(i){let o=aa(i);if(o)this.foreignKeys=o==="OFF"||o==="0"||o==="FALSE"||o==="NO"?"OFF":"ON"}async execute(i){this.assertOpen();let o=ia.test(i.sql);if(this.pinned){let g=this.pinned,h=[{type:"execute",stmt:i}];if(o)h.push({type:"get_autocommit"});let d;try{d=await g.send(h)}catch(y){if(this.pinned===g)this.pinned=null;throw y}if(o&&ks(d[1])){if(this.pinned===g)this.pinned=null;await g.close().catch(()=>{})}let p=this.rows(He(d[0]));return this.notePragma(i.sql),p}if(o){let g=this.openStream(),h;try{h=await g.send([{type:"execute",stmt:i},{type:"get_autocommit"}])}catch(p){throw await g.close().catch(()=>{}),p}if(h[0]?.type!=="error"&&!ks(h[1]))this.pinned=g;else await g.close().catch(()=>{});return this.rows(He(h[0]))}let c=this.openStream(),[f]=await c.send([{type:"execute",stmt:i}],{close:!0}),u=this.rows(He(f));return this.notePragma(i.sql),u}async close(){this.closed=!0;let i=this.pinned;this.pinned=null,await i?.close().catch(()=>{})}}function Fs(i,o){return{async execute(c){let[f]=await o.send([{type:"execute",stmt:c}]),u=i.rows(He(f));return i.notePragma(c.sql),u},async sequence(c){let f=[];for(let u of c)f.push(await this.execute(u));return f}}}function la(i){return{execute:(o)=>i.execute(o),async sequence(o){if(i.pinned){let f=[];for(let u of o)f.push(await i.execute(u));return f}let c=i.openStream();try{let f=[];for(let u of o)f.push(await Fs(i,c).execute(u));return f}finally{await c.close().catch(()=>{})}}}}function Rs(i){return{__raw:!0,value:i,toString:()=>i}}function fa(i,o){let c=i[0],f=[];for(let u=0;u<o.length;u++){let g=o[u],h=Ir(g);if(h&&typeof h.sql==="string"&&Array.isArray(h.values))c+=h.sql+(i[u+1]||""),f.push(...h.values);else if(h&&(h.__raw||h.raw)){let d=h.raw,p=h.__raw?h.value:typeof d==="string"?d:d();c+=p+(i[u+1]||"")}else if(Array.isArray(g))c+=g.map(()=>"?").join(", ")+(i[u+1]||""),f.push(...g);else c+=`?${i[u+1]||""}`,f.push(g)}return{sql:c,params:f}}function Fr(i,o,c,f){let u=()=>{try{return i.target.execute(Le(o,c))}catch(h){return Promise.reject(h)}},g={sql:o,values:c,execute:u,raw:()=>o,toString:()=>o,cancel:()=>{}};if(f)g.then=(h,d)=>u().then(h,d);return g}function Dr(i){function o(c,...f){if(Array.isArray(c)&&"raw"in c){let{sql:u,params:g}=fa(c,f);return Fr(i,u,g,!1)}if(typeof c==="string")return Rs(c);return Fr(i,"",[],!1)}return o.raw=(c)=>Rs(c),o.unsafe=(c,f=[])=>Fr(i,c,f??[],!0),o.query=(c,f)=>{try{return i.target.execute(Le(c,f??[]))}catch(u){return Promise.reject(u)}},o.file=async(c)=>{let{readFileSync:f}=await import("fs"),u=_r(f(c,"utf-8")).map((g)=>g.trim()).filter((g)=>g&&!g.startsWith("--"));return await i.target.sequence(u.map((g)=>Le(g))),[]},o.batch=async(c)=>{if(i.session.assertOpen(),c.length===0)return[];let f=i.stream!==null,u=c.map((E)=>Le(E.sql,E.args??[])),g=[];if(!f)g.push({stmt:{sql:"BEGIN"}});for(let E of u)g.push({stmt:E,condition:g.length?{type:"ok",step:g.length-1}:null});if(!f){let E=g.length-1;g.push({stmt:{sql:"COMMIT"},condition:{type:"ok",step:E}}),g.push({stmt:{sql:"ROLLBACK"},condition:{type:"not",cond:{type:"ok",step:E+1}}})}let h=i.stream??i.session.openStream(),d;try{d=await h.send([{type:"batch",batch:{steps:g}}],{close:!f})}finally{if(!f)await h.close().catch(()=>{})}let p=d[0];if(!p)throw new a("The libSQL server sent no batch result",{code:"LIBSQL_PROTOCOL_ERROR"});if(p.type==="error")throw Ie(p.error);if(p.response.type!=="batch")throw new a(`Expected a batch result, got '${p.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});let{step_results:y,step_errors:w}=p.response.result,S=f?0:1;for(let E=0;E<w.length;E++){let v=w[E];if(v)throw Ie(v)}return u.map((E,v)=>{let x=y[v+S];if(!x)throw new a(`Batch statement ${v+1} did not run`,{code:"LIBSQL_BATCH_SKIPPED"});return i.session.rows(x)})},o.begin=async(c,f)=>{let u=typeof c==="function"?c:f;if(typeof u!=="function")throw TypeError("[query-builder] libsql begin(): a transaction callback is required");if(i.session.assertOpen(),i.stream){let w=`qb_sp_${i.depth}`,S=i.target;await S.execute({sql:`SAVEPOINT ${w}`});let E=Dr({...i,depth:i.depth+1});try{let v=await u(E);return await S.execute({sql:`RELEASE SAVEPOINT ${w}`}),v}catch(v){try{await S.execute({sql:`ROLLBACK TO SAVEPOINT ${w}`}),await S.execute({sql:`RELEASE SAVEPOINT ${w}`})}catch{}throw v}}let g=i.session.openStream(),h=Fs(i.session,g);try{await h.execute({sql:"BEGIN"})}catch(w){throw await g.close().catch(()=>{}),w}let d=Dr({session:i.session,target:h,stream:g,depth:1}),p;try{p=await u(d)}catch(w){try{await g.send([{type:"execute",stmt:{sql:"ROLLBACK"}}],{close:!0})}catch{await g.close().catch(()=>{})}throw w}let[y]=await g.send([{type:"execute",stmt:{sql:"COMMIT"}}],{close:!0});return He(y),p},o.savepoint=o.begin,o.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on libSQL. Use begin()/transaction().")},o.close=async()=>{if(i.stream)return;await i.session.close()},o.libsql={url:i.session.http.baseUrl,transaction:i.stream!==null},o}function Wt(i){let o=new Ns(i);return Dr({session:o,target:la(o),stream:null,depth:0})}function Wn(i){return(typeof i==="function"||typeof i==="object"&&i!==null)&&typeof i.libsql==="object"&&i.libsql!==null}var Ut=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"];function Vt(){let i=e.sqlite?.pragmas;return Array.isArray(i)?i:Ut}function k(i){for(let o of Vt())try{i.run(o)}catch{}}function ze(i){return`"${i.replaceAll('"','""')}"`}class Mr{database;pending=[];bytes=0;timer;closed=!1;failure;constructor(i){this.database=i}get hasPending(){return this.pending.length>0}append=(i,o)=>{if(this.failure)return Promise.reject(this.failure);if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));let c=Object.keys(o),f=c.map((h)=>{let d=o[h];if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength).slice();return d??null}),u=JSON.stringify([i,c]),g=512+u.length*2+f.reduce((h,d)=>h+(typeof d==="string"?d.length*2:ArrayBuffer.isView(d)?d.byteLength:16),0);if(this.hasPending&&(this.pending.length>=32||this.bytes+g>262144))this.flush();return new Promise((h,d)=>{let p={table:i,columns:c,values:f,shape:u,uncached:g>262144,resolve:h,reject:d};if(this.database.inTransaction||g>262144){this.writeOne(p);return}this.pending.push(p),this.bytes+=g,this.timer??=setImmediate(()=>this.flush())})};flush(){if(this.timer!==void 0)clearImmediate(this.timer),this.timer=void 0;let i=this.pending;this.pending=[],this.bytes=0;for(let o=0;o<i.length;){if(this.failure){for(let u of i.slice(o))u.reject(this.failure);return}let c=o+1;while(c<i.length&&i[c].shape===i[o].shape)c++;let f=i.slice(o,c);if(o=c,f.length===1||!f[0].columns.length||this.database.inTransaction){for(let u of f)this.writeOne(u);continue}try{this.database.transaction(()=>{let u=f[0],g=`(${u.columns.map(()=>"?").join(",")})`,h=`INSERT INTO ${ze(u.table)} (${u.columns.map(ze).join(",")}) VALUES ${f.map(()=>g).join(",")}`;this.database.query(h).run(...f.flatMap((d)=>d.values))})();for(let u of f)u.resolve()}catch(u){if(this.database.inTransaction){this.invalidate(u);for(let g of[...f,...i.slice(o)])g.reject(u);return}for(let g of f)this.writeOne(g)}}}writeOne(i){let o=!1;try{this.assertUsable(),o=this.database.inTransaction;let c=i.columns.length?`INSERT INTO ${ze(i.table)} (${i.columns.map(ze).join(",")}) VALUES (${i.columns.map(()=>"?").join(",")})`:`INSERT INTO ${ze(i.table)} DEFAULT VALUES`,f=()=>{if(!i.uncached)return this.database.query(c).run(...i.values);let u=this.database.prepare(c);try{return u.run(...i.values)}finally{u.finalize()}};if(o)f();else this.database.transaction(f)();i.resolve()}catch(c){if(!this.failure&&!o&&this.database.inTransaction)this.invalidate(c);i.reject(c)}}assertUsable(){if(this.failure)throw this.failure}invalidate(i){this.failure=Error("SQLite connection is unusable after deferred insert rollback failed",{cause:i});try{this.database.close()}catch{}}close(){this.closed=!0,this.flush()}}function Br(i){return i}function Ir(i){return i!==null&&typeof i==="object"?i:null}function Mt(i,o){if(o.length===0||!/\$\d/.test(i))return{sql:i,params:o};let c=[],f="",u=0;for(let g=0;g<i.length;g++){let h=i[g];if(h==="'"||h==='"'||h==="`"){let d=da(i,g,h);f+=i.slice(g,d),g=d-1;continue}if(h==="-"&&i[g+1]==="-"){let d=i.indexOf(`
62
- `,g),p=d===-1?i.length:d;f+=i.slice(g,p),g=p-1;continue}if(h==="/"&&i[g+1]==="*"){let d=i.indexOf("*/",g+2),p=d===-1?i.length:d+2;f+=i.slice(g,p),g=p-1;continue}if(h==="$"){let d=/^\d+/.exec(i.slice(g+1))?.[0];if(d){let p=Number(d);if(u=Math.max(u,p),p>=1&&p<=o.length){c.push(o[p-1]),f+="?",g+=d.length;continue}}}f+=h}if(u>o.length)throw Error(`SQL references $${u} but only ${o.length} value${o.length===1?" was":"s were"} provided`);if(c.length===0)return{sql:i,params:o};return{sql:f,params:c}}function da(i,o,c){for(let f=o+1;f<i.length;f++){if(i[f]!==c)continue;if(i[f+1]===c){f++;continue}return f+1}return i.length}var jr=/^\s*(?:SELECT|WITH|INSERT|UPDATE|DELETE|REPLACE)\b/i;class Bs{db;deferredInserts;closed=!1;constructor(i){if(i!==":memory:"&&!i.startsWith(":")){let o=ga(i);if(o&&o!==".")ha(o,{recursive:!0})}this.db=new ua(i),k(this.db)}deferInsert=(i,o)=>{if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));if(!this.deferredInserts){let c=this.deferredInserts=new Mr(this.db),f=this.query.bind(this),u=this.run.bind(this),g=(h)=>{if(c.hasPending&&!jr.test(h))c.flush();c.assertUsable()};this.query=(h,d)=>(g(h),f(h,d)),this.run=(h,d)=>(g(h),u(h,d))}return this.deferredInserts.append(i,o)};flushDeferredInserts(){this.deferredInserts?.flush()}query(i,o=[]){let c=Mt(i,o),f=c.params.length>0||jr.test(c.sql),u=f?this.db.query(c.sql):this.db.prepare(c.sql);return(f&&c.params.length===0&&u.paramsCount>0?this.db.prepare(c.sql):u).all(...c.params)}run(i,o=[]){let c=Mt(i,o),f=c.params.length>0||jr.test(c.sql),u=f?this.db.query(c.sql):this.db.prepare(c.sql);return(f&&c.params.length===0&&u.paramsCount>0?this.db.prepare(c.sql):u).run(...c.params)}close(){this.closed=!0,this.deferredInserts?.close(),this.db.close()}get database(){return this.db}}function Is(i){return{__raw:!0,value:i,toString:()=>i}}function _s(i){let o=i.trimStart();for(;;)if(o.startsWith("--")){let c=o.indexOf(`
63
- `);o=c===-1?"":o.slice(c+1).trimStart()}else if(o.startsWith("/*")){let c=o.indexOf("*/");o=c===-1?"":o.slice(c+2).trimStart()}else return o}function _r(i){let o=[],c="",f=!1,u=!1,g=!1,h=!1;for(let p=0;p<i.length;p++){let y=i[p],w=i[p+1];if(!f&&!u&&!h&&y==="-"&&w==="-"){g=!0,c+=y;continue}if(g&&(y===`
64
- `||y==="\r")){g=!1,c+=y;continue}if(!f&&!u&&!g&&y==="/"&&w==="*"){h=!0,c+=y;continue}if(h&&y==="*"&&w==="/"){h=!1,c+=y+w,p++;continue}if(g||h){c+=y;continue}if(y==="'"&&!u){if(f&&w==="'"){c+=y+w,p++;continue}f=!f,c+=y;continue}if(y==='"'&&!f){u=!u,c+=y;continue}if(y===";"&&!f&&!u){let S=_s(c.trim());if(S)o.push(S);c="";continue}c+=y}let d=_s(c.trim());if(d)o.push(d);return o}function Ms(i){let o=new Bs(i);function c(h,d){let p=h.trim().toUpperCase();if(p.startsWith("SELECT")||p.startsWith("PRAGMA")||/\bRETURNING\b/.test(p))return o.query(h,Br(d));return o.run(h,Br(d))}function f(h,...d){let p=h[0],y=[];for(let S=0;S<d.length;S++){let E=d[S],v=Ir(E);if(v&&typeof v.sql==="string"&&Array.isArray(v.values))p+=v.sql+(h[S+1]||""),y.push(...v.values);else if(v&&(v.__raw||v.raw)){let x=v.raw,C=v.__raw?v.value:typeof x==="string"?x:x();p+=C+(h[S+1]||"")}else if(Array.isArray(E)){let x=E.map(()=>"?").join(", ");p+=x+(h[S+1]||""),y.push(...E)}else p+=`?${h[S+1]||""}`,y.push(E)}let w=()=>c(p,y);return{sql:p,values:y,executeSync:w,execute:()=>{try{return Promise.resolve(w())}catch(S){return Promise.reject(S)}},raw:()=>p,toString:()=>p,cancel:()=>{}}}function u(h,...d){if(Array.isArray(h)&&"raw"in h)return f(h,...d);if(typeof h==="string")return Is(h);return f([""])}u.raw=(h)=>Is(h),u.unsafe=(h,d=[])=>{let p=()=>c(h,d),y=()=>{try{return Promise.resolve(p())}catch(w){return Promise.reject(w)}};return{sql:h,values:d,execute:y,executeSync:p,then:(w,S)=>y().then(w,S),raw:()=>h,toString:()=>h,cancel:()=>{}}},u.deferInsert=o.deferInsert,u.flushDeferredInserts=()=>o.flushDeferredInserts(),u.close=()=>(o.close(),Promise.resolve()),u.query=(h,d)=>{try{let p=o.query(h,Br(d||[]));return Promise.resolve(p)}catch(p){return Promise.reject(p)}},u.file=async(h,d)=>{try{let{readFileSync:p}=await import("fs"),y=p(h,"utf-8"),w=_r(y);for(let S of w){let E=S.trim();if(!E||E.startsWith("--"))continue;let v=E.toUpperCase();if(v.startsWith("SELECT")||v.startsWith("PRAGMA"))o.query(S);else o.run(S)}return Promise.resolve([])}catch(p){return Promise.reject(p)}};let g=0;return u.begin=async(h,d)=>{let p=typeof h==="function"?h:d;if(typeof p!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let y=g>0,w=`qb_sp_${g}`;if(y)o.run(`SAVEPOINT ${w}`);else o.run("BEGIN");g++;try{let S=await p(u);if(g--,y)o.run(`RELEASE SAVEPOINT ${w}`);else o.run("COMMIT");return S}catch(S){g--;try{if(y)o.run(`ROLLBACK TO SAVEPOINT ${w}`),o.run(`RELEASE SAVEPOINT ${w}`);else o.run("ROLLBACK")}catch{}throw S}},u.savepoint=u.begin,u.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},u._wrapper=o,u}function ma(i){let o=i.replace(/^(?:sqlite|sqlite3|file):/i,"");if(o===i)return i;return(o.startsWith("///")?o.slice(2):o.startsWith("//")?o.slice(2):o)||":memory:"}function Ke(i=e.database){let o=Ge.env.DB_DATABASE||i?.database||"";return String(o).replace(/^['"]|['"]$/g,"")}function pa(i,o){if((i==="postgres"||i==="mysql"||i==="singlestore"||i==="vitess")&&Ge.env.DB_CONNECTION===i){let y=Ge.env,w=(y.DB_DATABASE||o.database||"").replace(/^['"]|['"]$/g,""),S=y.DB_USERNAME||o.username,E=y.DB_PASSWORD??o.password??"",v=y.DB_HOST||o.host||"localhost",x=y.DB_PORT||o.port,C=i==="postgres"?"postgres":"mysql",A=y.DB_SSL==="true"||y.DB_SSL==="1"||o.ssl?"?ssl=true":"";return`${C}://${S}:${E}@${v}${x?`:${x}`:""}/${w}${A}`}if(o.url)return i==="sqlite"?ma(o.url):o.url;let{database:c,username:f,password:u,host:g="localhost",port:h,ssl:d}=o,p=d||Ge.env.DB_SSL==="true"||Ge.env.DB_SSL==="1"?"?ssl=true":"";switch(i){case"postgres":return`postgres://${f}:${u}@${g}${h?`:${h}`:""}/${c}${p}`;case"mysql":case"singlestore":case"vitess":return`mysql://${f}:${u}@${g}${h?`:${h}`:""}/${c}${p}`;case"sqlite":if(c===":memory:")return":memory:";return c||":memory:";default:throw Error(`Unsupported dialect: ${i}`)}}function js(i){if(!i)return{};let o={},c=(f)=>Math.max(0,Math.round(f/1000));if(typeof i.max==="number"&&Number.isFinite(i.max))o.max=i.max;if(typeof i.idleTimeoutMs==="number"&&Number.isFinite(i.idleTimeoutMs))o.idleTimeout=c(i.idleTimeoutMs);if(typeof i.acquireTimeoutMs==="number"&&Number.isFinite(i.acquireTimeoutMs))o.connectionTimeout=c(i.acquireTimeoutMs);if(typeof i.maxLifetimeMs==="number"&&Number.isFinite(i.maxLifetimeMs))o.maxLifetime=c(i.maxLifetimeMs);return o}function _(i=e.database,o=e.dialect){if(o!=="sqlite"||!i)return null;let c=it(i.url)?i.url:it(i.database)?i.database:null;if(!c)return null;return{url:c,authToken:i.authToken||void 0}}function ya(){let i=e.dialect,o=_(e.database,i);if(o)return Wt(o);let c=pa(i,e.database);try{if(i==="sqlite")return Ms(c);let f=js(e.database.pool);return Object.keys(f).length>0?new Ds(c,f):new Ds(c)}catch(f){if(console.error(`[query-builder] Failed to create database connection for dialect '${i}': ${f.message}`),i==="sqlite")return Ms(":memory:");throw f}}var Pe=null,Kr=null;function wa(){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,authToken:i.authToken,pool:js(i.pool)})}function b(i=!1){let o=wa();if(i||Pe!==null&&Kr!==o||!Pe)Ks(),Pe=ya(),Kr=o;return Pe}function Ks(){let i=Pe;return i?.flushDeferredInserts?.(),Pe=null,Kr=null,i}async function ba(i){if(!i||typeof i.close!=="function")return;await i.close()}function hn(){ba(Ks()).catch((o)=>{console.error(`[query-builder] Failed to close database connection: ${o.message}`)})}async function st(i){try{return await i(b())}catch(o){if(o?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||o?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let c=b(!0);return await i(c)}throw o}}function Sa(){return new Proxy(function(){},{get(i,o){let c=b(),f=c[o];if(typeof f==="function")return f.bind(c);return f},apply(i,o,c){return b()(...c)}})}var r=Sa();function Fe(i){let o=String(i).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(o.endsWith("y")&&!/[aeou]y$/.test(o))return`${o.slice(0,-1)}ies`;if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return`${o}es`;return`${o}s`}function T(i){return typeof i?.table==="string"&&i.table.length>0?i.table:Fe(String(i?.name??""))}function gn(i){return i.endsWith("s")?i.slice(0,-1):i}function pn(i){if(i.endsWith("ies")&&i.length>3){let o=i.slice(0,-3),c=o[o.length-1];if(c&&!"aeiou".includes(c))return`${o}y`}if(i.endsWith("es")&&i.length>2){let o=i.slice(0,-2);if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return o}if(i.endsWith("s")&&!i.endsWith("ss")&&!i.endsWith("us")&&!i.endsWith("is"))return i.slice(0,-1);return i}function m(i){if(i==="none")return(o)=>o;if(i==="inflect")return pn;return gn}var Ht="1 = 0";function D(i){if(i.length===0)return"";let o=[];for(let c of i)if(c.conn==="OR"&&o.length>0)o[o.length-1].push(c);else o.push([c]);return o.map((c,f)=>{let u=c.map((h)=>h.sql).join(" OR "),g=c.length>1&&o.length>1?`(${u})`:u;return f===0?g:`${c[0].conn} ${g}`}).join(" ")}function l(i,o,c,f){if(o.length===0)return c?"1 = 1":"1 = 0";return`${i} ${c?"NOT IN":"IN"} (${f})`}function at(i,o){if(o!=="postgres")return i;return je(i,(c)=>`$${c}`).text}function X(i){return je(i,()=>{return}).count}function je(i,o){let c="",f=0,u=0,g=0;while(g<i.length){let h=i[g],d=-1;if(h==="'"||h==='"'||h==="`")d=va(i,g,h);else if(h==="-"&&i[g+1]==="-"){let p=i.indexOf(`
65
- `,g+2);d=p===-1?i.length:p}else if(h==="/"&&i[g+1]==="*"){let p=1;d=g+2;while(d<i.length&&p>0)if(i[d]==="/"&&i[d+1]==="*")p++,d+=2;else if(i[d]==="*"&&i[d+1]==="/")p--,d+=2;else d++}else if(h==="$"){let p=i.slice(g).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(p){let y=i.indexOf(p,g+p.length);d=y===-1?i.length:y+p.length}}if(d!==-1){g=d;continue}if(h==="?"){f++;let p=o(f);if(p!==void 0)c+=i.slice(u,g)+p,u=g+1}g++}return{text:u===0?i:c+i.slice(u),count:f}}function va(i,o,c){let f=o+1;while(f<i.length){if(i[f]===c){if(i[f+1]===c){f+=2;continue}return f+1}f++}return i.length}function qe(i,o,c=Number.POSITIVE_INFINITY){let f=[],u=0,g=(h)=>h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||h===95;for(let h=0;h<i.length;h++){let d=i.charCodeAt(h);if(d===45&&i.charCodeAt(h+1)===45){let y=i.indexOf(`
66
- `,h+2);if(y===-1)return f;h=y;continue}if(d===47&&i.charCodeAt(h+1)===42){let y=1,w=h+2;while(w<i.length&&y>0)if(i[w]==="/"&&i[w+1]==="*")y++,w+=2;else if(i[w]==="*"&&i[w+1]==="/")y--,w+=2;else w++;h=w-1;continue}if(d===39||d===34||d===96){let y=h+1;while(y<i.length){if(i.charCodeAt(y)===d){if(i.charCodeAt(y+1)===d){y+=2;continue}break}y++}h=y;continue}if(d===36){let y=/^\$(?:[A-Z_][A-Z0-9_]*)?\$/i.exec(i.slice(h));if(y){let w=i.indexOf(y[0],h+y[0].length);h=w===-1?i.length:w+y[0].length-1;continue}}if(d===40){u++;continue}if(d===41){u=Math.max(0,u-1);continue}if(u!==0)continue;if(h===0)continue;let p=d&-33;if(p<65||p>90)continue;if(g(i.charCodeAt(h-1)))continue;for(let{key:y,pattern:w}of o){w.lastIndex=h;let S=w.exec(i);if(!S)continue;if(f.push({key:y,start:h,length:S[0].length}),f.length>=c)return f;h+=S[0].length-1;break}}return f}
67
- export{n,nt,e,P,rt,t,s,B,_e,dn,it,fn,a,Ie,jt,qt,mn,Le,Wt,Wn,Ut,Vt,k,Ke,_,b,hn,st,r,Fe,T,gn,pn,m,Ht,D,l,at,X,je,qe};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{ht,w,R,Qe,A}from"./chunk-3b13fc8j.js";import"./chunk-vyqr0w2z.js";import"./chunk-9wck98bv.js";import"./chunk-rzfnhh9f.js";import"./chunk-bpwg9p8b.js";import"./chunk-93ny6tvm.js";export{R as executeMigration,Qe as executeMigrationWithReport,w as generateMigration,A as resetDatabase,ht as saveMigrationSnapshot};