bun-query-builder 0.2.70 → 0.3.1

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