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