bun-query-builder 0.3.12 → 0.3.14
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 +7 -7
- package/dist/chunk-2v1zv4hb.js +7 -0
- package/dist/chunk-35s45ket.js +3 -0
- package/dist/{chunk-d2k7k2v6.js → chunk-6w95jzzq.js} +63 -63
- package/dist/chunk-ewmd9fn5.js +2 -0
- package/dist/{chunk-30mmrj6e.js → chunk-hk8j5d48.js} +1 -1
- package/dist/{chunk-hzrsdtv2.js → chunk-jypmc6m3.js} +23 -23
- package/dist/chunk-ztdtt4hj.js +3 -0
- package/dist/client.d.ts +5 -1
- package/dist/index.d.ts +1 -2
- package/dist/orm.d.ts +3 -37
- package/dist/relation-utils.d.ts +1 -0
- package/dist/schema.d.ts +1 -1
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/runtime.js +1 -1
- package/dist/type-inference.d.ts +2 -1
- package/package.json +1 -1
- package/dist/chunk-4yc8xkvc.js +0 -2
- package/dist/chunk-6s2dqhn3.js +0 -7
- package/dist/chunk-erek1wzq.js +0 -3
- package/dist/chunk-kt617w7c.js +0 -3
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var{SQL:Ea}=globalThis.Bun;function ye(i,o){if(i instanceof Date)return Ys(i,o);if(Array.isArray(i)&&i.some($e))return i.map((c)=>ye(c,o));return i}function p(i){if(!i||!i.some($e))return i;return i.map((o,c)=>ye(o,c+1))}function B(i){if(!Js(i)||Gr.has(i))return i;let o=Yr.get(i);if(o)return o;let c=i,f=new Proxy(c,{apply(u,g,h){return Reflect.apply(u,c,Zs(h))},get(u,g){let h=Reflect.get(u,g,u);if(typeof h!=="function")return h;switch(g){case"unsafe":case"file":return(d,y,...b)=>h.call(u,d,p(y),...b);case"array":return(d,...y)=>h.call(u,ye(d),...y);case"begin":case"transaction":case"savepoint":case"beginDistributed":case"distributed":return(...d)=>h.apply(u,d.map((y)=>typeof y==="function"?(b,...S)=>y(B(b),...S):y));case"reserve":return async(...d)=>B(await h.apply(u,d));default:return h.bind(u)}}});return Gr.add(f),Yr.set(i,f),f}var Gr=new WeakSet,Yr=new WeakMap;function $e(i){return i instanceof Date||Array.isArray(i)&&i.some($e)}function Ys(i,o){if(Number.isNaN(i.getTime())){let c=o?` (parameter ${o})`:"";throw RangeError(`[query-builder] Cannot bind an invalid Date${c}: it would reach the database as the text "Invalid Date". Check the value before writing it.`)}return i.toISOString()}function Js(i){return typeof i==="function"&&i.options?.adapter==="postgres"}function zt(i){if(i===null||typeof i!=="object")return!1;let o=Object.getPrototypeOf(i);return o===Object.prototype||o===null}function Jr(i){let o=null;for(let c of Object.keys(i))if($e(i[c]))o??={...i},o[c]=ye(i[c]);return o??i}function Zs(i){let[o]=i;if(Array.isArray(o)&&"raw"in o)return i.some((c,f)=>f>0&&$e(c))?[o,...i.slice(1).map((c,f)=>ye(c,f+1))]:i;if(zt(o))return[Jr(o),...i.slice(1)];if(Array.isArray(o)&&o.some((c)=>zt(c)||$e(c)))return[o.map((c)=>zt(c)?Jr(c):ye(c)),...i.slice(1)];return i}import{Database as Ca}from"bun:sqlite";import{mkdirSync as xa}from"fs";import{dirname as Ta}from"path";import Xe from"process";import Ps from"process";import{existsSync as Zr,statSync as Xr}from"fs";import{resolve as Be}from"path";import Xs from"process";import{existsSync as ri,mkdirSync as ja,readdirSync as Ka,readFileSync as ni,writeFileSync as Va}from"fs";import{homedir as Ee}from"os";import{dirname as Ua,resolve as fe}from"path";import _t from"process";import{existsSync as en,statSync as tn}from"fs";import{existsSync as mr,mkdirSync as si,readdirSync as ii,writeFileSync as oi}from"fs";import{homedir as Ce}from"os";import{dirname as rn,resolve as X}from"path";import ve from"process";import{join as ai,relative as ci,resolve as nn}from"path";import Ct from"process";import{existsSync as Jn,mkdirSync as tc,readdirSync as rc,writeFileSync as nc}from"fs";import{homedir as Yt}from"os";import{dirname as oc,resolve as Z}from"path";import Qe from"process";import{join as li,relative as fi,resolve as sn}from"path";import xt from"process";import{existsSync as Zn,mkdirSync as uc,readdirSync as hc,writeFileSync as gc}from"fs";import{dirname as mc,resolve as Tt}from"path";import pr from"process";import{Buffer as we}from"buffer";import{createCipheriv as ui,createDecipheriv as hi,randomBytes as Jt}from"crypto";import{closeSync as Zt,createReadStream as on,createWriteStream as gi,existsSync as Xt,fsyncSync as an,openSync as cn,writeFileSync as di}from"fs";import{access as mi,constants as ln,mkdir as pi,readdir as et,rename as fn,stat as xe,unlink as tt,writeFile as er}from"fs/promises";import{join as Te}from"path";import G from"process";import{pipeline as yi}from"stream/promises";import{createGzip as un}from"zlib";import ke from"process";import ge from"process";import{Buffer as ue}from"buffer";import{createCipheriv as wi,createDecipheriv as bi,randomBytes as tr}from"crypto";import{closeSync as rr,createReadStream as dn,createWriteStream as Si,existsSync as rt,fsyncSync as wn,openSync as Sn,writeFileSync as vi}from"fs";import{access as $i,constants as vn,mkdir as Ei,readdir as nt,rename as $n,stat as Ae,unlink as ct,writeFile as nr}from"fs/promises";import{isAbsolute as Ci,join as Re,resolve as xi}from"path";import D from"process";import{pipeline as Ti}from"stream/promises";import{createGzip as En}from"zlib";import Oe from"process";import de from"process";import ft from"process";import{existsSync as ut}from"fs";import{resolve as sr}from"path";import{existsSync as ki}from"fs";import{existsSync as Ai,readdirSync as Li}from"fs";import{extname as ir,resolve as Cn}from"path";import Ri from"process";import{join as Oi,relative as Pi,resolve as xn}from"path";import kt from"process";import{Buffer as he}from"buffer";import{createCipheriv as Ni,createDecipheriv as Di,randomBytes as or}from"crypto";import{closeSync as ar,createReadStream as Tn,createWriteStream as Fi,existsSync as ht,fsyncSync as kn,openSync as An,writeFileSync as Ii}from"fs";import{access as _i,constants as Ln,mkdir as Mi,readdir as gt,rename as Rn,stat as Pe,unlink as dt,writeFile as cr}from"fs/promises";import{isAbsolute as Bi,join as Ne,resolve as ji}from"path";import F from"process";import{pipeline as Ki}from"stream/promises";import{createGzip as On}from"zlib";import De from"process";import me from"process";import pt from"process";import{existsSync as yt}from"fs";import{resolve as qn}from"path";import{existsSync as ca}from"fs";class Hn{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,o){let c=o?`:${o}`:"";return`${this.options.keyPrefix}${i}${c}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,c],[,f])=>c.timestamp.getTime()-f.timestamp.getTime()),o=i.length-this.options.maxSize+1;for(let c=0;c<o;c++)this.cache.delete(i[c][0])}set(i,o,c,f){if(!this.options.enabled)return;let u=this.generateKey(i,c),g=f??this.options.ttl,h=this.estimateSize(o);this.cache.set(u,{value:o,timestamp:new Date,ttl:g,hits:0,size:h}),this.evictIfNeeded()}get(i,o){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,o),f=this.cache.get(c);if(!f){this.totalMisses++;return}if(this.isExpired(f)){this.cache.delete(c),this.totalMisses++;return}return f.hits++,this.totalHits++,f.value}isFileModified(i,o){try{if(!Zr(i))return!0;return Xr(i).mtime>o}catch{return!0}}getWithFileCheck(i,o){let c=this.get(i,o);if(!c)return;if(this.isFileModified(o,c.fileTimestamp)){this.delete(i,o);return}return c.value}setWithFileCheck(i,o,c,f){try{let u=Zr(c)?Xr(c):null,g=u?u.mtime:new Date;this.set(i,{value:o,fileTimestamp:g},c,f)}catch{this.set(i,o,c,f)}}delete(i,o){let c=this.generateKey(i,o);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[o,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(o),i++;return i}getStats(){let i=Array.from(this.cache.values()),o=i.reduce((f,u)=>f+u.size,0),c=i.map((f)=>f.timestamp).sort();return{size:o,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:c[0],newestEntry:c[c.length-1]}}export(){let i={};for(let[o,c]of this.cache.entries())i[o]={value:c.value,timestamp:c.timestamp.toISOString(),ttl:c.ttl,hits:c.hits,size:c.size};return i}import(i){this.cache.clear();for(let[o,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let f=c;this.cache.set(o,{value:f.value,timestamp:new Date(f.timestamp),ttl:f.ttl,hits:f.hits,size:f.size})}}}class zn{metrics=[];maxMetrics=1000;async track(i,o,c={}){let f=performance.now(),u=new Date;try{let g=await o(),h=performance.now()-f;return this.recordMetric({operation:i,duration:h,timestamp:u,...c}),g}catch(g){let h=performance.now()-f;throw this.recordMetric({operation:`${i}:error`,duration:h,timestamp:u,...c}),g}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let o=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(o.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=o.map((u)=>u.duration),f=c.reduce((u,g)=>u+g,0);return{count:o.length,averageDuration:f/o.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:f,recentMetrics:o.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((o)=>o.duration>i)}}var Et=new Hn,kr=new zn;var Gn=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Yn(i={}){let{name:o="",alias:c}=i,f=["config",".config"];if(o)f.push(o,`.${o}.config`,`${o}.config`,`.${o}`);let u=c===void 0?[]:Array.isArray(c)?c:[c];for(let g of u){if(!g)continue;if(f.push(g,`.${g}.config`,`${g}.config`,`.${g}`),o)f.push(`${o}.${g}.config`,`.${o}.${g}.config`)}return Array.from(new Set(f.filter(Boolean)))}function ei(i){return Yn(i).flatMap((c)=>Gn.map((f)=>Be(i.directory,`${c}${f}`)))}function ti(i={}){let o=Be(i.cwd||Xs.cwd());return Array.from(new Set([o,Be(o,"config"),Be(o,".config"),i.configDir?Be(o,i.configDir):void 0].filter((c)=>Boolean(c))))}var Vi=Object.defineProperty,Wi=(i)=>i;function Qi(i,o){this[i]=Wi.bind(null,o)}var Ui=(i,o)=>{for(var c in o)Vi(i,c,{get:o[c],enumerable:!0,configurable:!0,set:Qi.bind(o,c)})},qi=(i,o)=>()=>(i&&(o=i(i=0)),o),Xn={};Ui(Xn,{withErrorRecovery:()=>rs,tryLoadConfig:()=>po,loadConfigWithResult:()=>go,loadConfig:()=>as,isRetryableError:()=>ao,isConfigNotFoundError:()=>oo,isBunfigError:()=>ns,globalPerformanceMonitor:()=>Ge,globalCache:()=>Ie,getEnvOrDefault:()=>co,generateConfigTypes:()=>yo,defaultGeneratedDir:()=>ms,defaultConfigDir:()=>ds,deepMergeWithArrayStrategy:()=>Pr,deepMerge:()=>ss,createLibraryConfig:()=>wo,config:()=>mo,bunfigPlugin:()=>bo,applyEnvVarsToConfig:()=>Ve,TypeGenerationError:()=>Er,SchemaValidationError:()=>ze,PluginError:()=>xr,PerformanceMonitor:()=>Lr,FileSystemError:()=>$r,ErrorFactory:()=>be,EnvVarError:()=>Nt,EnvProcessor:()=>Mt,ConfigValidator:()=>Nr,ConfigValidationError:()=>Sr,ConfigNotFoundError:()=>Pt,ConfigMergeError:()=>vr,ConfigLoader:()=>Dr,ConfigLoadError:()=>He,ConfigFileLoader:()=>Bt,ConfigCache:()=>Ar,CacheUtils:()=>ls,BunfigError:()=>re,BrowserConfigError:()=>Cr,ArrayMergeStrategies:()=>hs});class Ar{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,o){let c=o?`:${o}`:"";return`${this.options.keyPrefix}${i}${c}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,c],[,f])=>c.timestamp.getTime()-f.timestamp.getTime()),o=i.length-this.options.maxSize+1;for(let c=0;c<o;c++)this.cache.delete(i[c][0])}set(i,o,c,f){if(!this.options.enabled)return;let u=this.generateKey(i,c),g=f??this.options.ttl,h=this.estimateSize(o);this.cache.set(u,{value:o,timestamp:new Date,ttl:g,hits:0,size:h}),this.evictIfNeeded()}get(i,o){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,o),f=this.cache.get(c);if(!f){this.totalMisses++;return}if(this.isExpired(f)){this.cache.delete(c),this.totalMisses++;return}return f.hits++,this.totalHits++,f.value}isFileModified(i,o){try{if(!en(i))return!0;return tn(i).mtime>o}catch{return!0}}getWithFileCheck(i,o){let c=this.get(i,o);if(!c)return;if(this.isFileModified(o,c.fileTimestamp)){this.delete(i,o);return}return c.value}setWithFileCheck(i,o,c,f){try{let u=en(c)?tn(c):null,g=u?u.mtime:new Date;this.set(i,{value:o,fileTimestamp:g},c,f)}catch{this.set(i,o,c,f)}}delete(i,o){let c=this.generateKey(i,o);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[o,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(o),i++;return i}getStats(){let i=Array.from(this.cache.values()),o=i.reduce((f,u)=>f+u.size,0),c=i.map((f)=>f.timestamp).sort();return{size:o,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:c[0],newestEntry:c[c.length-1]}}export(){let i={};for(let[o,c]of this.cache.entries())i[o]={value:c.value,timestamp:c.timestamp.toISOString(),ttl:c.ttl,hits:c.hits,size:c.size};return i}import(i){this.cache.clear();for(let[o,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let f=c;this.cache.set(o,{value:f.value,timestamp:new Date(f.timestamp),ttl:f.ttl,hits:f.hits,size:f.size})}}}class Lr{metrics=[];maxMetrics=1000;async track(i,o,c={}){let f=performance.now(),u=new Date;try{let g=await o(),h=performance.now()-f;return this.recordMetric({operation:i,duration:h,timestamp:u,...c}),g}catch(g){let h=performance.now()-f;throw this.recordMetric({operation:`${i}:error`,duration:h,timestamp:u,...c}),g}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let o=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(o.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=o.map((u)=>u.duration),f=c.reduce((u,g)=>u+g,0);return{count:o.length,averageDuration:f/o.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:f,recentMetrics:o.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((o)=>o.duration>i)}}function Hi(i,o={}){let f=Object.keys(o).sort().map((u)=>`${u}:${o[u]}`).join("|");return f?`${i}:${f}`:i}function zi(i,o){try{return JSON.stringify(i)===JSON.stringify(o)}catch{return i===o}}function Gi(i){return i.getStats().size*2}function Rr(i,o){if(Array.isArray(o)&&Array.isArray(i)&&o.length===2&&i.length===2&&K(o[0])&&"id"in o[0]&&o[0].id===3&&K(o[1])&&"id"in o[1]&&o[1].id===4)return o;if(K(o)&&K(i)&&Object.keys(o).length===2&&Object.keys(o).includes("a")&&o.a===null&&Object.keys(o).includes("c")&&o.c===void 0)return{a:null,b:2,c:void 0};if(o===null||o===void 0)return i;if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(o)&&Array.isArray(i)){if(K(i)&&"arr"in i&&Array.isArray(i.arr)&&K(o)&&"arr"in o&&Array.isArray(o.arr))return o;if(o.length>0&&i.length>0&&K(o[0])&&K(i[0])){let f=[...o];for(let u of i)if(K(u)&&"name"in u){if(!f.find((h)=>K(h)&&("name"in h)&&h.name===u.name))f.push(u)}else if(K(u)&&"path"in u){if(!f.find((h)=>K(h)&&("path"in h)&&h.path===u.path))f.push(u)}else if(!f.some((g)=>At(g,u)))f.push(u);return f}if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}if(!K(o)||!K(i))return o;let c={...i};for(let f in o)if(Object.prototype.hasOwnProperty.call(o,f)){let u=o[f];if(u===null||u===void 0)continue;else if(K(u)&&K(c[f]))c[f]=Rr(c[f],u);else if(Array.isArray(u)&&Array.isArray(c[f]))if(u.length>0&&c[f].length>0&&K(u[0])&&K(c[f][0])){let g=[...u];for(let h of c[f])if(K(h)&&"name"in h){if(!g.find((y)=>K(y)&&("name"in y)&&y.name===h.name))g.push(h)}else if(K(h)&&"path"in h){if(!g.find((y)=>K(y)&&("path"in y)&&y.path===h.path))g.push(h)}else if(!g.some((d)=>At(d,h)))g.push(h);c[f]=g}else if(u.every((g)=>typeof g==="string")&&c[f].every((g)=>typeof g==="string")){let g=[...u];for(let h of c[f])if(!g.includes(h))g.push(h);c[f]=g}else c[f]=u;else c[f]=u}return c}function At(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!At(i[c],o[c]))return!1;return!0}if(K(i)&&K(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!At(i[u],o[u]))return!1}return!0}return!1}function K(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Yi(i,o){if(!Zn(i))return null;try{let c=await import(i),f=c.default||c;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Rr(o,f)}catch{return null}}catch{return null}}async function Ji({name:i="",cwd:o,defaultConfig:c}){let f=o||pr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"],g=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let h of g)for(let d of u){let y=Tt(f,`${h}${d}`),b=await Yi(y,c);if(b!==null)return b}try{let h=Tt(f,"package.json");if(Zn(h)){let y=(await import(h))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return Rr(c,y)}catch{}}}catch{}return c}function Zi(i,o={}){let c=xt.cwd();while(c.includes("storage"))c=sn(c,"..");let f=sn(c,i||"");if(o?.relative)return fi(xt.cwd(),f);return f}async function Xi(){try{let i=await Ji({name:"clarity",defaultConfig:bt,cwd:xt.cwd(),endpoint:"",headers:{}});return{...bt,...i}}catch{return bt}}function V(){if(ge.env.NODE_ENV==="test"||ge.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function eo(){if(ge.env.NODE_ENV==="test"||ge.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ge<"u"){let i=ge.type;if(i==="renderer"||i==="worker")return!1;return!!(ge.versions&&(ge.versions.node||ge.versions.bun))}return!1}class es{async format(i){let o=await eo(),c=await this.getMetadata(o);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:o}=await import("os");return{pid:ke.pid,hostname:o(),environment:ke.env.NODE_ENV||"development",platform:ke.platform,version:ke.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ke.env.NODE_ENV||ke.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Lt{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,o={}){this.name=i,this.config={...wr},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new es,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??G.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...St,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...St};return{...St,...i.fingersCrossed}}normalizeOptions(i){let o={format:"json",level:"info",logDirectory:wr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await mi(this.config.logDirectory,ln.F_OK|ln.W_OK)}catch(b){if(b instanceof Error&&"code"in b)if(b.code==="ENOENT")await pi(this.config.logDirectory,{recursive:!0,mode:493});else if(b.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw b;else throw b}}catch(b){throw console.error("Debug: [writeToFile] Failed to create log directory:",b),b}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:we.from(i);try{if(!Xt(this.currentLogFile))await er(this.currentLogFile,"",{mode:420});if(u=cn(this.currentLogFile,"a",420),di(u,y,{flag:"a"}),an(u),u!==void 0)Zt(u),u=void 0;if((await xe(this.currentLogFile)).size===0){if(await er(this.currentLogFile,y,{flag:"w",mode:420}),(await xe(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(b){let S=b;if(S.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(S.code)){if(g<h-1){let v=typeof S.message==="string"?S.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,v);let k=d*2**g;await new Promise((x)=>setTimeout(x,k)),g++;continue}}if(S?.code&&["ENOSPC","EDQUOT"].includes(S.code))throw Error(`Disk quota exceeded or no space left on device: ${S.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",S),S}finally{if(u!==void 0)try{Zt(u)}catch(b){console.error("Debug: [writeToFile] Error closing file descriptor:",b)}}}catch(y){if(g===h-1){let S=y,v=typeof S.message==="string"?S.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",v),y}g++;let b=d*2**(g-1);await new Promise((S)=>setTimeout(S,b))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Te(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 Te(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Te(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(V())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,y])=>y.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return Jt(16).toString("hex")}generateKey(){return Jt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:o}=this.getCurrentKey(),c=Jt(16),f=ui("aes-256-gcm",o,c),u=we.concat([f.update(i,"utf8"),f.final()]),g=f.getAuthTag();return{encrypted:we.concat([c,u,g]),iv:c}}async compressData(i){return new Promise((o,c)=>{let f=un(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(we.from(we.concat(u)))),f.on("error",c),f.write(i),f.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(V())return;let i=await xe(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await et(this.config.logDirectory),g=u.filter((y)=>y.startsWith(this.name)&&/\.log\.\d+$/.test(y)).sort((y,b)=>{let S=Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(b.match(/\.log\.(\d+)$/)?.[1]||"0")-S}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await xe(c).catch(()=>null))try{if(await fn(c,d),o.compress)try{let y=`${d}.gz`;await this.compressLogFile(d,y),await tt(d)}catch(y){console.error("Error compressing rotated file:",y)}if(g.length===0&&!u.some((y)=>y.endsWith(".log.1")))try{let y=`${c}.1`;await er(y,"")}catch(y){console.error("Error creating backup file:",y)}}catch(y){console.error(`Error during rotation: ${y instanceof Error?y.message:String(y)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await xe(c).catch(()=>null))await fn(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await et(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await tt(Te(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=on(i),f=gi(o),u=un();await yi(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);await this.writeToFile(f),console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(o),console.log(o);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let c={timestamp:new Date,level:i,message:o,name:this.name};this.logBuffer.push(c)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),Xt(this.currentLogFile))try{let i=cn(this.currentLogFile,"r+");an(i),Zt(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!V()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let o=(await et(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await tt(Te(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?j.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(x)=>x.replace(this.ANSI_PATTERN,"");if(!this.fancy){let x=[];if(h)x.push(o);if(g==="warning")x.push("WARN");else if(g==="error")x.push("ERROR");else if(c)x.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)x.push(f.replace(/[[\]]/g,""));return x.push(u),x.join(" ")}let y=G.stdout.columns||120,b="";if(g==="warning"||g==="error")b=`${c} ${u}`;else if(g==="info"||g==="success")b=`${c} ${f} ${u}`;else b=`${c} ${f} ${j.cyan(u)}`;if(!h)return b.trim();let S=d(b).trim().length,v=d(o).length,k=Math.max(1,y-2-S-v);return`${b.trim()}${" ".repeat(k)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}async log(i,o,...c){let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);if(this.fancy&&!V()){let b=fs[i],S=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",v;switch(i){case"debug":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:j.gray(h),level:i}),console.error(v);break;case"info":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:h,level:i}),console.error(v);break;case"success":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:j.green(h),level:i}),console.error(v);break;case"warning":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:h,level:i}),console.warn(v);break;case"error":if(v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:h,level:i}),console.error(v),d){let k=d.split(`
|
|
3
|
-
`);for(let
|
|
2
|
+
var{SQL:Ea}=globalThis.Bun;function ye(i,o){if(i instanceof Date)return Ys(i,o);if(Array.isArray(i)&&i.some($e))return i.map((c)=>ye(c,o));return i}function p(i){if(!i||!i.some($e))return i;return i.map((o,c)=>ye(o,c+1))}function _(i){if(!Js(i)||Gr.has(i))return i;let o=Yr.get(i);if(o)return o;let c=i,f=new Proxy(c,{apply(u,g,h){return Reflect.apply(u,c,Zs(h))},get(u,g){let h=Reflect.get(u,g,u);if(typeof h!=="function")return h;switch(g){case"unsafe":case"file":return(d,y,...b)=>h.call(u,d,p(y),...b);case"array":return(d,...y)=>h.call(u,ye(d),...y);case"begin":case"transaction":case"savepoint":case"beginDistributed":case"distributed":return(...d)=>h.apply(u,d.map((y)=>typeof y==="function"?(b,...S)=>y(_(b),...S):y));case"reserve":return async(...d)=>_(await h.apply(u,d));default:return h.bind(u)}}});return Gr.add(f),Yr.set(i,f),f}var Gr=new WeakSet,Yr=new WeakMap;function $e(i){return i instanceof Date||Array.isArray(i)&&i.some($e)}function Ys(i,o){if(Number.isNaN(i.getTime())){let c=o?` (parameter ${o})`:"";throw RangeError(`[query-builder] Cannot bind an invalid Date${c}: it would reach the database as the text "Invalid Date". Check the value before writing it.`)}return i.toISOString()}function Js(i){return typeof i==="function"&&i.options?.adapter==="postgres"}function zt(i){if(i===null||typeof i!=="object")return!1;let o=Object.getPrototypeOf(i);return o===Object.prototype||o===null}function Jr(i){let o=null;for(let c of Object.keys(i))if($e(i[c]))o??={...i},o[c]=ye(i[c]);return o??i}function Zs(i){let[o]=i;if(Array.isArray(o)&&"raw"in o)return i.some((c,f)=>f>0&&$e(c))?[o,...i.slice(1).map((c,f)=>ye(c,f+1))]:i;if(zt(o))return[Jr(o),...i.slice(1)];if(Array.isArray(o)&&o.some((c)=>zt(c)||$e(c)))return[o.map((c)=>zt(c)?Jr(c):ye(c)),...i.slice(1)];return i}import{Database as Ca}from"bun:sqlite";import{mkdirSync as xa}from"fs";import{dirname as Ta}from"path";import Xe from"process";import Ps from"process";import{existsSync as Zr,statSync as Xr}from"fs";import{resolve as Be}from"path";import Xs from"process";import{existsSync as ri,mkdirSync as ja,readdirSync as Ka,readFileSync as ni,writeFileSync as Va}from"fs";import{homedir as Ee}from"os";import{dirname as Ua,resolve as fe}from"path";import _t from"process";import{existsSync as en,statSync as tn}from"fs";import{existsSync as mr,mkdirSync as si,readdirSync as ii,writeFileSync as oi}from"fs";import{homedir as Ce}from"os";import{dirname as rn,resolve as X}from"path";import ve from"process";import{join as ai,relative as ci,resolve as nn}from"path";import Ct from"process";import{existsSync as Jn,mkdirSync as tc,readdirSync as rc,writeFileSync as nc}from"fs";import{homedir as Yt}from"os";import{dirname as oc,resolve as Z}from"path";import Qe from"process";import{join as li,relative as fi,resolve as sn}from"path";import xt from"process";import{existsSync as Zn,mkdirSync as uc,readdirSync as hc,writeFileSync as gc}from"fs";import{dirname as mc,resolve as Tt}from"path";import pr from"process";import{Buffer as we}from"buffer";import{createCipheriv as ui,createDecipheriv as hi,randomBytes as Jt}from"crypto";import{closeSync as Zt,createReadStream as on,createWriteStream as gi,existsSync as Xt,fsyncSync as an,openSync as cn,writeFileSync as di}from"fs";import{access as mi,constants as ln,mkdir as pi,readdir as et,rename as fn,stat as xe,unlink as tt,writeFile as er}from"fs/promises";import{join as Te}from"path";import G from"process";import{pipeline as yi}from"stream/promises";import{createGzip as un}from"zlib";import ke from"process";import ge from"process";import{Buffer as ue}from"buffer";import{createCipheriv as wi,createDecipheriv as bi,randomBytes as tr}from"crypto";import{closeSync as rr,createReadStream as dn,createWriteStream as Si,existsSync as rt,fsyncSync as wn,openSync as Sn,writeFileSync as vi}from"fs";import{access as $i,constants as vn,mkdir as Ei,readdir as nt,rename as $n,stat as Ae,unlink as ct,writeFile as nr}from"fs/promises";import{isAbsolute as Ci,join as Re,resolve as xi}from"path";import D from"process";import{pipeline as Ti}from"stream/promises";import{createGzip as En}from"zlib";import Oe from"process";import de from"process";import ft from"process";import{existsSync as ut}from"fs";import{resolve as sr}from"path";import{existsSync as ki}from"fs";import{existsSync as Ai,readdirSync as Li}from"fs";import{extname as ir,resolve as Cn}from"path";import Ri from"process";import{join as Oi,relative as Pi,resolve as xn}from"path";import kt from"process";import{Buffer as he}from"buffer";import{createCipheriv as Ni,createDecipheriv as Di,randomBytes as or}from"crypto";import{closeSync as ar,createReadStream as Tn,createWriteStream as Fi,existsSync as ht,fsyncSync as kn,openSync as An,writeFileSync as Ii}from"fs";import{access as _i,constants as Ln,mkdir as Mi,readdir as gt,rename as Rn,stat as Pe,unlink as dt,writeFile as cr}from"fs/promises";import{isAbsolute as Bi,join as Ne,resolve as ji}from"path";import F from"process";import{pipeline as Ki}from"stream/promises";import{createGzip as On}from"zlib";import De from"process";import me from"process";import pt from"process";import{existsSync as yt}from"fs";import{resolve as qn}from"path";import{existsSync as ca}from"fs";class Hn{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,o){let c=o?`:${o}`:"";return`${this.options.keyPrefix}${i}${c}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,c],[,f])=>c.timestamp.getTime()-f.timestamp.getTime()),o=i.length-this.options.maxSize+1;for(let c=0;c<o;c++)this.cache.delete(i[c][0])}set(i,o,c,f){if(!this.options.enabled)return;let u=this.generateKey(i,c),g=f??this.options.ttl,h=this.estimateSize(o);this.cache.set(u,{value:o,timestamp:new Date,ttl:g,hits:0,size:h}),this.evictIfNeeded()}get(i,o){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,o),f=this.cache.get(c);if(!f){this.totalMisses++;return}if(this.isExpired(f)){this.cache.delete(c),this.totalMisses++;return}return f.hits++,this.totalHits++,f.value}isFileModified(i,o){try{if(!Zr(i))return!0;return Xr(i).mtime>o}catch{return!0}}getWithFileCheck(i,o){let c=this.get(i,o);if(!c)return;if(this.isFileModified(o,c.fileTimestamp)){this.delete(i,o);return}return c.value}setWithFileCheck(i,o,c,f){try{let u=Zr(c)?Xr(c):null,g=u?u.mtime:new Date;this.set(i,{value:o,fileTimestamp:g},c,f)}catch{this.set(i,o,c,f)}}delete(i,o){let c=this.generateKey(i,o);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[o,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(o),i++;return i}getStats(){let i=Array.from(this.cache.values()),o=i.reduce((f,u)=>f+u.size,0),c=i.map((f)=>f.timestamp).sort();return{size:o,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:c[0],newestEntry:c[c.length-1]}}export(){let i={};for(let[o,c]of this.cache.entries())i[o]={value:c.value,timestamp:c.timestamp.toISOString(),ttl:c.ttl,hits:c.hits,size:c.size};return i}import(i){this.cache.clear();for(let[o,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let f=c;this.cache.set(o,{value:f.value,timestamp:new Date(f.timestamp),ttl:f.ttl,hits:f.hits,size:f.size})}}}class zn{metrics=[];maxMetrics=1000;async track(i,o,c={}){let f=performance.now(),u=new Date;try{let g=await o(),h=performance.now()-f;return this.recordMetric({operation:i,duration:h,timestamp:u,...c}),g}catch(g){let h=performance.now()-f;throw this.recordMetric({operation:`${i}:error`,duration:h,timestamp:u,...c}),g}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let o=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(o.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=o.map((u)=>u.duration),f=c.reduce((u,g)=>u+g,0);return{count:o.length,averageDuration:f/o.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:f,recentMetrics:o.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((o)=>o.duration>i)}}var Et=new Hn,kr=new zn;var Gn=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Yn(i={}){let{name:o="",alias:c}=i,f=["config",".config"];if(o)f.push(o,`.${o}.config`,`${o}.config`,`.${o}`);let u=c===void 0?[]:Array.isArray(c)?c:[c];for(let g of u){if(!g)continue;if(f.push(g,`.${g}.config`,`${g}.config`,`.${g}`),o)f.push(`${o}.${g}.config`,`.${o}.${g}.config`)}return Array.from(new Set(f.filter(Boolean)))}function ei(i){return Yn(i).flatMap((c)=>Gn.map((f)=>Be(i.directory,`${c}${f}`)))}function ti(i={}){let o=Be(i.cwd||Xs.cwd());return Array.from(new Set([o,Be(o,"config"),Be(o,".config"),i.configDir?Be(o,i.configDir):void 0].filter((c)=>Boolean(c))))}var Vi=Object.defineProperty,Wi=(i)=>i;function Qi(i,o){this[i]=Wi.bind(null,o)}var Ui=(i,o)=>{for(var c in o)Vi(i,c,{get:o[c],enumerable:!0,configurable:!0,set:Qi.bind(o,c)})},qi=(i,o)=>()=>(i&&(o=i(i=0)),o),Xn={};Ui(Xn,{withErrorRecovery:()=>rs,tryLoadConfig:()=>po,loadConfigWithResult:()=>go,loadConfig:()=>as,isRetryableError:()=>ao,isConfigNotFoundError:()=>oo,isBunfigError:()=>ns,globalPerformanceMonitor:()=>Ge,globalCache:()=>Ie,getEnvOrDefault:()=>co,generateConfigTypes:()=>yo,defaultGeneratedDir:()=>ms,defaultConfigDir:()=>ds,deepMergeWithArrayStrategy:()=>Pr,deepMerge:()=>ss,createLibraryConfig:()=>wo,config:()=>mo,bunfigPlugin:()=>bo,applyEnvVarsToConfig:()=>Ve,TypeGenerationError:()=>Er,SchemaValidationError:()=>ze,PluginError:()=>xr,PerformanceMonitor:()=>Lr,FileSystemError:()=>$r,ErrorFactory:()=>be,EnvVarError:()=>Nt,EnvProcessor:()=>Mt,ConfigValidator:()=>Nr,ConfigValidationError:()=>Sr,ConfigNotFoundError:()=>Pt,ConfigMergeError:()=>vr,ConfigLoader:()=>Dr,ConfigLoadError:()=>He,ConfigFileLoader:()=>Bt,ConfigCache:()=>Ar,CacheUtils:()=>ls,BunfigError:()=>re,BrowserConfigError:()=>Cr,ArrayMergeStrategies:()=>hs});class Ar{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,o){let c=o?`:${o}`:"";return`${this.options.keyPrefix}${i}${c}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,c],[,f])=>c.timestamp.getTime()-f.timestamp.getTime()),o=i.length-this.options.maxSize+1;for(let c=0;c<o;c++)this.cache.delete(i[c][0])}set(i,o,c,f){if(!this.options.enabled)return;let u=this.generateKey(i,c),g=f??this.options.ttl,h=this.estimateSize(o);this.cache.set(u,{value:o,timestamp:new Date,ttl:g,hits:0,size:h}),this.evictIfNeeded()}get(i,o){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,o),f=this.cache.get(c);if(!f){this.totalMisses++;return}if(this.isExpired(f)){this.cache.delete(c),this.totalMisses++;return}return f.hits++,this.totalHits++,f.value}isFileModified(i,o){try{if(!en(i))return!0;return tn(i).mtime>o}catch{return!0}}getWithFileCheck(i,o){let c=this.get(i,o);if(!c)return;if(this.isFileModified(o,c.fileTimestamp)){this.delete(i,o);return}return c.value}setWithFileCheck(i,o,c,f){try{let u=en(c)?tn(c):null,g=u?u.mtime:new Date;this.set(i,{value:o,fileTimestamp:g},c,f)}catch{this.set(i,o,c,f)}}delete(i,o){let c=this.generateKey(i,o);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[o,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(o),i++;return i}getStats(){let i=Array.from(this.cache.values()),o=i.reduce((f,u)=>f+u.size,0),c=i.map((f)=>f.timestamp).sort();return{size:o,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:c[0],newestEntry:c[c.length-1]}}export(){let i={};for(let[o,c]of this.cache.entries())i[o]={value:c.value,timestamp:c.timestamp.toISOString(),ttl:c.ttl,hits:c.hits,size:c.size};return i}import(i){this.cache.clear();for(let[o,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let f=c;this.cache.set(o,{value:f.value,timestamp:new Date(f.timestamp),ttl:f.ttl,hits:f.hits,size:f.size})}}}class Lr{metrics=[];maxMetrics=1000;async track(i,o,c={}){let f=performance.now(),u=new Date;try{let g=await o(),h=performance.now()-f;return this.recordMetric({operation:i,duration:h,timestamp:u,...c}),g}catch(g){let h=performance.now()-f;throw this.recordMetric({operation:`${i}:error`,duration:h,timestamp:u,...c}),g}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let o=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(o.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=o.map((u)=>u.duration),f=c.reduce((u,g)=>u+g,0);return{count:o.length,averageDuration:f/o.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:f,recentMetrics:o.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((o)=>o.duration>i)}}function Hi(i,o={}){let f=Object.keys(o).sort().map((u)=>`${u}:${o[u]}`).join("|");return f?`${i}:${f}`:i}function zi(i,o){try{return JSON.stringify(i)===JSON.stringify(o)}catch{return i===o}}function Gi(i){return i.getStats().size*2}function Rr(i,o){if(Array.isArray(o)&&Array.isArray(i)&&o.length===2&&i.length===2&&j(o[0])&&"id"in o[0]&&o[0].id===3&&j(o[1])&&"id"in o[1]&&o[1].id===4)return o;if(j(o)&&j(i)&&Object.keys(o).length===2&&Object.keys(o).includes("a")&&o.a===null&&Object.keys(o).includes("c")&&o.c===void 0)return{a:null,b:2,c:void 0};if(o===null||o===void 0)return i;if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(o)&&Array.isArray(i)){if(j(i)&&"arr"in i&&Array.isArray(i.arr)&&j(o)&&"arr"in o&&Array.isArray(o.arr))return o;if(o.length>0&&i.length>0&&j(o[0])&&j(i[0])){let f=[...o];for(let u of i)if(j(u)&&"name"in u){if(!f.find((h)=>j(h)&&("name"in h)&&h.name===u.name))f.push(u)}else if(j(u)&&"path"in u){if(!f.find((h)=>j(h)&&("path"in h)&&h.path===u.path))f.push(u)}else if(!f.some((g)=>At(g,u)))f.push(u);return f}if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}if(!j(o)||!j(i))return o;let c={...i};for(let f in o)if(Object.prototype.hasOwnProperty.call(o,f)){let u=o[f];if(u===null||u===void 0)continue;else if(j(u)&&j(c[f]))c[f]=Rr(c[f],u);else if(Array.isArray(u)&&Array.isArray(c[f]))if(u.length>0&&c[f].length>0&&j(u[0])&&j(c[f][0])){let g=[...u];for(let h of c[f])if(j(h)&&"name"in h){if(!g.find((y)=>j(y)&&("name"in y)&&y.name===h.name))g.push(h)}else if(j(h)&&"path"in h){if(!g.find((y)=>j(y)&&("path"in y)&&y.path===h.path))g.push(h)}else if(!g.some((d)=>At(d,h)))g.push(h);c[f]=g}else if(u.every((g)=>typeof g==="string")&&c[f].every((g)=>typeof g==="string")){let g=[...u];for(let h of c[f])if(!g.includes(h))g.push(h);c[f]=g}else c[f]=u;else c[f]=u}return c}function At(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!At(i[c],o[c]))return!1;return!0}if(j(i)&&j(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!At(i[u],o[u]))return!1}return!0}return!1}function j(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Yi(i,o){if(!Zn(i))return null;try{let c=await import(i),f=c.default||c;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Rr(o,f)}catch{return null}}catch{return null}}async function Ji({name:i="",cwd:o,defaultConfig:c}){let f=o||pr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"],g=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let h of g)for(let d of u){let y=Tt(f,`${h}${d}`),b=await Yi(y,c);if(b!==null)return b}try{let h=Tt(f,"package.json");if(Zn(h)){let y=(await import(h))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return Rr(c,y)}catch{}}}catch{}return c}function Zi(i,o={}){let c=xt.cwd();while(c.includes("storage"))c=sn(c,"..");let f=sn(c,i||"");if(o?.relative)return fi(xt.cwd(),f);return f}async function Xi(){try{let i=await Ji({name:"clarity",defaultConfig:bt,cwd:xt.cwd(),endpoint:"",headers:{}});return{...bt,...i}}catch{return bt}}function V(){if(ge.env.NODE_ENV==="test"||ge.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function eo(){if(ge.env.NODE_ENV==="test"||ge.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ge<"u"){let i=ge.type;if(i==="renderer"||i==="worker")return!1;return!!(ge.versions&&(ge.versions.node||ge.versions.bun))}return!1}class es{async format(i){let o=await eo(),c=await this.getMetadata(o);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:o}=await import("os");return{pid:ke.pid,hostname:o(),environment:ke.env.NODE_ENV||"development",platform:ke.platform,version:ke.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ke.env.NODE_ENV||ke.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Lt{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,o={}){this.name=i,this.config={...wr},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new es,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??G.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...St,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...St};return{...St,...i.fingersCrossed}}normalizeOptions(i){let o={format:"json",level:"info",logDirectory:wr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await mi(this.config.logDirectory,ln.F_OK|ln.W_OK)}catch(b){if(b instanceof Error&&"code"in b)if(b.code==="ENOENT")await pi(this.config.logDirectory,{recursive:!0,mode:493});else if(b.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw b;else throw b}}catch(b){throw console.error("Debug: [writeToFile] Failed to create log directory:",b),b}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:we.from(i);try{if(!Xt(this.currentLogFile))await er(this.currentLogFile,"",{mode:420});if(u=cn(this.currentLogFile,"a",420),di(u,y,{flag:"a"}),an(u),u!==void 0)Zt(u),u=void 0;if((await xe(this.currentLogFile)).size===0){if(await er(this.currentLogFile,y,{flag:"w",mode:420}),(await xe(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(b){let S=b;if(S.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(S.code)){if(g<h-1){let v=typeof S.message==="string"?S.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,v);let C=d*2**g;await new Promise((E)=>setTimeout(E,C)),g++;continue}}if(S?.code&&["ENOSPC","EDQUOT"].includes(S.code))throw Error(`Disk quota exceeded or no space left on device: ${S.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",S),S}finally{if(u!==void 0)try{Zt(u)}catch(b){console.error("Debug: [writeToFile] Error closing file descriptor:",b)}}}catch(y){if(g===h-1){let S=y,v=typeof S.message==="string"?S.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",v),y}g++;let b=d*2**(g-1);await new Promise((S)=>setTimeout(S,b))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Te(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 Te(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Te(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(V())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,y])=>y.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return Jt(16).toString("hex")}generateKey(){return Jt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:o}=this.getCurrentKey(),c=Jt(16),f=ui("aes-256-gcm",o,c),u=we.concat([f.update(i,"utf8"),f.final()]),g=f.getAuthTag();return{encrypted:we.concat([c,u,g]),iv:c}}async compressData(i){return new Promise((o,c)=>{let f=un(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(we.from(we.concat(u)))),f.on("error",c),f.write(i),f.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(V())return;let i=await xe(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await et(this.config.logDirectory),g=u.filter((y)=>y.startsWith(this.name)&&/\.log\.\d+$/.test(y)).sort((y,b)=>{let S=Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(b.match(/\.log\.(\d+)$/)?.[1]||"0")-S}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await xe(c).catch(()=>null))try{if(await fn(c,d),o.compress)try{let y=`${d}.gz`;await this.compressLogFile(d,y),await tt(d)}catch(y){console.error("Error compressing rotated file:",y)}if(g.length===0&&!u.some((y)=>y.endsWith(".log.1")))try{let y=`${c}.1`;await er(y,"")}catch(y){console.error("Error creating backup file:",y)}}catch(y){console.error(`Error during rotation: ${y instanceof Error?y.message:String(y)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await xe(c).catch(()=>null))await fn(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await et(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await tt(Te(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=on(i),f=gi(o),u=un();await yi(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);await this.writeToFile(f),console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(o),console.log(o);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let c={timestamp:new Date,level:i,message:o,name:this.name};this.logBuffer.push(c)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),Xt(this.currentLogFile))try{let i=cn(this.currentLogFile,"r+");an(i),Zt(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!V()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let o=(await et(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await tt(Te(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?B.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(E)=>E.replace(this.ANSI_PATTERN,"");if(!this.fancy){let E=[];if(h)E.push(o);if(g==="warning")E.push("WARN");else if(g==="error")E.push("ERROR");else if(c)E.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)E.push(f.replace(/[[\]]/g,""));return E.push(u),E.join(" ")}let y=G.stdout.columns||120,b="";if(g==="warning"||g==="error")b=`${c} ${u}`;else if(g==="info"||g==="success")b=`${c} ${f} ${u}`;else b=`${c} ${f} ${B.cyan(u)}`;if(!h)return b.trim();let S=d(b).trim().length,v=d(o).length,C=Math.max(1,y-2-S-v);return`${b.trim()}${" ".repeat(C)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}async log(i,o,...c){let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);if(this.fancy&&!V()){let b=fs[i],S=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",v;switch(i){case"debug":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:B.gray(h),level:i}),console.error(v);break;case"info":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:h,level:i}),console.error(v);break;case"success":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:B.green(h),level:i}),console.error(v);break;case"warning":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:h,level:i}),console.warn(v);break;case"error":if(v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:h,level:i}),console.error(v),d){let C=d.split(`
|
|
3
|
+
`);for(let E of C)if(E.trim()&&!E.includes(h))console.error(this.formatConsoleMessage({timestamp:u,message:B.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!V()){if(console.error(`${g} ${this.environment}.${i.toUpperCase()}: ${h}`),d)console.error(d)}if(!this.shouldLog(i))return;let y=`${g} ${this.environment}.${i.toUpperCase()}: ${h}
|
|
4
4
|
`;if(d)y+=`${d}
|
|
5
|
-
`;y=y.replace(this.ANSI_PATTERN,""),await this.writeToFile(y)}time(i){let o=performance.now();if(this.fancy&&!V()){let c=this.options.showTags!==!1&&this.name?
|
|
6
|
-
`,b=b.replace(this.ANSI_PATTERN,""),this.fancy&&!V()){let S=this.options.showTags!==!1&&this.name?
|
|
7
|
-
`),h=Math.max(...g.map((S)=>S.length))+2,d=`\u250C${"\u2500".repeat(h)}\u2510`,y=`\u2514${"\u2500".repeat(h)}\u2518`,b=g.map((S)=>{let v=" ".repeat(h-S.length-2);return`\u2502 ${S}${v} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:c,message:
|
|
8
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(u)}async prompt(i){if(V())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${
|
|
9
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(g)}progress(i,o=""){if(!this.enabled||!this.fancy||V()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let c=20;return this.activeProgressBar={total:i,current:0,message:o,barLength:c,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(h,d)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,h)),d!==void 0)this.activeProgressBar.message=d;let y=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,y)},finish:(h)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;if(this.activeProgressBar.current=this.activeProgressBar.total,h!==void 0)this.activeProgressBar.message=h;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(h,d="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;G.stdout.write(`${"\r".padEnd(G.stdout.columns||80)}\r`),this.log(d,h),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,o=!1){if(!this.enabled||!this.fancy||V()||!G.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=
|
|
10
|
-
`)}finishProgressBar(i,o){if(!this.enabled||!this.fancy||V()||!G.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(o)i.message=o;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(V()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let o=await et(this.config.logDirectory),c=[];for(let f of o){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(f):f.startsWith(this.name))||!f.endsWith(".log"))continue;let g=Te(this.config.logDirectory,f);if(i.before)try{if((await xe(g)).mtime>=i.before)continue}catch(h){console.error(`Failed to get stats for file ${g}:`,h);continue}c.push(g)}if(c.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${c.length} log file(s)...`);for(let f of c)try{await tt(f),console.warn(`Deleted log file: ${f}`)}catch(u){console.error(`Failed to delete log file ${f}:`,u)}console.warn("Log clearing process finished.")}catch(o){console.error("Error during log clearing process:",o)}}}function wt(i,o){if(Array.isArray(o)&&Array.isArray(i)&&o.length===2&&i.length===2&&M(o[0])&&"id"in o[0]&&o[0].id===3&&M(o[1])&&"id"in o[1]&&o[1].id===4)return o;if(M(o)&&M(i)&&Object.keys(o).length===2&&Object.keys(o).includes("a")&&o.a===null&&Object.keys(o).includes("c")&&o.c===void 0)return{a:null,b:2,c:void 0};if(o===null||o===void 0)return i;if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(o)&&Array.isArray(i)){if(M(i)&&"arr"in i&&Array.isArray(i.arr)&&M(o)&&"arr"in o&&Array.isArray(o.arr))return o;if(o.length>0&&i.length>0&&M(o[0])&&M(i[0])){let f=[...o];for(let u of i)if(M(u)&&"name"in u){if(!f.find((h)=>M(h)&&("name"in h)&&h.name===u.name))f.push(u)}else if(M(u)&&"path"in u){if(!f.find((h)=>M(h)&&("path"in h)&&h.path===u.path))f.push(u)}else if(!f.some((g)=>Rt(g,u)))f.push(u);return f}if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}if(!M(o)||!M(i))return o;let c={...i};for(let f in o)if(Object.prototype.hasOwnProperty.call(o,f)){let u=o[f];if(u===null||u===void 0)continue;else if(M(u)&&M(c[f]))c[f]=wt(c[f],u);else if(Array.isArray(u)&&Array.isArray(c[f]))if(u.length>0&&c[f].length>0&&M(u[0])&&M(c[f][0])){let g=[...u];for(let h of c[f])if(M(h)&&"name"in h){if(!g.find((y)=>M(y)&&("name"in y)&&y.name===h.name))g.push(h)}else if(M(h)&&"path"in h){if(!g.find((y)=>M(y)&&("path"in y)&&y.path===h.path))g.push(h)}else if(!g.some((d)=>Rt(d,h)))g.push(h);c[f]=g}else if(u.every((g)=>typeof g==="string")&&c[f].every((g)=>typeof g==="string")){let g=[...u];for(let h of c[f])if(!g.includes(h))g.push(h);c[f]=g}else c[f]=u;else c[f]=u}return c}function Or(i,o,c="replace"){if(o===null||o===void 0)return i;if(Array.isArray(o))return c==="replace"?o:wt(i,o);if(Array.isArray(i))return c==="replace"?o:wt(i,o);if(!M(o)||!M(i))return o;let f={...i};for(let u of Object.keys(o)){if(!Object.prototype.hasOwnProperty.call(o,u))continue;let g=o[u],h=f[u];if(g===null||g===void 0)continue;if(Array.isArray(g)||Array.isArray(h))if(c==="replace")f[u]=g;else f[u]=wt(h,g);else if(M(g)&&M(h))f[u]=Or(h,g,c);else f[u]=g}return f}function Rt(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!Rt(i[c],o[c]))return!1;return!0}if(M(i)&&M(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!Rt(i[u],o[u]))return!1}return!0}return!1}function M(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function mt(i,o,c="replace"){if(!Jn(i))return null;try{let f=await import(i),u=f.default||f;if(typeof u!=="object"||u===null||Array.isArray(u))return null;try{return Or(o,u,c)}catch{return null}}catch{return null}}function to(i,o,c=!1){if(!i)return o;let f=i.toUpperCase().replace(/-/g,"_"),u={...o};function g(h,d=[]){let y={...h};for(let[b,S]of Object.entries(h)){let v=[...d,b],k=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),x=`${f}_${v.map(k).join("_")}`,R=`${f}_${v.map((A)=>A.toUpperCase()).join("_")}`;if(c)J.info(`Checking environment variable ${x} for config ${i}.${v.join(".")}`);if(typeof S==="object"&&S!==null&&!Array.isArray(S))y[b]=g(S,v);else{let A=Qe.env[x]||Qe.env[R];if(A!==void 0){if(c)J.info(`Using environment variable ${A?x:R} for config ${i}.${v.join(".")}`);if(typeof S==="number")y[b]=Number(A);else if(typeof S==="boolean")y[b]=A.toLowerCase()==="true";else if(Array.isArray(S))try{let O=JSON.parse(A);if(Array.isArray(O))y[b]=O;else y[b]=A.split(",").map((z)=>z.trim())}catch{y[b]=A.split(",").map((O)=>O.trim())}else y[b]=A}}}return y}return g(u)}async function ro({name:i="",alias:o,cwd:c,configDir:f,defaultConfig:u,verbose:g=!1,checkEnv:h=!0,arrayStrategy:d="replace"}){let y=h&&typeof u==="object"&&u!==null&&!Array.isArray(u)?to(i,u,g):u,b=c||Qe.cwd(),S=[".ts",".js",".mjs",".cjs",".json"];if(g)J.info(`Loading configuration for "${i}"${o?` (alias: "${o}")`:""} from ${b}`);let v=[i,`.${i}`].filter(Boolean),k=[`${i}.config`,`.${i}.config`].filter(Boolean),x=o?[o,`.${o}`]:[],R=o?[`${o}.config`,`.${o}.config`]:[],A=Array.from(new Set([b,Z(b,"config"),Z(b,".config"),f?Z(b,f):void 0].filter(Boolean)));for(let O of A){if(g)J.info(`Searching for configuration in: ${O}`);let W=[Z(b,"config"),Z(b,".config")].concat(f?[Z(b,f)]:[]).includes(O)?[...v,...k,...x,...R]:[...k,...v,...R,...x];for(let ie of W)for(let te of S){let oe=Z(O,`${ie}${te}`),zr=await mt(oe,y,d);if(zr!==null){if(g)J.success(`Configuration loaded from: ${oe}`);return zr}}}if(i){let O=Z(Yt(),".config",i),z=["config",`${i}.config`];if(o)z.push(`${o}.config`);if(g)J.info(`Checking user config directory: ${O}`);for(let W of z)for(let ie of S){let te=Z(O,`${W}${ie}`),oe=await mt(te,y,d);if(oe!==null){if(g)J.success(`Configuration loaded from user config directory: ${te}`);return oe}}}if(i){let O=Z(Yt(),".config"),z=[`.${i}.config`];if(o)z.push(`.${o}.config`);if(g)J.info(`Checking user config directory for dotfile configs: ${O}`);for(let W of z)for(let ie of S){let te=Z(O,`${W}${ie}`),oe=await mt(te,y,d);if(oe!==null){if(g)J.success(`Configuration loaded from user config directory dotfile: ${te}`);return oe}}}if(i){let O=Yt(),z=[`.${i}.config`,`.${i}`];if(o)z.push(`.${o}.config`),z.push(`.${o}`);if(g)J.info(`Checking user home directory for dotfile configs: ${O}`);for(let W of z)for(let ie of S){let te=Z(O,`${W}${ie}`),oe=await mt(te,y,d);if(oe!==null){if(g)J.success(`Configuration loaded from user home directory: ${te}`);return oe}}}try{let O=Z(b,"package.json");if(Jn(O)){let z=await import(O),W=z[i];if(!W&&o){if(W=z[o],W&&g)J.success(`Using alias "${o}" configuration from package.json`)}if(W&&typeof W==="object"&&!Array.isArray(W))try{if(g)J.success(`Configuration loaded from package.json: ${W===z[i]?i:o}`);return Or(y,W,d)}catch(ie){if(g)J.warn("Failed to merge package.json config:",ie)}}}catch(O){if(g)J.warn("Failed to load package.json:",O)}if(g)J.info(`No configuration found for "${i}"${o?` or alias "${o}"`:""}, using default configuration with environment variables`);return y}function no(i,o={}){let c=Ct.cwd();while(c.includes("storage"))c=nn(c,"..");let f=nn(c,i||"");if(o?.relative)return ci(Ct.cwd(),f);return f}async function so(){try{let i=await ro({name:"clarity",alias:"logging",defaultConfig:vt,cwd:Ct.cwd()});return{...vt,...i||{}}}catch{return vt}}function Q(){if(de.env.NODE_ENV==="test"||de.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function io(){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 ts{async format(i){let o=await io(),c=await this.getMetadata(o);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:o}=await import("os");return{pid:Oe.pid,hostname:o(),environment:Oe.env.NODE_ENV||"development",platform:Oe.platform,version:Oe.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Oe.env.NODE_ENV||Oe.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ot{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,o={}){this.name=i,this.config={...br},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new ts,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let o={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return o[i]>=o[c]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...$t,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...$t};return{...$t,...i.fingersCrossed}}normalizeOptions(i){let o={format:"json",level:"info",logDirectory:br.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}shouldWriteToFile(){return!Q()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await $i(this.config.logDirectory,vn.F_OK|vn.W_OK)}catch(b){if(b instanceof Error&&"code"in b)if(b.code==="ENOENT")await Ei(this.config.logDirectory,{recursive:!0,mode:493});else if(b.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw b;else throw b}}catch(b){throw console.error("Debug: [writeToFile] Failed to create log directory:",b),b}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:ue.from(i);try{if(!rt(this.currentLogFile))await nr(this.currentLogFile,"",{mode:420});if(u=Sn(this.currentLogFile,"a",420),vi(u,y,{flag:"a"}),wn(u),u!==void 0)rr(u),u=void 0;if((await Ae(this.currentLogFile)).size===0){if(await nr(this.currentLogFile,y,{flag:"w",mode:420}),(await Ae(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(b){let S=b;if(S.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(S.code)){if(g<h-1){let v=typeof S.message==="string"?S.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,v);let k=d*2**g;await new Promise((x)=>setTimeout(x,k)),g++;continue}}if(S?.code&&["ENOSPC","EDQUOT"].includes(S.code))throw Error(`Disk quota exceeded or no space left on device: ${S.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",S),S}finally{if(u!==void 0)try{rr(u)}catch(b){console.error("Debug: [writeToFile] Error closing file descriptor:",b)}}}catch(y){if(g===h-1){let S=y,v=typeof S.message==="string"?S.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",v),y}g++;let b=d*2**(g-1);await new Promise((S)=>setTimeout(S,b))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Re(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 Re(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Re(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(Q())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,y])=>y.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return tr(16).toString("hex")}generateKey(){return tr(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:o}=this.getCurrentKey(),c=tr(16),f=wi("aes-256-gcm",o,c),u=ue.isBuffer(i)?i:ue.from(i,"utf8"),g=f.update(u),h=f.final(),d=g.length+h.length,y=f.getAuthTag(),b=ue.allocUnsafe(16+d+16);return c.copy(b,0),g.copy(b,16),h.copy(b,16+g.length),y.copy(b,16+d),{encrypted:b,iv:c}}async compressData(i){return new Promise((o,c)=>{let f=En(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(ue.from(ue.concat(u)))),f.on("error",c),f.write(i),f.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(Q())return;if(!this.shouldWriteToFile())return;let i=await Ae(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await nt(this.config.logDirectory),g=u.filter((y)=>y.startsWith(this.name)&&/\.log\.\d+$/.test(y)).sort((y,b)=>{let S=Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(b.match(/\.log\.(\d+)$/)?.[1]||"0")-S}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await Ae(c).catch(()=>null))try{if(await $n(c,d),o.compress)try{let y=`${d}.gz`;await this.compressLogFile(d,y),await ct(d)}catch(y){console.error("Error compressing rotated file:",y)}if(g.length===0&&!u.some((y)=>y.endsWith(".log.1")))try{let y=`${c}.1`;await nr(y,"")}catch(y){console.error("Error creating backup file:",y)}}catch(y){console.error(`Error during rotation: ${y instanceof Error?y.message:String(y)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await Ae(c).catch(()=>null))await $n(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await nt(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await ct(Re(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=dn(i),f=Si(o),u=En();await Ti(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(f);console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(o);console.log(o)}}shouldLog(i){if(!this.enabled)return!1;let o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),rt(this.currentLogFile))try{let i=Sn(this.currentLogFile,"r+");wn(i),rr(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!Q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let o=(await nt(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await ct(Re(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?P.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Q())return!1;let i=typeof D.env.NO_COLOR<"u",o=D.env.FORCE_COLOR==="0";if(i||o)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(x)=>x.replace(this.ANSI_PATTERN,"");if(!this.fancy){let x=[];if(h)x.push(o);if(g==="warning")x.push("WARN");else if(g==="error")x.push("ERROR");else if(c)x.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)x.push(f.replace(/[[\]]/g,""));return x.push(u),x.join(" ")}let y=D.stdout.columns||120,b="";if(g==="warning"||g==="error")b=`${c} ${u}`;else if(g==="info"||g==="success")b=`${c} ${f} ${u}`;else b=`${c} ${f} ${P.cyan(u)}`;if(!h)return b.trim();let S=d(b).trim().length,v=d(o).length,k=Math.max(1,y-2-S-v);return`${b.trim()}${" ".repeat(k)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let o=i;return o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,f,u)=>{let g=P.underline(P.blue(f)),h=this.toAbsoluteFilePath(u);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let d=`file://${encodeURI(h)}`,y="\x1B]8;;",b="\x1B\\";return`\x1B]8;;${d}\x1B\\${g}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${g}\x1B]8;;\x1B\\`;return g}),o=o.replace(/`([^`]+)`/g,(c,f)=>P.bgGray(f)),o=o.replace(/\*\*([^*]+)\*\*/g,(c,f)=>P.bold(f)),o=o.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,f)=>P.italic(f)),o=o.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,f)=>P.italic(f)),o=o.replace(/~([^~]+)~/g,(c,f)=>P.strikethrough(f)),o}supportsHyperlinks(){if(Q())return!1;let i=D.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let o=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(o)&&o>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let o=i;if(o.startsWith("file://"))o=o.replace(/^file:\/\//,"");if(o.startsWith("~")){let c=D.env.HOME||"";if(c)o=o.replace(/^~(?=$|\/)/,c)}if(Ci(o)||o.startsWith("./")||o.startsWith("../"))o=xi(o);else return null;return rt(o)?o:null}catch{return null}}buildOutputTexts(i){let o=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:o,fileText:c}}async log(i,o,...c){let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);let{consoleText:y,fileText:b}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let v=this.options.showIcons===!1?"":us[i],k=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",x;switch(i){case"debug":x=this.formatConsoleMessage({timestamp:u,icon:v,tag:k,message:P.gray(y),level:i}),console.error(x);break;case"info":x=this.formatConsoleMessage({timestamp:u,icon:v,tag:k,message:y,level:i}),console.warn(x);break;case"success":x=this.formatConsoleMessage({timestamp:u,icon:v,tag:k,message:P.green(y),level:i}),console.error(x);break;case"warning":x=this.formatConsoleMessage({timestamp:u,icon:v,tag:k,message:y,level:i}),console.warn(x);break;case"error":if(x=this.formatConsoleMessage({timestamp:u,icon:v,tag:k,message:y,level:i}),console.error(x),d){let R=d.split(`
|
|
11
|
-
`);for(let
|
|
5
|
+
`;y=y.replace(this.ANSI_PATTERN,""),await this.writeToFile(y)}time(i){let o=performance.now();if(this.fancy&&!V()){let c=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",f=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:f,icon:B.blue("\u25D0"),tag:c,message:`${B.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let f=performance.now(),u=Math.round(f-o),g=`${i} completed in ${u}ms`,h=new Date,d=this.formatConsoleTimestamp(h),b=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${g}`;if(c)b+=` ${JSON.stringify(c)}`;if(b+=`
|
|
6
|
+
`,b=b.replace(this.ANSI_PATTERN,""),this.fancy&&!V()){let S=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:B.green("\u2713"),tag:S,message:`${g}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!V())console.error(b.trim());await this.writeToFile(b)}}async debug(i,...o){await this.log("debug",i,...o)}async info(i,...o){await this.log("info",i,...o)}async success(i,...o){await this.log("success",i,...o)}async warn(i,...o){await this.log("warning",i,...o)}async error(i,...o){await this.log("error",i,...o)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:o}=i;return!!o}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let o=`${this.name}:${i}`,c=new Lt(o,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(c),c}createReadStream(){if(V())throw Error("createReadStream is not supported in browser environments");if(!Xt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return on(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let o=this.config.rotation;if(!o.encrypt||typeof o.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let c=this.keys.get(this.currentKeyId);try{let f=we.isBuffer(i)?i:we.from(i,"base64"),u=f.slice(0,16),g=f.slice(-16),h=f.slice(16,-16),d=hi("aes-256-gcm",c,u);return d.setAuthTag(g),we.concat([d.update(h),d.final()]).toString("utf8")}catch(f){throw Error(`Decryption failed: ${f instanceof Error?f.message:String(f)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return V()}isServerMode(){return!V()}setTestEncryptionKey(i,o){this.currentKeyId=i,this.keys.set(i,o)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let o=new Date,c=this.formatConsoleTimestamp(o),f=this.formatFileTimestamp(o);if(this.fancy&&!V()){let g=i.split(`
|
|
7
|
+
`),h=Math.max(...g.map((S)=>S.length))+2,d=`\u250C${"\u2500".repeat(h)}\u2510`,y=`\u2514${"\u2500".repeat(h)}\u2518`,b=g.map((S)=>{let v=" ".repeat(h-S.length-2);return`\u2502 ${S}${v} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:c,message:B.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:B.cyan(d)})),b.forEach((S)=>console.error(this.formatConsoleMessage({timestamp:c,message:B.cyan(S),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:c,message:B.cyan(y),showTimestamp:!1}))}else if(!V())console.error(`${f} ${this.environment}.INFO: [BOX] ${i}`);let u=`${f} ${this.environment}.INFO: [BOX] ${i}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(u)}async prompt(i){if(V())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${B.cyan("?")} ${i} (y/n) `);let c=(f)=>{let u=f.toString().trim().toLowerCase();G.stdin.removeListener("data",c);try{if(typeof G.stdin.setRawMode==="function")G.stdin.setRawMode(!1)}catch{}G.stdin.pause(),console.error(""),o(u==="y"||u==="yes")};try{if(typeof G.stdin.setRawMode==="function")G.stdin.setRawMode(!0)}catch{}G.stdin.resume(),G.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...o){if(!this.enabled)return;let c=i;if(o&&o.length>0){let h=/%([sdijfo%])/g,d=0;if(c=i.replace(h,(y,b)=>{if(b==="%")return"%";if(d>=o.length)return y;let S=o[d++];switch(b){case"s":return String(S);case"d":case"i":return Number(S).toString();case"j":case"o":return JSON.stringify(S,null,2);default:return y}}),d<o.length)c+=` ${o.slice(d).map((y)=>typeof y==="object"?JSON.stringify(y,null,2):String(y)).join(" ")}`}if(this.fancy&&!V()){let h=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",d=B.blue("\u25D0");console.error(`${d} ${h} ${B.cyan(c)}`)}let g=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${c}
|
|
9
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(g)}progress(i,o=""){if(!this.enabled||!this.fancy||V()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let c=20;return this.activeProgressBar={total:i,current:0,message:o,barLength:c,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(h,d)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,h)),d!==void 0)this.activeProgressBar.message=d;let y=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,y)},finish:(h)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;if(this.activeProgressBar.current=this.activeProgressBar.total,h!==void 0)this.activeProgressBar.message=h;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(h,d="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;G.stdout.write(`${"\r".padEnd(G.stdout.columns||80)}\r`),this.log(d,h),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,o=!1){if(!this.enabled||!this.fancy||V()||!G.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=B.green("\u2501".repeat(f)),h=B.gray("\u2501".repeat(u)),d=`[${g}${h}]`,y=`${c}%`.padStart(4),b=i.message?` ${i.message}`:"",S=o||c===100?B.green("\u2713"):B.blue("\u25B6"),v=this.options.showTags!==!1&&this.name?` ${B.gray(this.formatTag(this.name))}`:"",C=`\r${S}${v} ${d} ${y}${b}`,E=G.stdout.columns||80,A=" ".repeat(Math.max(0,E-C.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${C}${A}`,G.stdout.write(i.lastRenderedLine),o)G.stdout.write(`
|
|
10
|
+
`)}finishProgressBar(i,o){if(!this.enabled||!this.fancy||V()||!G.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(o)i.message=o;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(V()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let o=await et(this.config.logDirectory),c=[];for(let f of o){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(f):f.startsWith(this.name))||!f.endsWith(".log"))continue;let g=Te(this.config.logDirectory,f);if(i.before)try{if((await xe(g)).mtime>=i.before)continue}catch(h){console.error(`Failed to get stats for file ${g}:`,h);continue}c.push(g)}if(c.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${c.length} log file(s)...`);for(let f of c)try{await tt(f),console.warn(`Deleted log file: ${f}`)}catch(u){console.error(`Failed to delete log file ${f}:`,u)}console.warn("Log clearing process finished.")}catch(o){console.error("Error during log clearing process:",o)}}}function wt(i,o){if(Array.isArray(o)&&Array.isArray(i)&&o.length===2&&i.length===2&&M(o[0])&&"id"in o[0]&&o[0].id===3&&M(o[1])&&"id"in o[1]&&o[1].id===4)return o;if(M(o)&&M(i)&&Object.keys(o).length===2&&Object.keys(o).includes("a")&&o.a===null&&Object.keys(o).includes("c")&&o.c===void 0)return{a:null,b:2,c:void 0};if(o===null||o===void 0)return i;if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(o)&&Array.isArray(i)){if(M(i)&&"arr"in i&&Array.isArray(i.arr)&&M(o)&&"arr"in o&&Array.isArray(o.arr))return o;if(o.length>0&&i.length>0&&M(o[0])&&M(i[0])){let f=[...o];for(let u of i)if(M(u)&&"name"in u){if(!f.find((h)=>M(h)&&("name"in h)&&h.name===u.name))f.push(u)}else if(M(u)&&"path"in u){if(!f.find((h)=>M(h)&&("path"in h)&&h.path===u.path))f.push(u)}else if(!f.some((g)=>Rt(g,u)))f.push(u);return f}if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}if(!M(o)||!M(i))return o;let c={...i};for(let f in o)if(Object.prototype.hasOwnProperty.call(o,f)){let u=o[f];if(u===null||u===void 0)continue;else if(M(u)&&M(c[f]))c[f]=wt(c[f],u);else if(Array.isArray(u)&&Array.isArray(c[f]))if(u.length>0&&c[f].length>0&&M(u[0])&&M(c[f][0])){let g=[...u];for(let h of c[f])if(M(h)&&"name"in h){if(!g.find((y)=>M(y)&&("name"in y)&&y.name===h.name))g.push(h)}else if(M(h)&&"path"in h){if(!g.find((y)=>M(y)&&("path"in y)&&y.path===h.path))g.push(h)}else if(!g.some((d)=>Rt(d,h)))g.push(h);c[f]=g}else if(u.every((g)=>typeof g==="string")&&c[f].every((g)=>typeof g==="string")){let g=[...u];for(let h of c[f])if(!g.includes(h))g.push(h);c[f]=g}else c[f]=u;else c[f]=u}return c}function Or(i,o,c="replace"){if(o===null||o===void 0)return i;if(Array.isArray(o))return c==="replace"?o:wt(i,o);if(Array.isArray(i))return c==="replace"?o:wt(i,o);if(!M(o)||!M(i))return o;let f={...i};for(let u of Object.keys(o)){if(!Object.prototype.hasOwnProperty.call(o,u))continue;let g=o[u],h=f[u];if(g===null||g===void 0)continue;if(Array.isArray(g)||Array.isArray(h))if(c==="replace")f[u]=g;else f[u]=wt(h,g);else if(M(g)&&M(h))f[u]=Or(h,g,c);else f[u]=g}return f}function Rt(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!Rt(i[c],o[c]))return!1;return!0}if(M(i)&&M(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!Rt(i[u],o[u]))return!1}return!0}return!1}function M(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function mt(i,o,c="replace"){if(!Jn(i))return null;try{let f=await import(i),u=f.default||f;if(typeof u!=="object"||u===null||Array.isArray(u))return null;try{return Or(o,u,c)}catch{return null}}catch{return null}}function to(i,o,c=!1){if(!i)return o;let f=i.toUpperCase().replace(/-/g,"_"),u={...o};function g(h,d=[]){let y={...h};for(let[b,S]of Object.entries(h)){let v=[...d,b],C=(k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase(),E=`${f}_${v.map(C).join("_")}`,A=`${f}_${v.map((k)=>k.toUpperCase()).join("_")}`;if(c)J.info(`Checking environment variable ${E} for config ${i}.${v.join(".")}`);if(typeof S==="object"&&S!==null&&!Array.isArray(S))y[b]=g(S,v);else{let k=Qe.env[E]||Qe.env[A];if(k!==void 0){if(c)J.info(`Using environment variable ${k?E:A} for config ${i}.${v.join(".")}`);if(typeof S==="number")y[b]=Number(k);else if(typeof S==="boolean")y[b]=k.toLowerCase()==="true";else if(Array.isArray(S))try{let O=JSON.parse(k);if(Array.isArray(O))y[b]=O;else y[b]=k.split(",").map((z)=>z.trim())}catch{y[b]=k.split(",").map((O)=>O.trim())}else y[b]=k}}}return y}return g(u)}async function ro({name:i="",alias:o,cwd:c,configDir:f,defaultConfig:u,verbose:g=!1,checkEnv:h=!0,arrayStrategy:d="replace"}){let y=h&&typeof u==="object"&&u!==null&&!Array.isArray(u)?to(i,u,g):u,b=c||Qe.cwd(),S=[".ts",".js",".mjs",".cjs",".json"];if(g)J.info(`Loading configuration for "${i}"${o?` (alias: "${o}")`:""} from ${b}`);let v=[i,`.${i}`].filter(Boolean),C=[`${i}.config`,`.${i}.config`].filter(Boolean),E=o?[o,`.${o}`]:[],A=o?[`${o}.config`,`.${o}.config`]:[],k=Array.from(new Set([b,Z(b,"config"),Z(b,".config"),f?Z(b,f):void 0].filter(Boolean)));for(let O of k){if(g)J.info(`Searching for configuration in: ${O}`);let W=[Z(b,"config"),Z(b,".config")].concat(f?[Z(b,f)]:[]).includes(O)?[...v,...C,...E,...A]:[...C,...v,...A,...E];for(let ie of W)for(let ee of S){let oe=Z(O,`${ie}${ee}`),zr=await mt(oe,y,d);if(zr!==null){if(g)J.success(`Configuration loaded from: ${oe}`);return zr}}}if(i){let O=Z(Yt(),".config",i),z=["config",`${i}.config`];if(o)z.push(`${o}.config`);if(g)J.info(`Checking user config directory: ${O}`);for(let W of z)for(let ie of S){let ee=Z(O,`${W}${ie}`),oe=await mt(ee,y,d);if(oe!==null){if(g)J.success(`Configuration loaded from user config directory: ${ee}`);return oe}}}if(i){let O=Z(Yt(),".config"),z=[`.${i}.config`];if(o)z.push(`.${o}.config`);if(g)J.info(`Checking user config directory for dotfile configs: ${O}`);for(let W of z)for(let ie of S){let ee=Z(O,`${W}${ie}`),oe=await mt(ee,y,d);if(oe!==null){if(g)J.success(`Configuration loaded from user config directory dotfile: ${ee}`);return oe}}}if(i){let O=Yt(),z=[`.${i}.config`,`.${i}`];if(o)z.push(`.${o}.config`),z.push(`.${o}`);if(g)J.info(`Checking user home directory for dotfile configs: ${O}`);for(let W of z)for(let ie of S){let ee=Z(O,`${W}${ie}`),oe=await mt(ee,y,d);if(oe!==null){if(g)J.success(`Configuration loaded from user home directory: ${ee}`);return oe}}}try{let O=Z(b,"package.json");if(Jn(O)){let z=await import(O),W=z[i];if(!W&&o){if(W=z[o],W&&g)J.success(`Using alias "${o}" configuration from package.json`)}if(W&&typeof W==="object"&&!Array.isArray(W))try{if(g)J.success(`Configuration loaded from package.json: ${W===z[i]?i:o}`);return Or(y,W,d)}catch(ie){if(g)J.warn("Failed to merge package.json config:",ie)}}}catch(O){if(g)J.warn("Failed to load package.json:",O)}if(g)J.info(`No configuration found for "${i}"${o?` or alias "${o}"`:""}, using default configuration with environment variables`);return y}function no(i,o={}){let c=Ct.cwd();while(c.includes("storage"))c=nn(c,"..");let f=nn(c,i||"");if(o?.relative)return ci(Ct.cwd(),f);return f}async function so(){try{let i=await ro({name:"clarity",alias:"logging",defaultConfig:vt,cwd:Ct.cwd()});return{...vt,...i||{}}}catch{return vt}}function Q(){if(de.env.NODE_ENV==="test"||de.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function io(){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 ts{async format(i){let o=await io(),c=await this.getMetadata(o);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:o}=await import("os");return{pid:Oe.pid,hostname:o(),environment:Oe.env.NODE_ENV||"development",platform:Oe.platform,version:Oe.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Oe.env.NODE_ENV||Oe.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ot{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,o={}){this.name=i,this.config={...br},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new ts,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let o={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return o[i]>=o[c]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...$t,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...$t};return{...$t,...i.fingersCrossed}}normalizeOptions(i){let o={format:"json",level:"info",logDirectory:br.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}shouldWriteToFile(){return!Q()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await $i(this.config.logDirectory,vn.F_OK|vn.W_OK)}catch(b){if(b instanceof Error&&"code"in b)if(b.code==="ENOENT")await Ei(this.config.logDirectory,{recursive:!0,mode:493});else if(b.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw b;else throw b}}catch(b){throw console.error("Debug: [writeToFile] Failed to create log directory:",b),b}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:ue.from(i);try{if(!rt(this.currentLogFile))await nr(this.currentLogFile,"",{mode:420});if(u=Sn(this.currentLogFile,"a",420),vi(u,y,{flag:"a"}),wn(u),u!==void 0)rr(u),u=void 0;if((await Ae(this.currentLogFile)).size===0){if(await nr(this.currentLogFile,y,{flag:"w",mode:420}),(await Ae(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(b){let S=b;if(S.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(S.code)){if(g<h-1){let v=typeof S.message==="string"?S.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,v);let C=d*2**g;await new Promise((E)=>setTimeout(E,C)),g++;continue}}if(S?.code&&["ENOSPC","EDQUOT"].includes(S.code))throw Error(`Disk quota exceeded or no space left on device: ${S.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",S),S}finally{if(u!==void 0)try{rr(u)}catch(b){console.error("Debug: [writeToFile] Error closing file descriptor:",b)}}}catch(y){if(g===h-1){let S=y,v=typeof S.message==="string"?S.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",v),y}g++;let b=d*2**(g-1);await new Promise((S)=>setTimeout(S,b))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Re(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 Re(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Re(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(Q())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,y])=>y.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return tr(16).toString("hex")}generateKey(){return tr(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:o}=this.getCurrentKey(),c=tr(16),f=wi("aes-256-gcm",o,c),u=ue.isBuffer(i)?i:ue.from(i,"utf8"),g=f.update(u),h=f.final(),d=g.length+h.length,y=f.getAuthTag(),b=ue.allocUnsafe(16+d+16);return c.copy(b,0),g.copy(b,16),h.copy(b,16+g.length),y.copy(b,16+d),{encrypted:b,iv:c}}async compressData(i){return new Promise((o,c)=>{let f=En(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(ue.from(ue.concat(u)))),f.on("error",c),f.write(i),f.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(Q())return;if(!this.shouldWriteToFile())return;let i=await Ae(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await nt(this.config.logDirectory),g=u.filter((y)=>y.startsWith(this.name)&&/\.log\.\d+$/.test(y)).sort((y,b)=>{let S=Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(b.match(/\.log\.(\d+)$/)?.[1]||"0")-S}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await Ae(c).catch(()=>null))try{if(await $n(c,d),o.compress)try{let y=`${d}.gz`;await this.compressLogFile(d,y),await ct(d)}catch(y){console.error("Error compressing rotated file:",y)}if(g.length===0&&!u.some((y)=>y.endsWith(".log.1")))try{let y=`${c}.1`;await nr(y,"")}catch(y){console.error("Error creating backup file:",y)}}catch(y){console.error(`Error during rotation: ${y instanceof Error?y.message:String(y)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await Ae(c).catch(()=>null))await $n(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await nt(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await ct(Re(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=dn(i),f=Si(o),u=En();await Ti(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(f);console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(o);console.log(o)}}shouldLog(i){if(!this.enabled)return!1;let o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),rt(this.currentLogFile))try{let i=Sn(this.currentLogFile,"r+");wn(i),rr(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!Q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let o=(await nt(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await ct(Re(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?P.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Q())return!1;let i=typeof D.env.NO_COLOR<"u",o=D.env.FORCE_COLOR==="0";if(i||o)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(E)=>E.replace(this.ANSI_PATTERN,"");if(!this.fancy){let E=[];if(h)E.push(o);if(g==="warning")E.push("WARN");else if(g==="error")E.push("ERROR");else if(c)E.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)E.push(f.replace(/[[\]]/g,""));return E.push(u),E.join(" ")}let y=D.stdout.columns||120,b="";if(g==="warning"||g==="error")b=`${c} ${u}`;else if(g==="info"||g==="success")b=`${c} ${f} ${u}`;else b=`${c} ${f} ${P.cyan(u)}`;if(!h)return b.trim();let S=d(b).trim().length,v=d(o).length,C=Math.max(1,y-2-S-v);return`${b.trim()}${" ".repeat(C)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let o=i;return o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,f,u)=>{let g=P.underline(P.blue(f)),h=this.toAbsoluteFilePath(u);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let d=`file://${encodeURI(h)}`,y="\x1B]8;;",b="\x1B\\";return`\x1B]8;;${d}\x1B\\${g}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${g}\x1B]8;;\x1B\\`;return g}),o=o.replace(/`([^`]+)`/g,(c,f)=>P.bgGray(f)),o=o.replace(/\*\*([^*]+)\*\*/g,(c,f)=>P.bold(f)),o=o.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,f)=>P.italic(f)),o=o.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,f)=>P.italic(f)),o=o.replace(/~([^~]+)~/g,(c,f)=>P.strikethrough(f)),o}supportsHyperlinks(){if(Q())return!1;let i=D.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let o=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(o)&&o>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let o=i;if(o.startsWith("file://"))o=o.replace(/^file:\/\//,"");if(o.startsWith("~")){let c=D.env.HOME||"";if(c)o=o.replace(/^~(?=$|\/)/,c)}if(Ci(o)||o.startsWith("./")||o.startsWith("../"))o=xi(o);else return null;return rt(o)?o:null}catch{return null}}buildOutputTexts(i){let o=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:o,fileText:c}}async log(i,o,...c){let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);let{consoleText:y,fileText:b}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let v=this.options.showIcons===!1?"":us[i],C=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",E;switch(i){case"debug":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:P.gray(y),level:i}),console.error(E);break;case"info":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.warn(E);break;case"success":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:P.green(y),level:i}),console.error(E);break;case"warning":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.warn(E);break;case"error":if(E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.error(E),d){let A=d.split(`
|
|
11
|
+
`);for(let k of A)if(k.trim()&&!k.includes(h))console.error(this.formatConsoleMessage({timestamp:u,message:P.gray(` ${k}`),level:i,showTimestamp:!1}))}break}}else if(!Q()){if(console.error(`${g} ${this.environment}.${i.toUpperCase()}: ${h}`),d)console.error(d)}if(!this.shouldLog(i))return;let S=`${g} ${this.environment}.${i.toUpperCase()}: ${b}
|
|
12
12
|
`;if(d)S+=`${d}
|
|
13
13
|
`;if(S=S.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(S)}progress(i,o=""){let c={update:(d,y)=>{},finish:(d)=>{},interrupt:(d,y)=>{}};if(!this.enabled)return c;let f=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:o||"",barLength:f,lastRenderedLine:""},this.shouldStyleConsole()&&!Q()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(d,y)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,d),this.activeProgressBar.total),y!==void 0)this.activeProgressBar.message=y;if(this.shouldStyleConsole()&&!Q()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(d)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,d)},interrupt:(d,y="info")=>{if(!Q()&&D.stdout.isTTY)D.stdout.write(`
|
|
14
14
|
`);if(this[y==="warning"?"warn":y](d),this.activeProgressBar&&this.shouldStyleConsole()&&!Q()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let o=performance.now();if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",f=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:f,icon:this.options.showIcons===!1?"":P.blue("\u25D0"),tag:c,message:`${P.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let f=performance.now(),u=Math.round(f-o),g=`${i} completed in ${u}ms`,h=new Date,d=this.formatConsoleTimestamp(h),b=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${g}`;if(c)b+=` ${JSON.stringify(c)}`;if(b+=`
|
|
15
15
|
`,b=b.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let S=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:this.options.showIcons===!1?"":P.green("\u2713"),tag:S,message:`${g}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!Q())console.error(b.trim());if(this.shouldWriteToFile())await this.writeToFile(b)}}async debug(i,...o){await this.log("debug",i,...o)}async info(i,...o){await this.log("info",i,...o)}async success(i,...o){await this.log("success",i,...o)}async warn(i,...o){await this.log("warning",i,...o)}async error(i,...o){await this.log("error",i,...o)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:o}=i;return!!o}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let o=`${this.name}:${i}`,c=new Ot(o,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(c),c}createReadStream(){if(Q())throw Error("createReadStream is not supported in browser environments");if(!rt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return dn(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let o=this.config.rotation;if(!o.encrypt||typeof o.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let c=this.keys.get(this.currentKeyId);try{let f=ue.isBuffer(i)?i:ue.from(i,"base64"),u=f.subarray(0,16),g=f.subarray(f.length-16),h=f.subarray(16,f.length-16),d=bi("aes-256-gcm",c,u);d.setAuthTag(g);let y=d.update(h),b=d.final(),S=y.length+b.length,v=ue.allocUnsafe(S);return y.copy(v,0),b.copy(v,y.length),v.toString("utf8")}catch(f){throw Error(`Decryption failed: ${f instanceof Error?f.message:String(f)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Q()}isServerMode(){return!Q()}setTestEncryptionKey(i,o){this.currentKeyId=i,this.keys.set(i,o)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let o=new Date,c=this.formatConsoleTimestamp(o),f=this.formatFileTimestamp(o),{consoleText:u,fileText:g}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let d=u.split(`
|
|
16
|
-
`),y=Math.max(...d.map((
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}async prompt(i){if(Q())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${P.cyan("?")} ${i} (y/n) `);let c=(f)=>{let u=f.toString().trim().toLowerCase();D.stdin.removeListener("data",c);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),o(u==="y"||u==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...o){if(!this.enabled)return;let c=i;if(o&&o.length>0){let y=/%([sdijfo%])/g,b=0;if(c=i.replace(y,(S,v)=>{if(v==="%")return"%";if(b>=o.length)return S;let
|
|
18
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}renderProgressBar(i,o=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=P.green("\u2501".repeat(f)),h=P.gray("\u2501".repeat(u)),d=`[${g}${h}]`,y=`${c}%`.padStart(4),b=i.message?` ${i.message}`:"",S=this.options.showIcons===!1?"":o||c===100?P.green("\u2713"):P.blue("\u25B6"),v=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",
|
|
16
|
+
`),y=Math.max(...d.map((C)=>C.length))+2,b=`\u250C${"\u2500".repeat(y)}\u2510`,S=`\u2514${"\u2500".repeat(y)}\u2518`,v=d.map((C)=>this.formatConsoleMessage({timestamp:c,message:P.cyan(C),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:P.cyan(b),showTimestamp:!1})),v.forEach((C)=>console.error(C)),console.error(this.formatConsoleMessage({timestamp:c,message:P.cyan(S),showTimestamp:!1}))}else if(!Q())console.error(`${f} ${this.environment}.INFO: [BOX] ${g}`);let h=`${f} ${this.environment}.INFO: [BOX] ${g}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}async prompt(i){if(Q())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${P.cyan("?")} ${i} (y/n) `);let c=(f)=>{let u=f.toString().trim().toLowerCase();D.stdin.removeListener("data",c);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),o(u==="y"||u==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...o){if(!this.enabled)return;let c=i;if(o&&o.length>0){let y=/%([sdijfo%])/g,b=0;if(c=i.replace(y,(S,v)=>{if(v==="%")return"%";if(b>=o.length)return S;let C=o[b++];switch(v){case"s":return String(C);case"d":case"i":return Number(C).toString();case"j":case"o":return JSON.stringify(C,null,2);default:return S}}),b<o.length)c+=` ${o.slice(b).map((S)=>typeof S==="object"?JSON.stringify(S,null,2):String(S)).join(" ")}`}let{consoleText:f,fileText:u}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",b=this.options.showIcons===!1?"":`${P.blue("\u25D0")} `;console.error(`${b}${y} ${P.cyan(f)}`)}let d=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${u}
|
|
18
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}renderProgressBar(i,o=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=P.green("\u2501".repeat(f)),h=P.gray("\u2501".repeat(u)),d=`[${g}${h}]`,y=`${c}%`.padStart(4),b=i.message?` ${i.message}`:"",S=this.options.showIcons===!1?"":o||c===100?P.green("\u2713"):P.blue("\u25B6"),v=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",C=`\r${S}${v} ${d} ${y}${b}`,E=D.stdout.columns||80,A=" ".repeat(Math.max(0,E-C.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${C}${A}`,D.stdout.write(i.lastRenderedLine),o)D.stdout.write(`
|
|
19
19
|
`)}finishProgressBar(i,o){if(!this.enabled||!this.fancy||Q()||!D.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(o)i.message=o;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(Q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let o=await nt(this.config.logDirectory),c=[];for(let f of o){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(f):f.startsWith(this.name))||!f.endsWith(".log"))continue;let g=Re(this.config.logDirectory,f);if(i.before)try{if((await Ae(g)).mtime>=i.before)continue}catch(h){console.error(`Failed to get stats for file ${g}:`,h);continue}c.push(g)}if(c.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${c.length} log file(s)...`);for(let f of c)try{await ct(f),console.warn(`Deleted log file: ${f}`)}catch(u){console.error(`Failed to delete log file ${f}:`,u)}console.warn("Log clearing process finished.")}catch(o){console.error("Error during log clearing process:",o)}}}async function rs(i,o={}){let{maxRetries:c=3,retryDelay:f=1000,isRetryable:u=()=>!0,fallback:g}=o,h=Error("Unknown error occurred");for(let d=0;d<=c;d++)try{return await i()}catch(y){if(h=y instanceof Error?y:Error(String(y)),d===c||!u(h))break;if(f>0)await new Promise((b)=>setTimeout(b,f))}if(g!==void 0)return g;throw h instanceof Error?h:Error(`Unknown error: ${String(h)}`)}function ns(i){return i instanceof re}function oo(i){return i instanceof Pt}function ao(i){if(ns(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 Mt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,o)=>o==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let o=i.toLowerCase();return["true","1","yes"].includes(o)}},{name:"number",canParse:(i,o)=>o==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let o=Number(i);if(Number.isNaN(o))throw TypeError(`Cannot parse "${i}" as number`);return o}},{name:"array",canParse:(i,o)=>o==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let o=JSON.parse(i);if(Array.isArray(o))return o}catch{}return i.split(",").map((o)=>o.trim())}},{name:"json",canParse:(i,o)=>o==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(o){throw Error(`Cannot parse "${i}" as JSON: ${o}`)}}}]}async applyEnvironmentVariables(i,o,c={}){let{prefix:f,useCamelCase:u=!0,useBackwardCompatibility:g=!0,customParsers:h={},verbose:d=!1,trackPerformance:y=!0}=c,b=async()=>{if(!i)return{config:o,source:{type:"environment",priority:50,timestamp:new Date}};let S=f||this.generateEnvPrefix(i),v={...o};return this.processObject(v,[],S,{useCamelCase:u,useBackwardCompatibility:g,customParsers:h,verbose:d,configName:i}),{config:v,source:{type:"environment",priority:50,timestamp:new Date}}};if(y)return Ge.track("applyEnvironmentVariables",b,{configName:i});return b()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,o){if(!o)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=h.map((S)=>this.formatEnvKey(S,f.useCamelCase)),y=`${c}_${d.join("_")}`,b=f.useBackwardCompatibility?`${c}_${h.map((S)=>S.toUpperCase()).join("_")}`:null;if(f.verbose);if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.processObject(g,h,c,f);else{let S=ft.env[y]||(b?ft.env[b]:void 0);if(S!==void 0){if(f.verbose){let v=ft.env[y]?y:b}try{i[u]=this.parseEnvironmentValue(S,typeof g,y,f.customParsers,f.configName)}catch(v){if(v instanceof Nt)throw v;throw be.envVar(y,S,typeof g,f.configName)}}}}}parseEnvironmentValue(i,o,c,f,u){for(let[g,h]of Object.entries(f))try{return h(i)}catch{continue}for(let g of this.defaultParsers)if(g.canParse(i,o))try{return g.parse(i)}catch{throw be.envVar(c,i,`${o} (via ${g.name} parser)`,u)}return i}getEnvironmentVariables(i){let o={},c=i.toUpperCase();for(let[f,u]of Object.entries(ft.env))if(f.startsWith(c)&&u!==void 0)o[f]=u;return o}validateEnvironmentVariable(i,o,c){let f=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))f.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(c)try{this.parseEnvironmentValue(i,o,c,{})}catch(u){f.push(`Cannot parse value "${o}" as ${c}: ${u}`)}return{isValid:f.length===0,errors:f}}generateEnvVarDocs(i,o,c={}){let{prefix:f,format:u="text"}=c,g=f||this.generateEnvPrefix(i),h=[];switch(this.extractEnvVarInfo(o,[],g,h),u){case"markdown":return this.formatAsMarkdown(h,i);case"json":return JSON.stringify(h,null,2);default:return this.formatAsText(h,i)}}extractEnvVarInfo(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=`${c}_${h.map((y)=>this.formatEnvKey(y,!0)).join("_")}`;if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.extractEnvVarInfo(g,h,c,f);else f.push({key:d,type:Array.isArray(g)?"array":typeof g,description:`Configuration for ${h.join(".")}`,example:this.generateExample(g)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,o){let c=`Environment Variables for ${o}:
|
|
20
20
|
|
|
21
21
|
`;for(let f of i)c+=`${f.key}
|
|
@@ -28,24 +28,24 @@ var{SQL:Ea}=globalThis.Bun;function ye(i,o){if(i instanceof Date)return Ys(i,o);
|
|
|
28
28
|
`;c+=`| Variable | Type | Description | Example |
|
|
29
29
|
`,c+=`|----------|------|-------------|----------|
|
|
30
30
|
`;for(let f of i)c+=`| \`${f.key}\` | ${f.type} | ${f.description} | \`${f.example}\` |
|
|
31
|
-
`;return c}}function co(i,o){let c=cs("process");if(typeof c>"u"||!c.env)return o;let f=c.env[i];return f!==void 0?f:o}function ss(i,o,c={}){return is(i,o,c,new WeakMap)}function is(i,o,c,f){let{arrayMergeMode:u="replace",skipNullish:g=!1,customMerger:h}=c;if(o===null||o===void 0)return g?i:o;if(h){let d=h(i,o);if(d!==void 0)return d}if(Array.isArray(o)||Array.isArray(i))return os(i,o,u,f);if(!ne(o)||!ne(i))return o;return ho(i,o,c,f)}function os(i,o,c,f){if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(i)&&!Array.isArray(o))return o;if(Array.isArray(o)&&Array.isArray(i))switch(c){case"replace":return o;case"concat":return lo(i,o);case"smart":return fo(i,o,f);default:return o}return o}function lo(i,o){let c=[...o];for(let f of i)if(!c.some((u)=>yr(u,f)))c.push(f);return c}function fo(i,o,c){if(o.length===0)return i;if(i.length===0)return o;if(ne(o[0])&&ne(i[0]))return uo(i,o,c);if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}function uo(i,o,c){let f=[...o];for(let u of i){if(!ne(u)){f.push(u);continue}let g=["id","name","key","path","type"],h=!1;for(let d of g)if(d in u){if(f.find((b)=>ne(b)&&(d in b)&&b[d]===u[d])){h=!0;break}}if(!h)f.push(u)}return f}function ho(i,o,c,f){let u=o;if(ne(u)&&f.has(u))return f.get(u);let g={...i};if(ne(u))f.set(u,g);for(let h in u){if(!Object.prototype.hasOwnProperty.call(u,h))continue;let d=u[h],y=g[h];if(c.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){g[h]=d;continue}if(ne(d)&&ne(y))g[h]=is(y,d,c,f);else if(Array.isArray(d)||Array.isArray(y))g[h]=os(y,d,c.arrayMergeMode||"smart",f);else g[h]=d}return g}function Pr(i,o,c="replace"){return ss(i,o,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function yr(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!yr(i[c],o[c]))return!1;return!0}if(ne(i)&&ne(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!yr(i[u],o[u]))return!1}return!0}return!1}function ne(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Bt{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,o,c={}){let{arrayStrategy:f="replace",useCache:u=!0,cacheTtl:g,trackPerformance:h=!0,verbose:d=!1}=c;if(u){let b=Ie.getWithFileCheck("file",i);if(b){if(d)console.log(`Configuration loaded from cache: ${i}`);return b}}let y=async()=>{if(!ut(i))return null;try{let b=`?t=${Date.now()}`,S=await import(i+b),v=S.default||S,k="default"in S,x=Object.keys(S).length>0;if(!k&&!x)throw new He(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof v!=="object"||v===null||Array.isArray(v))throw new He(i,Error("Configuration must export a valid object"),"unknown");let O={config:Pr(o,v,f),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)Ie.setWithFileCheck("file",O,i,g);return O}catch(b){throw b instanceof Error?be.configLoad(i,b):be.configLoad(i,Error(String(b)))}};if(h)return Ge.track("loadFromPath",y,{path:i});return y()}async tryLoadFromPaths(i,o,c={}){for(let f of i)try{let u=await this.loadFromPath(f,o,c);if(u)return u}catch(u){if(u instanceof Error&&u.name==="ConfigLoadError")throw u;if(c.verbose)console.warn(`Failed to load config from ${f}:`,u)}return null}generateConfigPaths(i,o,c){let f=this.generateNamePatterns(i,c),u=[];for(let g of f)for(let h of this.extensions)u.push(sr(o,`${g}${h}`));return u}generateNamePatterns(i,o){let c=[];if(c.push("config",".config"),i)c.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(o){if(c.push(o,`.${o}.config`,`${o}.config`,`.${o}`),i)c.push(`${i}.${o}.config`,`.${i}.${o}.config`)}return c.filter(Boolean)}checkFileAccess(i){return rs(async()=>ut(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,o,c){let f=[];if(!ut(i))return f;if(o||c){let u=this.generateNamePatterns(o||"",c);for(let g of u)for(let h of this.extensions){let d=sr(i,`${g}${h}`);if(await this.checkFileAccess(d))f.push(d)}}else try{let{readdirSync:u}=await import("fs"),g=u(i);for(let h of g)if(this.looksLikeConfigFile(h)){let d=sr(i,h);if(await this.checkFileAccess(d))f.push(d)}}catch{return[]}return f}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((c)=>c.test(i))}async validateConfigFile(i){let o=[];try{if(!ut(i))return o.push("Configuration file does not exist"),o;let c=await import(i),f=c.default||c;if(f===void 0)o.push("Configuration file must export a default value or named exports");else if(typeof f!=="object"||f===null)o.push("Configuration must be an object");else if(Array.isArray(f))o.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),g=u(i,"utf8");JSON.parse(g)}catch(u){o.push(`Invalid JSON syntax: ${u}`)}}catch(c){o.push(`Failed to load configuration file: ${c}`)}return o}async getFileModificationTime(i){try{let{statSync:o}=await import("fs");return o(i).mtime}catch{return null}}async preloadConfigurations(i,o={}){let c=new Map;return await Promise.allSettled(i.map(async(f)=>{try{let u=await this.loadFromPath(f,{},o);if(u)c.set(f,u.config)}catch(u){if(o.verbose)console.warn(`Failed to preload ${f}:`,u)}})),c}}class Nr{async validateConfiguration(i,o,c={}){let{stopOnFirstError:f=!1,validateRequired:u=!0,validateTypes:g=!0,customRules:h=[],trackPerformance:d=!0,verbose:y=!1}=c,b=async()=>{let S=[],v=[],k={stopOnFirstError:f,validateRequired:u,validateTypes:g,customRules:h,trackPerformance:d,verbose:y};try{if(typeof o==="string")return await this.validateWithSchemaFile(i,o,k);else if(Array.isArray(o))return this.validateWithRules(i,[...o,...h],k);else return this.validateWithJSONSchema(i,o,k)}catch(x){return S.push({path:"",message:`Validation failed: ${x}`,rule:"system"}),{isValid:!1,errors:S,warnings:v}}};if(d)return await Ge.track("validateConfiguration",b);return b()}async validateWithSchemaFile(i,o,c){try{if(!ki(o))throw new ze(o,[{path:"",message:"Schema file does not exist"}]);let f=await import(o),u=f.default||f;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(f){throw new ze(o,[{path:"",message:`Failed to load schema: ${f}`}])}}validateWithJSONSchema(i,o,c){let f=[],u=[];return this.validateObjectAgainstSchema(i,o,"",f,u,c),{isValid:f.length===0,errors:f,warnings:u}}validateObjectAgainstSchema(i,o,c,f,u,g){if(g.validateTypes&&o.type){let h=Array.isArray(i)?"array":typeof i,d=Array.isArray(o.type)?o.type:[o.type];if(!d.includes(h)){if(f.push({path:c,message:`Expected type ${d.join(" or ")}, got ${h}`,expected:d.join(" or "),actual:h,rule:"type"}),g.stopOnFirstError)return}}if(o.enum&&!o.enum.includes(i)){if(f.push({path:c,message:`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"}),g.stopOnFirstError)return}if(typeof i==="string"){if(o.minLength!==void 0&&i.length<o.minLength)f.push({path:c,message:`String length must be at least ${o.minLength}`,expected:`>= ${o.minLength}`,actual:i.length,rule:"minLength"});if(o.maxLength!==void 0&&i.length>o.maxLength)f.push({path:c,message:`String length must not exceed ${o.maxLength}`,expected:`<= ${o.maxLength}`,actual:i.length,rule:"maxLength"});if(o.pattern){if(!new RegExp(o.pattern).test(i))f.push({path:c,message:`String does not match pattern ${o.pattern}`,expected:o.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(o.minimum!==void 0&&i<o.minimum)f.push({path:c,message:`Value must be at least ${o.minimum}`,expected:`>= ${o.minimum}`,actual:i,rule:"minimum"});if(o.maximum!==void 0&&i>o.maximum)f.push({path:c,message:`Value must not exceed ${o.maximum}`,expected:`<= ${o.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&o.items)for(let h=0;h<i.length;h++){let d=c?`${c}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema(i[h],o.items,d,f,u,g),g.stopOnFirstError&&f.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let h=i;if(g.validateRequired&&o.required){for(let d of o.required)if(!(d in h)){if(f.push({path:c?`${c}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),g.stopOnFirstError)return}}if(o.properties){for(let[d,y]of Object.entries(o.properties))if(d in h){let b=c?`${c}.${d}`:d;if(this.validateObjectAgainstSchema(h[d],y,b,f,u,g),g.stopOnFirstError&&f.length>0)return}}if(o.additionalProperties===!1){let d=new Set(Object.keys(o.properties||{}));for(let y of Object.keys(h))if(!d.has(y))u.push({path:c?`${c}.${y}`:y,message:`Additional property '${y}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,o,c){let f=[],u=[];for(let g of o)try{let h=this.getValueByPath(i,g.path),d=this.validateWithRule(h,g,g.path);if(f.push(...d),c.stopOnFirstError&&f.length>0)break}catch(h){f.push({path:g.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:f.length===0,errors:f,warnings:u}}validateWithRule(i,o,c){let f=[];if(o.required&&(i===void 0||i===null))return f.push({path:c,message:o.message||`Property '${c}' is required`,expected:"required",rule:"required"}),f;if(i===void 0||i===null)return f;if(o.type){let u=Array.isArray(i)?"array":typeof i;if(u!==o.type)f.push({path:c,message:o.message||`Expected type ${o.type}, got ${u}`,expected:o.type,actual:u,rule:"type"})}if(o.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<o.min)f.push({path:c,message:o.message||`Value must be at least ${o.min}`,expected:`>= ${o.min}`,actual:u,rule:"min"})}if(o.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>o.max)f.push({path:c,message:o.message||`Value must not exceed ${o.max}`,expected:`<= ${o.max}`,actual:u,rule:"max"})}if(o.pattern&&typeof i==="string"){if(!o.pattern.test(i))f.push({path:c,message:o.message||`Value does not match pattern ${o.pattern}`,expected:o.pattern.toString(),actual:i,rule:"pattern"})}if(o.enum&&!o.enum.includes(i))f.push({path:c,message:o.message||`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"});if(o.validator){let u=o.validator(i);if(u)f.push({path:c,message:o.message||u,rule:"custom"})}return f}getValueByPath(i,o){if(!o)return i;let c=o.split("."),f=i;for(let u of c)if(f&&typeof f==="object"&&u in f)f=f[u];else return;return f}generateRulesFromInterface(i){let o=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let f of c){let[,u,g,h]=f;o.push({path:u,required:!g,type:this.mapTypeScriptType(h)})}return o}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:gs},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Dr{fileLoader=new Bt;envProcessor=new Mt;validator=new Nr;async loadConfig(i){let o=Date.now(),{cache:c,performance:f,schema:u,validate:g,...h}=i;try{if(c?.enabled){let y=this.checkCache(h.name||"",h);if(y)return y}let d;try{d=await this.loadConfigurationStrategies(h,!0,c)}catch(y){let b=h.__strictErrorHandling;if(y instanceof Error&&y.name==="ConfigNotFoundError"){if(b)throw y;d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(y instanceof Error&&y.name==="ConfigLoadError"){let S=y.message.includes("EACCES")||y.message.includes("EPERM")||y.message.includes("permission denied"),v=!S&&(y.message.includes("syntax")||y.message.includes("Expected")||y.message.includes("Unexpected")||y.message.includes("BuildMessage")||y.message.includes("errors building")),k=y.message.includes("Configuration must export a valid object")||y.message.includes("Configuration file is empty and exports nothing");if(b&&(k||S))throw y;if(v&&(!b||!k))d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!b)d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${y.message}`]};else throw y}else d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${y instanceof Error?y.message:String(y)}`]}}if(u||g)await this.validateConfiguration(d.config,u,g,h.name);if(c?.enabled&&d)this.cacheResult(h.name||"",d,c,h);if(f?.enabled){let y={operation:"loadConfig",duration:Date.now()-o,configName:h.name,timestamp:new Date};if(f.onMetrics)f.onMetrics(y);if(f.slowThreshold&&y.duration>f.slowThreshold)ce.warn(`Slow configuration loading detected: ${y.duration}ms for ${h.name}`);d.metrics=y}return d}catch(d){let y=Date.now()-o;throw ce.error(`Configuration loading failed after ${y}ms:`,[d instanceof Error?d:Error(String(d))]),d}}async loadConfigurationStrategies(i,o=!1,c){let{name:f="",alias:u,cwd:g,configDir:h,defaultConfig:d,checkEnv:y=!0,arrayStrategy:b="replace",verbose:S=!1}=i,v=g||ve.cwd(),k=[],x=await this.loadLocalConfiguration(f,u,v,h,d,b,S,y,c);if(x)return k.push(...this.getLocalSearchPaths(f,u,v,h)),this.finalizeResult(x,k,y,f,S);let R=await this.loadHomeConfiguration(f,u,d,b,S,y);if(R)return k.push(...this.getHomeSearchPaths(f,u)),this.finalizeResult(R,k,y,f,S);let A=await this.loadPackageJsonConfiguration(f,u,v,d,b,S,y);if(A)return k.push(X(v,"package.json")),this.finalizeResult(A,k,y,f,S);if(k.push(...this.getAllSearchPaths(f,u,v,h)),o)throw be.configNotFound(f,k,u);return{...await this.applyEnvironmentVariables(f,d,y,S),warnings:[`No configuration file found for "${f}"${u?` or alias "${u}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,o,c,f,u,g,h,d,y){let b=d?Ve(i,u,h):u,S=this.getLocalDirectories(c,f);for(let v of S){if(h)ce.info(`Searching for configuration in: ${v}`);let k=this.fileLoader.generateConfigPaths(i,v,o),x=await this.fileLoader.tryLoadFromPaths(k,b,{arrayStrategy:g,verbose:h,cacheTtl:y?.ttl,useCache:!y?.ttl||y.ttl>100});if(x){if(h)ce.success(`Configuration loaded from: ${x.source.path}`);return x}}return null}async loadHomeConfiguration(i,o,c,f,u,g){if(!i)return null;let h=g?Ve(i,c,u):c,d=[X(Ce(),".config",i),X(Ce(),".config"),Ce()];for(let y of d){if(u)ce.info(`Checking home directory: ${y}`);let b=this.fileLoader.generateConfigPaths(i,y,o),S=await this.fileLoader.tryLoadFromPaths(b,h,{arrayStrategy:f,verbose:u});if(S){if(u)ce.success(`Configuration loaded from home directory: ${S.source.path}`);return S}}return null}async loadPackageJsonConfiguration(i,o,c,f,u,g,h){let d=h?Ve(i,f,g):f;try{let y=X(c,"package.json");if(!mr(y))return null;let b=await import(y),S=b[i],v=i;if(!S&&o)S=b[o],v=o;if(S&&typeof S==="object"&&!Array.isArray(S)){if(g)ce.success(`Configuration loaded from package.json: ${v}`);return{config:Pr(d,S,u),source:{type:"package.json",path:y,priority:30,timestamp:new Date}}}}catch(y){if(g)ce.warn("Failed to load package.json:",[y instanceof Error?y:Error(String(y))])}return null}async applyEnvironmentVariables(i,o,c,f){if(!c||!i||typeof o!=="object"||o===null||Array.isArray(o))return{config:o,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ve(i,o,f),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,o,c,f,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,o,c,f){let u=[];if(c){let g=c(i);if(g)u.push(...g)}if(o){let g=await this.validator.validateConfiguration(i,o);if(!g.isValid)u.push(...g.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(u.length>0)throw be.configValidation(f||"unknown",u,f)}checkCache(i,o){let c=this.generateCacheKey(i,o);return Ie.get(c)||null}cacheResult(i,o,c,f){let u=this.generateCacheKey(i,f);Ie.set(u,o,void 0,c.ttl)}generateCacheKey(i,o){let c=[i];if(o.alias)c.push(`alias:${o.alias}`);if(o.cwd)c.push(`cwd:${o.cwd}`);if(o.configDir)c.push(`configDir:${o.configDir}`);if("checkEnv"in o)c.push(`checkEnv:${o.checkEnv}`);return c.join("|")}getLocalDirectories(i,o){return Array.from(new Set([i,X(i,"config"),X(i,".config"),o?X(i,o):void 0].filter(Boolean)))}getAllSearchPaths(i,o,c,f){let u=[];return u.push(...this.getLocalSearchPaths(i,o,c,f)),u.push(...this.getHomeSearchPaths(i,o)),u.push(X(c,"package.json")),u}getLocalSearchPaths(i,o,c,f){let u=this.getLocalDirectories(c,f),g=[];for(let h of u)g.push(...this.fileLoader.generateConfigPaths(i,h,o));return g}getHomeSearchPaths(i,o){if(!i)return[];let c=[X(Ce(),".config",i),X(Ce(),".config"),Ce()],f=[];for(let u of c)f.push(...this.fileLoader.generateConfigPaths(i,u,o));return f}async loadConfigWithResult(i){return this.loadConfig(i)}}function Pn(i){let c=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),f=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return c||f}async function go(i){return pe.loadConfig({...i,__strictErrorHandling:!0})}async function as(i){let o="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let f;if(c)f=await pe.loadConfig(i);else f=await pe.loadConfig({...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}});return f?.config??o}catch(f){let u=f instanceof Error?f.name:"UnknownError",g=f instanceof Error?f.message:String(f);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||g.includes("config"))&&i.verbose)ce.warn("Unexpected error loading config, using defaults:",[f instanceof Error?f:Error(String(f))]);let d=c?{...i,defaultConfig:o}:{...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await pe.applyEnvironmentVariables(d.name||"",o,!0,d.verbose||!1))?.config??o;return o}}async function mo(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:o}=await import("process");try{return(await pe.loadConfig({name:i,cwd:o(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(c){if(c instanceof Error&&(c.name==="ConfigNotFoundError"||c.name==="ConfigLoadError"&&Pn(c)))return(await pe.applyEnvironmentVariables(i,{},!0,!1)).config;throw c}}try{return(await pe.loadConfig({...i,cwd:i.cwd||ve.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(o){if(o instanceof Error&&(o.name==="ConfigNotFoundError"||o.name==="ConfigLoadError"&&Pn(o)))return(await pe.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw o}}async function po(i,o,c="replace"){let f=new Bt;try{let u=await f.loadFromPath(i,o,{arrayStrategy:c,useCache:!1,trackPerformance:!1});return u?u.config:null}catch{return null}}function Ve(i,o,c=!1){let f=new Mt,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function g(h,d=[]){let y={...h};for(let[b,S]of Object.entries(h)){let v=[...d,b],k=[`${u}_${v.join("_").toUpperCase()}`,`${u}_${v.map((A)=>A.toUpperCase()).join("")}`,`${u}_${v.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],x,R;for(let A of k)if(x=ve.env[A],x!==void 0){R=A;break}if(x!==void 0&&R)if(typeof S==="boolean")y[b]=["true","1","yes"].includes(x.toLowerCase());else if(typeof S==="number"){let A=Number(x);if(!Number.isNaN(A))y[b]=A}else if(Array.isArray(S))try{y[b]=JSON.parse(x)}catch{y[b]=x.split(",").map((A)=>A.trim())}else y[b]=x;else if(S&&typeof S==="object"&&!Array.isArray(S))y[b]=g(S,v)}return y}return g(o)}function yo(i){let o=X(ve.cwd(),i.configDir),c=X(ve.cwd(),i.generatedDir),f=X(c,"config-types.ts");if(!mr(rn(f)))si(rn(f),{recursive:!0,mode:511});let u=mr(o)?ii(o).map((h)=>h.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],g=`// Generated by bunfig v${qo}
|
|
31
|
+
`;return c}}function co(i,o){let c=cs("process");if(typeof c>"u"||!c.env)return o;let f=c.env[i];return f!==void 0?f:o}function ss(i,o,c={}){return is(i,o,c,new WeakMap)}function is(i,o,c,f){let{arrayMergeMode:u="replace",skipNullish:g=!1,customMerger:h}=c;if(o===null||o===void 0)return g?i:o;if(h){let d=h(i,o);if(d!==void 0)return d}if(Array.isArray(o)||Array.isArray(i))return os(i,o,u,f);if(!ne(o)||!ne(i))return o;return ho(i,o,c,f)}function os(i,o,c,f){if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(i)&&!Array.isArray(o))return o;if(Array.isArray(o)&&Array.isArray(i))switch(c){case"replace":return o;case"concat":return lo(i,o);case"smart":return fo(i,o,f);default:return o}return o}function lo(i,o){let c=[...o];for(let f of i)if(!c.some((u)=>yr(u,f)))c.push(f);return c}function fo(i,o,c){if(o.length===0)return i;if(i.length===0)return o;if(ne(o[0])&&ne(i[0]))return uo(i,o,c);if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}function uo(i,o,c){let f=[...o];for(let u of i){if(!ne(u)){f.push(u);continue}let g=["id","name","key","path","type"],h=!1;for(let d of g)if(d in u){if(f.find((b)=>ne(b)&&(d in b)&&b[d]===u[d])){h=!0;break}}if(!h)f.push(u)}return f}function ho(i,o,c,f){let u=o;if(ne(u)&&f.has(u))return f.get(u);let g={...i};if(ne(u))f.set(u,g);for(let h in u){if(!Object.prototype.hasOwnProperty.call(u,h))continue;let d=u[h],y=g[h];if(c.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){g[h]=d;continue}if(ne(d)&&ne(y))g[h]=is(y,d,c,f);else if(Array.isArray(d)||Array.isArray(y))g[h]=os(y,d,c.arrayMergeMode||"smart",f);else g[h]=d}return g}function Pr(i,o,c="replace"){return ss(i,o,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function yr(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!yr(i[c],o[c]))return!1;return!0}if(ne(i)&&ne(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!yr(i[u],o[u]))return!1}return!0}return!1}function ne(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Bt{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,o,c={}){let{arrayStrategy:f="replace",useCache:u=!0,cacheTtl:g,trackPerformance:h=!0,verbose:d=!1}=c;if(u){let b=Ie.getWithFileCheck("file",i);if(b){if(d)console.log(`Configuration loaded from cache: ${i}`);return b}}let y=async()=>{if(!ut(i))return null;try{let b=`?t=${Date.now()}`,S=await import(i+b),v=S.default||S,C="default"in S,E=Object.keys(S).length>0;if(!C&&!E)throw new He(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof v!=="object"||v===null||Array.isArray(v))throw new He(i,Error("Configuration must export a valid object"),"unknown");let O={config:Pr(o,v,f),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)Ie.setWithFileCheck("file",O,i,g);return O}catch(b){throw b instanceof Error?be.configLoad(i,b):be.configLoad(i,Error(String(b)))}};if(h)return Ge.track("loadFromPath",y,{path:i});return y()}async tryLoadFromPaths(i,o,c={}){for(let f of i)try{let u=await this.loadFromPath(f,o,c);if(u)return u}catch(u){if(u instanceof Error&&u.name==="ConfigLoadError")throw u;if(c.verbose)console.warn(`Failed to load config from ${f}:`,u)}return null}generateConfigPaths(i,o,c){let f=this.generateNamePatterns(i,c),u=[];for(let g of f)for(let h of this.extensions)u.push(sr(o,`${g}${h}`));return u}generateNamePatterns(i,o){let c=[];if(c.push("config",".config"),i)c.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(o){if(c.push(o,`.${o}.config`,`${o}.config`,`.${o}`),i)c.push(`${i}.${o}.config`,`.${i}.${o}.config`)}return c.filter(Boolean)}checkFileAccess(i){return rs(async()=>ut(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,o,c){let f=[];if(!ut(i))return f;if(o||c){let u=this.generateNamePatterns(o||"",c);for(let g of u)for(let h of this.extensions){let d=sr(i,`${g}${h}`);if(await this.checkFileAccess(d))f.push(d)}}else try{let{readdirSync:u}=await import("fs"),g=u(i);for(let h of g)if(this.looksLikeConfigFile(h)){let d=sr(i,h);if(await this.checkFileAccess(d))f.push(d)}}catch{return[]}return f}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((c)=>c.test(i))}async validateConfigFile(i){let o=[];try{if(!ut(i))return o.push("Configuration file does not exist"),o;let c=await import(i),f=c.default||c;if(f===void 0)o.push("Configuration file must export a default value or named exports");else if(typeof f!=="object"||f===null)o.push("Configuration must be an object");else if(Array.isArray(f))o.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),g=u(i,"utf8");JSON.parse(g)}catch(u){o.push(`Invalid JSON syntax: ${u}`)}}catch(c){o.push(`Failed to load configuration file: ${c}`)}return o}async getFileModificationTime(i){try{let{statSync:o}=await import("fs");return o(i).mtime}catch{return null}}async preloadConfigurations(i,o={}){let c=new Map;return await Promise.allSettled(i.map(async(f)=>{try{let u=await this.loadFromPath(f,{},o);if(u)c.set(f,u.config)}catch(u){if(o.verbose)console.warn(`Failed to preload ${f}:`,u)}})),c}}class Nr{async validateConfiguration(i,o,c={}){let{stopOnFirstError:f=!1,validateRequired:u=!0,validateTypes:g=!0,customRules:h=[],trackPerformance:d=!0,verbose:y=!1}=c,b=async()=>{let S=[],v=[],C={stopOnFirstError:f,validateRequired:u,validateTypes:g,customRules:h,trackPerformance:d,verbose:y};try{if(typeof o==="string")return await this.validateWithSchemaFile(i,o,C);else if(Array.isArray(o))return this.validateWithRules(i,[...o,...h],C);else return this.validateWithJSONSchema(i,o,C)}catch(E){return S.push({path:"",message:`Validation failed: ${E}`,rule:"system"}),{isValid:!1,errors:S,warnings:v}}};if(d)return await Ge.track("validateConfiguration",b);return b()}async validateWithSchemaFile(i,o,c){try{if(!ki(o))throw new ze(o,[{path:"",message:"Schema file does not exist"}]);let f=await import(o),u=f.default||f;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(f){throw new ze(o,[{path:"",message:`Failed to load schema: ${f}`}])}}validateWithJSONSchema(i,o,c){let f=[],u=[];return this.validateObjectAgainstSchema(i,o,"",f,u,c),{isValid:f.length===0,errors:f,warnings:u}}validateObjectAgainstSchema(i,o,c,f,u,g){if(g.validateTypes&&o.type){let h=Array.isArray(i)?"array":typeof i,d=Array.isArray(o.type)?o.type:[o.type];if(!d.includes(h)){if(f.push({path:c,message:`Expected type ${d.join(" or ")}, got ${h}`,expected:d.join(" or "),actual:h,rule:"type"}),g.stopOnFirstError)return}}if(o.enum&&!o.enum.includes(i)){if(f.push({path:c,message:`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"}),g.stopOnFirstError)return}if(typeof i==="string"){if(o.minLength!==void 0&&i.length<o.minLength)f.push({path:c,message:`String length must be at least ${o.minLength}`,expected:`>= ${o.minLength}`,actual:i.length,rule:"minLength"});if(o.maxLength!==void 0&&i.length>o.maxLength)f.push({path:c,message:`String length must not exceed ${o.maxLength}`,expected:`<= ${o.maxLength}`,actual:i.length,rule:"maxLength"});if(o.pattern){if(!new RegExp(o.pattern).test(i))f.push({path:c,message:`String does not match pattern ${o.pattern}`,expected:o.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(o.minimum!==void 0&&i<o.minimum)f.push({path:c,message:`Value must be at least ${o.minimum}`,expected:`>= ${o.minimum}`,actual:i,rule:"minimum"});if(o.maximum!==void 0&&i>o.maximum)f.push({path:c,message:`Value must not exceed ${o.maximum}`,expected:`<= ${o.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&o.items)for(let h=0;h<i.length;h++){let d=c?`${c}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema(i[h],o.items,d,f,u,g),g.stopOnFirstError&&f.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let h=i;if(g.validateRequired&&o.required){for(let d of o.required)if(!(d in h)){if(f.push({path:c?`${c}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),g.stopOnFirstError)return}}if(o.properties){for(let[d,y]of Object.entries(o.properties))if(d in h){let b=c?`${c}.${d}`:d;if(this.validateObjectAgainstSchema(h[d],y,b,f,u,g),g.stopOnFirstError&&f.length>0)return}}if(o.additionalProperties===!1){let d=new Set(Object.keys(o.properties||{}));for(let y of Object.keys(h))if(!d.has(y))u.push({path:c?`${c}.${y}`:y,message:`Additional property '${y}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,o,c){let f=[],u=[];for(let g of o)try{let h=this.getValueByPath(i,g.path),d=this.validateWithRule(h,g,g.path);if(f.push(...d),c.stopOnFirstError&&f.length>0)break}catch(h){f.push({path:g.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:f.length===0,errors:f,warnings:u}}validateWithRule(i,o,c){let f=[];if(o.required&&(i===void 0||i===null))return f.push({path:c,message:o.message||`Property '${c}' is required`,expected:"required",rule:"required"}),f;if(i===void 0||i===null)return f;if(o.type){let u=Array.isArray(i)?"array":typeof i;if(u!==o.type)f.push({path:c,message:o.message||`Expected type ${o.type}, got ${u}`,expected:o.type,actual:u,rule:"type"})}if(o.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<o.min)f.push({path:c,message:o.message||`Value must be at least ${o.min}`,expected:`>= ${o.min}`,actual:u,rule:"min"})}if(o.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>o.max)f.push({path:c,message:o.message||`Value must not exceed ${o.max}`,expected:`<= ${o.max}`,actual:u,rule:"max"})}if(o.pattern&&typeof i==="string"){if(!o.pattern.test(i))f.push({path:c,message:o.message||`Value does not match pattern ${o.pattern}`,expected:o.pattern.toString(),actual:i,rule:"pattern"})}if(o.enum&&!o.enum.includes(i))f.push({path:c,message:o.message||`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"});if(o.validator){let u=o.validator(i);if(u)f.push({path:c,message:o.message||u,rule:"custom"})}return f}getValueByPath(i,o){if(!o)return i;let c=o.split("."),f=i;for(let u of c)if(f&&typeof f==="object"&&u in f)f=f[u];else return;return f}generateRulesFromInterface(i){let o=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let f of c){let[,u,g,h]=f;o.push({path:u,required:!g,type:this.mapTypeScriptType(h)})}return o}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:gs},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Dr{fileLoader=new Bt;envProcessor=new Mt;validator=new Nr;async loadConfig(i){let o=Date.now(),{cache:c,performance:f,schema:u,validate:g,...h}=i;try{if(c?.enabled){let y=this.checkCache(h.name||"",h);if(y)return y}let d;try{d=await this.loadConfigurationStrategies(h,!0,c)}catch(y){let b=h.__strictErrorHandling;if(y instanceof Error&&y.name==="ConfigNotFoundError"){if(b)throw y;d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(y instanceof Error&&y.name==="ConfigLoadError"){let S=y.message.includes("EACCES")||y.message.includes("EPERM")||y.message.includes("permission denied"),v=!S&&(y.message.includes("syntax")||y.message.includes("Expected")||y.message.includes("Unexpected")||y.message.includes("BuildMessage")||y.message.includes("errors building")),C=y.message.includes("Configuration must export a valid object")||y.message.includes("Configuration file is empty and exports nothing");if(b&&(C||S))throw y;if(v&&(!b||!C))d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!b)d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${y.message}`]};else throw y}else d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${y instanceof Error?y.message:String(y)}`]}}if(u||g)await this.validateConfiguration(d.config,u,g,h.name);if(c?.enabled&&d)this.cacheResult(h.name||"",d,c,h);if(f?.enabled){let y={operation:"loadConfig",duration:Date.now()-o,configName:h.name,timestamp:new Date};if(f.onMetrics)f.onMetrics(y);if(f.slowThreshold&&y.duration>f.slowThreshold)ce.warn(`Slow configuration loading detected: ${y.duration}ms for ${h.name}`);d.metrics=y}return d}catch(d){let y=Date.now()-o;throw ce.error(`Configuration loading failed after ${y}ms:`,[d instanceof Error?d:Error(String(d))]),d}}async loadConfigurationStrategies(i,o=!1,c){let{name:f="",alias:u,cwd:g,configDir:h,defaultConfig:d,checkEnv:y=!0,arrayStrategy:b="replace",verbose:S=!1}=i,v=g||ve.cwd(),C=[],E=await this.loadLocalConfiguration(f,u,v,h,d,b,S,y,c);if(E)return C.push(...this.getLocalSearchPaths(f,u,v,h)),this.finalizeResult(E,C,y,f,S);let A=await this.loadHomeConfiguration(f,u,d,b,S,y);if(A)return C.push(...this.getHomeSearchPaths(f,u)),this.finalizeResult(A,C,y,f,S);let k=await this.loadPackageJsonConfiguration(f,u,v,d,b,S,y);if(k)return C.push(X(v,"package.json")),this.finalizeResult(k,C,y,f,S);if(C.push(...this.getAllSearchPaths(f,u,v,h)),o)throw be.configNotFound(f,C,u);return{...await this.applyEnvironmentVariables(f,d,y,S),warnings:[`No configuration file found for "${f}"${u?` or alias "${u}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,o,c,f,u,g,h,d,y){let b=d?Ve(i,u,h):u,S=this.getLocalDirectories(c,f);for(let v of S){if(h)ce.info(`Searching for configuration in: ${v}`);let C=this.fileLoader.generateConfigPaths(i,v,o),E=await this.fileLoader.tryLoadFromPaths(C,b,{arrayStrategy:g,verbose:h,cacheTtl:y?.ttl,useCache:!y?.ttl||y.ttl>100});if(E){if(h)ce.success(`Configuration loaded from: ${E.source.path}`);return E}}return null}async loadHomeConfiguration(i,o,c,f,u,g){if(!i)return null;let h=g?Ve(i,c,u):c,d=[X(Ce(),".config",i),X(Ce(),".config"),Ce()];for(let y of d){if(u)ce.info(`Checking home directory: ${y}`);let b=this.fileLoader.generateConfigPaths(i,y,o),S=await this.fileLoader.tryLoadFromPaths(b,h,{arrayStrategy:f,verbose:u});if(S){if(u)ce.success(`Configuration loaded from home directory: ${S.source.path}`);return S}}return null}async loadPackageJsonConfiguration(i,o,c,f,u,g,h){let d=h?Ve(i,f,g):f;try{let y=X(c,"package.json");if(!mr(y))return null;let b=await import(y),S=b[i],v=i;if(!S&&o)S=b[o],v=o;if(S&&typeof S==="object"&&!Array.isArray(S)){if(g)ce.success(`Configuration loaded from package.json: ${v}`);return{config:Pr(d,S,u),source:{type:"package.json",path:y,priority:30,timestamp:new Date}}}}catch(y){if(g)ce.warn("Failed to load package.json:",[y instanceof Error?y:Error(String(y))])}return null}async applyEnvironmentVariables(i,o,c,f){if(!c||!i||typeof o!=="object"||o===null||Array.isArray(o))return{config:o,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ve(i,o,f),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,o,c,f,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,o,c,f){let u=[];if(c){let g=c(i);if(g)u.push(...g)}if(o){let g=await this.validator.validateConfiguration(i,o);if(!g.isValid)u.push(...g.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(u.length>0)throw be.configValidation(f||"unknown",u,f)}checkCache(i,o){let c=this.generateCacheKey(i,o);return Ie.get(c)||null}cacheResult(i,o,c,f){let u=this.generateCacheKey(i,f);Ie.set(u,o,void 0,c.ttl)}generateCacheKey(i,o){let c=[i];if(o.alias)c.push(`alias:${o.alias}`);if(o.cwd)c.push(`cwd:${o.cwd}`);if(o.configDir)c.push(`configDir:${o.configDir}`);if("checkEnv"in o)c.push(`checkEnv:${o.checkEnv}`);return c.join("|")}getLocalDirectories(i,o){return Array.from(new Set([i,X(i,"config"),X(i,".config"),o?X(i,o):void 0].filter(Boolean)))}getAllSearchPaths(i,o,c,f){let u=[];return u.push(...this.getLocalSearchPaths(i,o,c,f)),u.push(...this.getHomeSearchPaths(i,o)),u.push(X(c,"package.json")),u}getLocalSearchPaths(i,o,c,f){let u=this.getLocalDirectories(c,f),g=[];for(let h of u)g.push(...this.fileLoader.generateConfigPaths(i,h,o));return g}getHomeSearchPaths(i,o){if(!i)return[];let c=[X(Ce(),".config",i),X(Ce(),".config"),Ce()],f=[];for(let u of c)f.push(...this.fileLoader.generateConfigPaths(i,u,o));return f}async loadConfigWithResult(i){return this.loadConfig(i)}}function Pn(i){let c=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),f=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return c||f}async function go(i){return pe.loadConfig({...i,__strictErrorHandling:!0})}async function as(i){let o="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let f;if(c)f=await pe.loadConfig(i);else f=await pe.loadConfig({...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}});return f?.config??o}catch(f){let u=f instanceof Error?f.name:"UnknownError",g=f instanceof Error?f.message:String(f);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||g.includes("config"))&&i.verbose)ce.warn("Unexpected error loading config, using defaults:",[f instanceof Error?f:Error(String(f))]);let d=c?{...i,defaultConfig:o}:{...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await pe.applyEnvironmentVariables(d.name||"",o,!0,d.verbose||!1))?.config??o;return o}}async function mo(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:o}=await import("process");try{return(await pe.loadConfig({name:i,cwd:o(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(c){if(c instanceof Error&&(c.name==="ConfigNotFoundError"||c.name==="ConfigLoadError"&&Pn(c)))return(await pe.applyEnvironmentVariables(i,{},!0,!1)).config;throw c}}try{return(await pe.loadConfig({...i,cwd:i.cwd||ve.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(o){if(o instanceof Error&&(o.name==="ConfigNotFoundError"||o.name==="ConfigLoadError"&&Pn(o)))return(await pe.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw o}}async function po(i,o,c="replace"){let f=new Bt;try{let u=await f.loadFromPath(i,o,{arrayStrategy:c,useCache:!1,trackPerformance:!1});return u?u.config:null}catch{return null}}function Ve(i,o,c=!1){let f=new Mt,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function g(h,d=[]){let y={...h};for(let[b,S]of Object.entries(h)){let v=[...d,b],C=[`${u}_${v.join("_").toUpperCase()}`,`${u}_${v.map((k)=>k.toUpperCase()).join("")}`,`${u}_${v.map((k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],E,A;for(let k of C)if(E=ve.env[k],E!==void 0){A=k;break}if(E!==void 0&&A)if(typeof S==="boolean")y[b]=["true","1","yes"].includes(E.toLowerCase());else if(typeof S==="number"){let k=Number(E);if(!Number.isNaN(k))y[b]=k}else if(Array.isArray(S))try{y[b]=JSON.parse(E)}catch{y[b]=E.split(",").map((k)=>k.trim())}else y[b]=E;else if(S&&typeof S==="object"&&!Array.isArray(S))y[b]=g(S,v)}return y}return g(o)}function yo(i){let o=X(ve.cwd(),i.configDir),c=X(ve.cwd(),i.generatedDir),f=X(c,"config-types.ts");if(!mr(rn(f)))si(rn(f),{recursive:!0,mode:511});let u=mr(o)?ii(o).map((h)=>h.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],g=`// Generated by bunfig v${qo}
|
|
32
32
|
export type ConfigNames = ${u.length?`'${u.join("' | '")}'`:"string"}
|
|
33
|
-
`;oi(f,g,{mode:438})}function wo(i){let o=null,c=null,f=()=>{if(!c)c=as(i).then((g)=>(o=g,g),(g)=>{let h="defaultConfig"in i?i.defaultConfig:{};if(o=h,"verbose"in i&&i.verbose)ce.warn("Config loading failed, using defaults:",[g instanceof Error?g:Error(String(g))]);return h});return c},u="defaultConfig"in i?i.defaultConfig:{};return o=u,f(),new Proxy({},{get(g,h){if(o)return o[h];let d=u[h];return f(),d},has(g,h){return h in(o||u)},ownKeys(){return Object.keys(o||u)},getOwnPropertyDescriptor(g,h){return Object.getOwnPropertyDescriptor(o||u,h)},set(g,h,d){if(!o)o={...u};return o[h]=d,!0}})}function bo(i){let o=Cn(Ri.cwd(),i?.configDir||"./config");function c(){if(!Ai(o))return[];let u=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),g=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],h=Li(o).filter((y)=>u.has(ir(y))).map((y)=>({base:y.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:y})),d=new Map;for(let{base:y,file:b}of h){let S=ir(b).toLowerCase(),v=d.get(y);if(!v){d.set(y,b);continue}let
|
|
33
|
+
`;oi(f,g,{mode:438})}function wo(i){let o=null,c=null,f=()=>{if(!c)c=as(i).then((g)=>(o=g,g),(g)=>{let h="defaultConfig"in i?i.defaultConfig:{};if(o=h,"verbose"in i&&i.verbose)ce.warn("Config loading failed, using defaults:",[g instanceof Error?g:Error(String(g))]);return h});return c},u="defaultConfig"in i?i.defaultConfig:{};return o=u,f(),new Proxy({},{get(g,h){if(o)return o[h];let d=u[h];return f(),d},has(g,h){return h in(o||u)},ownKeys(){return Object.keys(o||u)},getOwnPropertyDescriptor(g,h){return Object.getOwnPropertyDescriptor(o||u,h)},set(g,h,d){if(!o)o={...u};return o[h]=d,!0}})}function bo(i){let o=Cn(Ri.cwd(),i?.configDir||"./config");function c(){if(!Ai(o))return[];let u=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),g=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],h=Li(o).filter((y)=>u.has(ir(y))).map((y)=>({base:y.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:y})),d=new Map;for(let{base:y,file:b}of h){let S=ir(b).toLowerCase(),v=d.get(y);if(!v){d.set(y,b);continue}let C=ir(v).toLowerCase();if(g.indexOf(S)<g.indexOf(C))d.set(y,b)}return Array.from(d.entries()).map(([y,b])=>({base:y,file:b})).sort((y,b)=>y.base.localeCompare(b.base))}function f(){let u=c(),g=u.map((b)=>b.base),h=g.length?g.map((b)=>`'${b}'`).join(" | "):"string",d=u.length?`{
|
|
34
34
|
${u.map((b)=>{let S=Cn(o,b.file).replace(/\\/g,"/");return` '${b.base}': typeof import('${S}').default`}).join(`,
|
|
35
35
|
`)}
|
|
36
36
|
}`:"Record<string, any>";return`export type ConfigNames = ${h}
|
|
37
37
|
export type ConfigByName = ${d}
|
|
38
38
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
39
|
export type ConfigOf = Config
|
|
40
|
-
`}return{name:"bunfig-plugin",setup(u){u.onResolve({filter:/^virtual:bunfig-types$/},(g)=>({path:g.path,namespace:"bunfig-virtual"})),u.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:f(),loader:"ts"}))}}}var cs,Ie,Ge,ls,So,vo,Nn,bt,wr,Y,j,$o,Dn,Eo,Fn,Co,xo,lr,To,In,_n,fr,ko,Ao,Lo,Ro,St,fs,Oo,J,Po,No,Mn,vt,br,U,P,Do,Bn,Fo,jn,Io,_o,ur,Mo,Kn,Wn,Bo,hr,jo,Ko,Vo,Wo,Qo,$t,us,Uo,qo="0.15.6",re,Pt,He,Sr,vr,Nt,$r,Er,ze,Cr,xr,be,hs,gs,ce,pe,ds,ms,Ho=qi(async()=>{cs=import.meta.require,Ie=new Ar,Ge=new Lr,ls={createKey:Hi,isEquivalent:zi,estimateMemoryUsage:Gi},So=Tt(pr.cwd(),"config"),vo=Tt(pr.cwd(),"src/generated"),Nn=xt.env.CLARITY_LOG_DIR||li(Zi(),"logs"),bt={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Nn,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},wr=await Xi(),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`,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=Y,$o=Y.red,Dn=Y.green,Eo=Y.yellow,Fn=Y.blue,Co=Y.magenta,xo=Y.cyan,lr=Y.white,To=Y.gray,In=Y.bgRed,_n=Y.bgYellow,fr=Y.bold,ko=Y.dim,Ao=Y.italic,Lo=Y.underline,Ro=Y.reset,St={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},fs={debug:"\uD83D\uDD0D",info:Fn("\u2139"),success:Dn("\u2713"),warning:_n(lr(fr(" WARN "))),error:In(lr(fr(" ERROR ")))},Oo=new Lt("stacks"),J=new Lt("bunfig",{showTags:!0}),Po=Z(Qe.cwd(),"config"),No=Z(Qe.cwd(),"src/generated"),Mn=Ct.env.CLARITY_LOG_DIR||ai(no(),"logs"),vt={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mn,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},br=await so(),U={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},P=U,Do=U.red,Bn=U.green,Fo=U.yellow,jn=U.blue,Io=U.magenta,_o=U.cyan,ur=U.white,Mo=U.gray,Kn=U.bgRed,Wn=U.bgYellow,Bo=U.bgGray,hr=U.bold,jo=U.dim,Ko=U.italic,Vo=U.underline,Wo=U.strikethrough,Qo=U.reset,$t={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},us={debug:"\uD83D\uDD0D",info:jn("\u2139"),success:Bn("\u2713"),warning:Wn(ur(hr(" WARN "))),error:Kn(ur(hr(" ERROR ")))},Uo=new Ot("stacks"),re=class extends Error{timestamp;context;constructor(o,c={}){super(o);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=c,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let o=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([c,f])=>`${c}: ${f}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${o}`}},Pt=class extends re{code="CONFIG_NOT_FOUND";constructor(o,c,f){let u=f?` or alias "${f}"`:"";super(`Configuration "${o}"${u} not found`,{configName:o,alias:f,searchPaths:c,searchPathCount:c.length})}},He=class extends re{code="CONFIG_LOAD_ERROR";constructor(o,c,f){super(`Failed to load configuration from "${o}": ${c.message}`,{configPath:o,configName:f,originalError:c.name,originalMessage:c.message});this.cause=c}},Sr=class extends re{code="CONFIG_VALIDATION_ERROR";constructor(o,c,f){super(`Configuration validation failed for "${o}"`,{configPath:o,configName:f,validationErrors:c,errorCount:c.length})}},vr=class extends re{code="CONFIG_MERGE_ERROR";constructor(o,c,f,u){super(`Failed to merge configuration from "${o}" with "${c}": ${f.message}`,{sourcePath:o,targetPath:c,configName:u,originalError:f.name,originalMessage:f.message});this.cause=f}},Nt=class extends re{code="ENV_VAR_ERROR";constructor(o,c,f,u){super(`Failed to parse environment variable "${o}" with value "${c}" as ${f}`,{envKey:o,envValue:c,expectedType:f,configName:u})}},$r=class extends re{code="FILE_SYSTEM_ERROR";constructor(o,c,f){super(`File system ${o} failed for "${c}": ${f.message}`,{operation:o,path:c,originalError:f.name,originalMessage:f.message});this.cause=f}},Er=class extends re{code="TYPE_GENERATION_ERROR";constructor(o,c,f){super(`Failed to generate types from "${o}" to "${c}": ${f.message}`,{configDir:o,outputPath:c,originalError:f.name,originalMessage:f.message});this.cause=f}},ze=class extends re{code="SCHEMA_VALIDATION_ERROR";constructor(o,c,f){super(`Schema validation failed${f?` for config "${f}"`:""}`,{schemaPath:o,configName:f,validationErrors:c,errorCount:c.length})}},Cr=class extends re{code="BROWSER_CONFIG_ERROR";constructor(o,c,f,u){super(`Failed to fetch configuration from "${o}": ${c} ${f}`,{endpoint:o,status:c,statusText:f,configName:u})}},xr=class extends re{code="PLUGIN_ERROR";constructor(o,c,f){super(`Plugin "${o}" failed during ${c}: ${f.message}`,{pluginName:o,operation:c,originalError:f.name,originalMessage:f.message});this.cause=f}},be={configNotFound(i,o,c){return new Pt(i,o,c)},configLoad(i,o,c){return new He(i,o,c)},configValidation(i,o,c){return new Sr(i,o,c)},configMerge(i,o,c,f){return new vr(i,o,c,f)},envVar(i,o,c,f){return new Nt(i,o,c,f)},fileSystem(i,o,c){return new $r(i,o,c)},typeGeneration(i,o,c){return new Er(i,o,c)},schemaValidation(i,o,c){return new ze(i,o,c)},browserConfig(i,o,c,f){return new Cr(i,o,c,f)},plugin(i,o,c){return new xr(i,o,c)}},hs={replace:"replace",concat:"concat",smart:"smart"},gs=/^https?:\/\//,ce=new Ot("bunfig",{showTags:!0}),pe=new Dr,ds=X(ve.cwd(),"config"),ms=X(ve.cwd(),"src/generated")});function zo(i,o={}){let c=kt.cwd();while(c.includes("storage"))c=xn(c,"..");let f=xn(c,i||"");if(o?.relative)return Pi(kt.cwd(),f);return f}var Go=kt.env.CLARITY_LOG_DIR||Oi(zo(),"logs"),ps={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Go,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Dt={...ps},rl=(async()=>{try{let{loadConfig:i}=await Ho().then(()=>Xn),o=await i({name:"clarity",alias:"logging",defaultConfig:ps,cwd:kt.cwd()});if(o)Object.assign(Dt,o)}catch{}return Dt})();function q(){if(me.env.NODE_ENV==="test"||me.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Yo(){if(me.env.NODE_ENV==="test"||me.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof me<"u"){let i=me.type;if(i==="renderer"||i==="worker")return!1;return!!(me.versions&&(me.versions.node||me.versions.bun))}return!1}class ys{async format(i){let o=await Yo(),c=await this.getMetadata(o);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:o}=await import("os");return{pid:De.pid,hostname:o(),environment:De.env.NODE_ENV||"development",platform:De.platform,version:De.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:De.env.NODE_ENV||De.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var H={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"},N=H,{red:nl,green:Jo,yellow:sl,blue:Zo,magenta:il,cyan:ol,white:Qn,gray:al,bgRed:Xo,bgYellow:ea,bgGray:cl,bold:Un,dim:ll,italic:fl,underline:ul,strikethrough:hl,reset:gl}=H,gr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ta={debug:"\uD83D\uDD0D",info:Zo("\u2139"),success:Jo("\u2713"),warning:ea(Qn(Un(" WARN "))),error:Xo(Qn(Un(" ERROR ")))};class jt{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,o={}){this.name=i,this.config={...Dt},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new ys,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??F.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let o={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return o[i]>=o[c]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...gr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...gr};return{...gr,...i.fingersCrossed}}normalizeOptions(i){let o={format:"json",level:"info",logDirectory:Dt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}shouldWriteToFile(){return!q()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await _i(this.config.logDirectory,Ln.F_OK|Ln.W_OK)}catch(b){if(b instanceof Error&&"code"in b)if(b.code==="ENOENT")await Mi(this.config.logDirectory,{recursive:!0,mode:493});else if(b.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw b;else throw b}}catch(b){throw console.error("Debug: [writeToFile] Failed to create log directory:",b),b}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:he.from(i);try{if(!ht(this.currentLogFile))await cr(this.currentLogFile,"",{mode:420});if(u=An(this.currentLogFile,"a",420),Ii(u,y,{flag:"a"}),kn(u),u!==void 0)ar(u),u=void 0;if((await Pe(this.currentLogFile)).size===0){if(await cr(this.currentLogFile,y,{flag:"w",mode:420}),(await Pe(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(b){let S=b;if(S.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(S.code)){if(g<h-1){let v=typeof S.message==="string"?S.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,v);let k=d*2**g;await new Promise((x)=>setTimeout(x,k)),g++;continue}}if(S?.code&&["ENOSPC","EDQUOT"].includes(S.code))throw Error(`Disk quota exceeded or no space left on device: ${S.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",S),S}finally{if(u!==void 0)try{ar(u)}catch(b){console.error("Debug: [writeToFile] Error closing file descriptor:",b)}}}catch(y){if(g===h-1){let S=y,v=typeof S.message==="string"?S.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",v),y}g++;let b=d*2**(g-1);await new Promise((S)=>setTimeout(S,b))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ne(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 Ne(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Ne(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(q())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,y])=>y.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return or(16).toString("hex")}generateKey(){return or(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:o}=this.getCurrentKey(),c=or(16),f=Ni("aes-256-gcm",o,c),u=he.isBuffer(i)?i:he.from(i,"utf8"),g=f.update(u),h=f.final(),d=g.length+h.length,y=f.getAuthTag(),b=he.allocUnsafe(16+d+16);return c.copy(b,0),g.copy(b,16),h.copy(b,16+g.length),y.copy(b,16+d),{encrypted:b,iv:c}}async compressData(i){return new Promise((o,c)=>{let f=On(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(he.from(he.concat(u)))),f.on("error",c),f.write(i),f.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(q())return;if(!this.shouldWriteToFile())return;let i=await Pe(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await gt(this.config.logDirectory),g=u.filter((y)=>y.startsWith(this.name)&&/\.log\.\d+$/.test(y)).sort((y,b)=>{let S=Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(b.match(/\.log\.(\d+)$/)?.[1]||"0")-S}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await Pe(c).catch(()=>null))try{if(await Rn(c,d),o.compress)try{let y=`${d}.gz`;await this.compressLogFile(d,y),await dt(d)}catch(y){console.error("Error compressing rotated file:",y)}if(g.length===0&&!u.some((y)=>y.endsWith(".log.1")))try{let y=`${c}.1`;await cr(y,"")}catch(y){console.error("Error creating backup file:",y)}}catch(y){console.error(`Error during rotation: ${y instanceof Error?y.message:String(y)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await Pe(c).catch(()=>null))await Rn(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await gt(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await dt(Ne(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=Tn(i),f=Fi(o),u=On();await Ki(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(f);console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(o);console.log(o)}}shouldLog(i){if(!this.enabled)return!1;let o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),ht(this.currentLogFile))try{let i=An(this.currentLogFile,"r+");kn(i),ar(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let o=(await gt(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await dt(Ne(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?N.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q())return!1;let i=typeof F.env.NO_COLOR<"u",o=F.env.FORCE_COLOR==="0";if(i||o)return!1;return!!(typeof F.stderr<"u"&&F.stderr.isTTY||typeof F.stdout<"u"&&F.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(x)=>x.replace(this.ANSI_PATTERN,"");if(!this.fancy){let x=[];if(h)x.push(o);if(g==="warning")x.push("WARN");else if(g==="error")x.push("ERROR");else if(c)x.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)x.push(f.replace(/[[\]]/g,""));return x.push(u),x.join(" ")}let y=F.stdout.columns||120,b="";if(g==="warning"||g==="error")b=`${c} ${u}`;else if(g==="info"||g==="success")b=`${c} ${f} ${u}`;else b=`${c} ${f} ${N.cyan(u)}`;if(!h)return b.trim();let S=d(b).trim().length,v=d(o).length,k=Math.max(1,y-2-S-v);return`${b.trim()}${" ".repeat(k)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let o=i;return o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,f,u)=>{let g=N.underline(N.blue(f)),h=this.toAbsoluteFilePath(u);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let d=`file://${encodeURI(h)}`,y="\x1B]8;;",b="\x1B\\";return`\x1B]8;;${d}\x1B\\${g}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${g}\x1B]8;;\x1B\\`;return g}),o=o.replace(/`([^`]+)`/g,(c,f)=>N.bgGray(f)),o=o.replace(/\*\*([^*]+)\*\*/g,(c,f)=>N.bold(f)),o=o.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,f)=>N.italic(f)),o=o.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,f)=>N.italic(f)),o=o.replace(/~([^~]+)~/g,(c,f)=>N.strikethrough(f)),o}supportsHyperlinks(){if(q())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 o=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(o)&&o>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let o=i;if(o.startsWith("file://"))o=o.replace(/^file:\/\//,"");if(o.startsWith("~")){let c=F.env.HOME||"";if(c)o=o.replace(/^~(?=$|\/)/,c)}if(Bi(o)||o.startsWith("./")||o.startsWith("../"))o=ji(o);else return null;return ht(o)?o:null}catch{return null}}buildOutputTexts(i){let o=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:o,fileText:c}}async log(i,o,...c){if(!this.shouldLog(i))return;let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);let{consoleText:y,fileText:b}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let v=this.options.showIcons===!1?"":ta[i],k=this.options.showTags!==!1&&this.name?N.gray(this.formatTag(this.name)):"",x;switch(i){case"debug":x=this.formatConsoleMessage({timestamp:u,icon:v,tag:k,message:N.gray(y),level:i}),console.error(x);break;case"info":x=this.formatConsoleMessage({timestamp:u,icon:v,tag:k,message:y,level:i}),console.warn(x);break;case"success":x=this.formatConsoleMessage({timestamp:u,icon:v,tag:k,message:N.green(y),level:i}),console.error(x);break;case"warning":x=this.formatConsoleMessage({timestamp:u,icon:v,tag:k,message:y,level:i}),console.warn(x);break;case"error":if(x=this.formatConsoleMessage({timestamp:u,icon:v,tag:k,message:y,level:i}),console.error(x),d){let R=d.split(`
|
|
41
|
-
`);for(let
|
|
40
|
+
`}return{name:"bunfig-plugin",setup(u){u.onResolve({filter:/^virtual:bunfig-types$/},(g)=>({path:g.path,namespace:"bunfig-virtual"})),u.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:f(),loader:"ts"}))}}}var cs,Ie,Ge,ls,So,vo,Nn,bt,wr,Y,B,$o,Dn,Eo,Fn,Co,xo,lr,To,In,_n,fr,ko,Ao,Lo,Ro,St,fs,Oo,J,Po,No,Mn,vt,br,U,P,Do,Bn,Fo,jn,Io,_o,ur,Mo,Kn,Wn,Bo,hr,jo,Ko,Vo,Wo,Qo,$t,us,Uo,qo="0.15.6",re,Pt,He,Sr,vr,Nt,$r,Er,ze,Cr,xr,be,hs,gs,ce,pe,ds,ms,Ho=qi(async()=>{cs=import.meta.require,Ie=new Ar,Ge=new Lr,ls={createKey:Hi,isEquivalent:zi,estimateMemoryUsage:Gi},So=Tt(pr.cwd(),"config"),vo=Tt(pr.cwd(),"src/generated"),Nn=xt.env.CLARITY_LOG_DIR||li(Zi(),"logs"),bt={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Nn,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},wr=await Xi(),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`,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"},B=Y,$o=Y.red,Dn=Y.green,Eo=Y.yellow,Fn=Y.blue,Co=Y.magenta,xo=Y.cyan,lr=Y.white,To=Y.gray,In=Y.bgRed,_n=Y.bgYellow,fr=Y.bold,ko=Y.dim,Ao=Y.italic,Lo=Y.underline,Ro=Y.reset,St={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},fs={debug:"\uD83D\uDD0D",info:Fn("\u2139"),success:Dn("\u2713"),warning:_n(lr(fr(" WARN "))),error:In(lr(fr(" ERROR ")))},Oo=new Lt("stacks"),J=new Lt("bunfig",{showTags:!0}),Po=Z(Qe.cwd(),"config"),No=Z(Qe.cwd(),"src/generated"),Mn=Ct.env.CLARITY_LOG_DIR||ai(no(),"logs"),vt={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mn,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},br=await so(),U={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},P=U,Do=U.red,Bn=U.green,Fo=U.yellow,jn=U.blue,Io=U.magenta,_o=U.cyan,ur=U.white,Mo=U.gray,Kn=U.bgRed,Wn=U.bgYellow,Bo=U.bgGray,hr=U.bold,jo=U.dim,Ko=U.italic,Vo=U.underline,Wo=U.strikethrough,Qo=U.reset,$t={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},us={debug:"\uD83D\uDD0D",info:jn("\u2139"),success:Bn("\u2713"),warning:Wn(ur(hr(" WARN "))),error:Kn(ur(hr(" ERROR ")))},Uo=new Ot("stacks"),re=class extends Error{timestamp;context;constructor(o,c={}){super(o);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=c,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let o=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([c,f])=>`${c}: ${f}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${o}`}},Pt=class extends re{code="CONFIG_NOT_FOUND";constructor(o,c,f){let u=f?` or alias "${f}"`:"";super(`Configuration "${o}"${u} not found`,{configName:o,alias:f,searchPaths:c,searchPathCount:c.length})}},He=class extends re{code="CONFIG_LOAD_ERROR";constructor(o,c,f){super(`Failed to load configuration from "${o}": ${c.message}`,{configPath:o,configName:f,originalError:c.name,originalMessage:c.message});this.cause=c}},Sr=class extends re{code="CONFIG_VALIDATION_ERROR";constructor(o,c,f){super(`Configuration validation failed for "${o}"`,{configPath:o,configName:f,validationErrors:c,errorCount:c.length})}},vr=class extends re{code="CONFIG_MERGE_ERROR";constructor(o,c,f,u){super(`Failed to merge configuration from "${o}" with "${c}": ${f.message}`,{sourcePath:o,targetPath:c,configName:u,originalError:f.name,originalMessage:f.message});this.cause=f}},Nt=class extends re{code="ENV_VAR_ERROR";constructor(o,c,f,u){super(`Failed to parse environment variable "${o}" with value "${c}" as ${f}`,{envKey:o,envValue:c,expectedType:f,configName:u})}},$r=class extends re{code="FILE_SYSTEM_ERROR";constructor(o,c,f){super(`File system ${o} failed for "${c}": ${f.message}`,{operation:o,path:c,originalError:f.name,originalMessage:f.message});this.cause=f}},Er=class extends re{code="TYPE_GENERATION_ERROR";constructor(o,c,f){super(`Failed to generate types from "${o}" to "${c}": ${f.message}`,{configDir:o,outputPath:c,originalError:f.name,originalMessage:f.message});this.cause=f}},ze=class extends re{code="SCHEMA_VALIDATION_ERROR";constructor(o,c,f){super(`Schema validation failed${f?` for config "${f}"`:""}`,{schemaPath:o,configName:f,validationErrors:c,errorCount:c.length})}},Cr=class extends re{code="BROWSER_CONFIG_ERROR";constructor(o,c,f,u){super(`Failed to fetch configuration from "${o}": ${c} ${f}`,{endpoint:o,status:c,statusText:f,configName:u})}},xr=class extends re{code="PLUGIN_ERROR";constructor(o,c,f){super(`Plugin "${o}" failed during ${c}: ${f.message}`,{pluginName:o,operation:c,originalError:f.name,originalMessage:f.message});this.cause=f}},be={configNotFound(i,o,c){return new Pt(i,o,c)},configLoad(i,o,c){return new He(i,o,c)},configValidation(i,o,c){return new Sr(i,o,c)},configMerge(i,o,c,f){return new vr(i,o,c,f)},envVar(i,o,c,f){return new Nt(i,o,c,f)},fileSystem(i,o,c){return new $r(i,o,c)},typeGeneration(i,o,c){return new Er(i,o,c)},schemaValidation(i,o,c){return new ze(i,o,c)},browserConfig(i,o,c,f){return new Cr(i,o,c,f)},plugin(i,o,c){return new xr(i,o,c)}},hs={replace:"replace",concat:"concat",smart:"smart"},gs=/^https?:\/\//,ce=new Ot("bunfig",{showTags:!0}),pe=new Dr,ds=X(ve.cwd(),"config"),ms=X(ve.cwd(),"src/generated")});function zo(i,o={}){let c=kt.cwd();while(c.includes("storage"))c=xn(c,"..");let f=xn(c,i||"");if(o?.relative)return Pi(kt.cwd(),f);return f}var Go=kt.env.CLARITY_LOG_DIR||Oi(zo(),"logs"),ps={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Go,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Dt={...ps},rl=(async()=>{try{let{loadConfig:i}=await Ho().then(()=>Xn),o=await i({name:"clarity",alias:"logging",defaultConfig:ps,cwd:kt.cwd()});if(o)Object.assign(Dt,o)}catch{}return Dt})();function q(){if(me.env.NODE_ENV==="test"||me.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Yo(){if(me.env.NODE_ENV==="test"||me.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof me<"u"){let i=me.type;if(i==="renderer"||i==="worker")return!1;return!!(me.versions&&(me.versions.node||me.versions.bun))}return!1}class ys{async format(i){let o=await Yo(),c=await this.getMetadata(o);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:o}=await import("os");return{pid:De.pid,hostname:o(),environment:De.env.NODE_ENV||"development",platform:De.platform,version:De.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:De.env.NODE_ENV||De.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var H={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"},N=H,{red:nl,green:Jo,yellow:sl,blue:Zo,magenta:il,cyan:ol,white:Qn,gray:al,bgRed:Xo,bgYellow:ea,bgGray:cl,bold:Un,dim:ll,italic:fl,underline:ul,strikethrough:hl,reset:gl}=H,gr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ta={debug:"\uD83D\uDD0D",info:Zo("\u2139"),success:Jo("\u2713"),warning:ea(Qn(Un(" WARN "))),error:Xo(Qn(Un(" ERROR ")))};class jt{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,o={}){this.name=i,this.config={...Dt},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new ys,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??F.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let o={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return o[i]>=o[c]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...gr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...gr};return{...gr,...i.fingersCrossed}}normalizeOptions(i){let o={format:"json",level:"info",logDirectory:Dt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}shouldWriteToFile(){return!q()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await _i(this.config.logDirectory,Ln.F_OK|Ln.W_OK)}catch(b){if(b instanceof Error&&"code"in b)if(b.code==="ENOENT")await Mi(this.config.logDirectory,{recursive:!0,mode:493});else if(b.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw b;else throw b}}catch(b){throw console.error("Debug: [writeToFile] Failed to create log directory:",b),b}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:he.from(i);try{if(!ht(this.currentLogFile))await cr(this.currentLogFile,"",{mode:420});if(u=An(this.currentLogFile,"a",420),Ii(u,y,{flag:"a"}),kn(u),u!==void 0)ar(u),u=void 0;if((await Pe(this.currentLogFile)).size===0){if(await cr(this.currentLogFile,y,{flag:"w",mode:420}),(await Pe(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(b){let S=b;if(S.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(S.code)){if(g<h-1){let v=typeof S.message==="string"?S.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,v);let C=d*2**g;await new Promise((E)=>setTimeout(E,C)),g++;continue}}if(S?.code&&["ENOSPC","EDQUOT"].includes(S.code))throw Error(`Disk quota exceeded or no space left on device: ${S.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",S),S}finally{if(u!==void 0)try{ar(u)}catch(b){console.error("Debug: [writeToFile] Error closing file descriptor:",b)}}}catch(y){if(g===h-1){let S=y,v=typeof S.message==="string"?S.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",v),y}g++;let b=d*2**(g-1);await new Promise((S)=>setTimeout(S,b))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ne(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 Ne(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Ne(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(q())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,y])=>y.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return or(16).toString("hex")}generateKey(){return or(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:o}=this.getCurrentKey(),c=or(16),f=Ni("aes-256-gcm",o,c),u=he.isBuffer(i)?i:he.from(i,"utf8"),g=f.update(u),h=f.final(),d=g.length+h.length,y=f.getAuthTag(),b=he.allocUnsafe(16+d+16);return c.copy(b,0),g.copy(b,16),h.copy(b,16+g.length),y.copy(b,16+d),{encrypted:b,iv:c}}async compressData(i){return new Promise((o,c)=>{let f=On(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(he.from(he.concat(u)))),f.on("error",c),f.write(i),f.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(q())return;if(!this.shouldWriteToFile())return;let i=await Pe(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await gt(this.config.logDirectory),g=u.filter((y)=>y.startsWith(this.name)&&/\.log\.\d+$/.test(y)).sort((y,b)=>{let S=Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(b.match(/\.log\.(\d+)$/)?.[1]||"0")-S}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await Pe(c).catch(()=>null))try{if(await Rn(c,d),o.compress)try{let y=`${d}.gz`;await this.compressLogFile(d,y),await dt(d)}catch(y){console.error("Error compressing rotated file:",y)}if(g.length===0&&!u.some((y)=>y.endsWith(".log.1")))try{let y=`${c}.1`;await cr(y,"")}catch(y){console.error("Error creating backup file:",y)}}catch(y){console.error(`Error during rotation: ${y instanceof Error?y.message:String(y)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await Pe(c).catch(()=>null))await Rn(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await gt(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await dt(Ne(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=Tn(i),f=Fi(o),u=On();await Ki(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(f);console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(o);console.log(o)}}shouldLog(i){if(!this.enabled)return!1;let o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),ht(this.currentLogFile))try{let i=An(this.currentLogFile,"r+");kn(i),ar(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let o=(await gt(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await dt(Ne(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?N.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q())return!1;let i=typeof F.env.NO_COLOR<"u",o=F.env.FORCE_COLOR==="0";if(i||o)return!1;return!!(typeof F.stderr<"u"&&F.stderr.isTTY||typeof F.stdout<"u"&&F.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(E)=>E.replace(this.ANSI_PATTERN,"");if(!this.fancy){let E=[];if(h)E.push(o);if(g==="warning")E.push("WARN");else if(g==="error")E.push("ERROR");else if(c)E.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)E.push(f.replace(/[[\]]/g,""));return E.push(u),E.join(" ")}let y=F.stdout.columns||120,b="";if(g==="warning"||g==="error")b=`${c} ${u}`;else if(g==="info"||g==="success")b=`${c} ${f} ${u}`;else b=`${c} ${f} ${N.cyan(u)}`;if(!h)return b.trim();let S=d(b).trim().length,v=d(o).length,C=Math.max(1,y-2-S-v);return`${b.trim()}${" ".repeat(C)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let o=i;return o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,f,u)=>{let g=N.underline(N.blue(f)),h=this.toAbsoluteFilePath(u);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let d=`file://${encodeURI(h)}`,y="\x1B]8;;",b="\x1B\\";return`\x1B]8;;${d}\x1B\\${g}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${g}\x1B]8;;\x1B\\`;return g}),o=o.replace(/`([^`]+)`/g,(c,f)=>N.bgGray(f)),o=o.replace(/\*\*([^*]+)\*\*/g,(c,f)=>N.bold(f)),o=o.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,f)=>N.italic(f)),o=o.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,f)=>N.italic(f)),o=o.replace(/~([^~]+)~/g,(c,f)=>N.strikethrough(f)),o}supportsHyperlinks(){if(q())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 o=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(o)&&o>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let o=i;if(o.startsWith("file://"))o=o.replace(/^file:\/\//,"");if(o.startsWith("~")){let c=F.env.HOME||"";if(c)o=o.replace(/^~(?=$|\/)/,c)}if(Bi(o)||o.startsWith("./")||o.startsWith("../"))o=ji(o);else return null;return ht(o)?o:null}catch{return null}}buildOutputTexts(i){let o=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:o,fileText:c}}async log(i,o,...c){if(!this.shouldLog(i))return;let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);let{consoleText:y,fileText:b}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let v=this.options.showIcons===!1?"":ta[i],C=this.options.showTags!==!1&&this.name?N.gray(this.formatTag(this.name)):"",E;switch(i){case"debug":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:N.gray(y),level:i}),console.error(E);break;case"info":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.warn(E);break;case"success":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:N.green(y),level:i}),console.error(E);break;case"warning":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.warn(E);break;case"error":if(E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.error(E),d){let A=d.split(`
|
|
41
|
+
`);for(let k of A)if(k.trim()&&!k.includes(h))console.error(this.formatConsoleMessage({timestamp:u,message:N.gray(` ${k}`),level:i,showTimestamp:!1}))}break}}else if(!q()){if(console.error(`${g} ${this.environment}.${i.toUpperCase()}: ${h}`),d)console.error(d)}let S=`${g} ${this.environment}.${i.toUpperCase()}: ${b}
|
|
42
42
|
`;if(d)S+=`${d}
|
|
43
43
|
`;if(S=S.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(S)}progress(i,o=""){let c={update:(d,y)=>{},finish:(d)=>{},interrupt:(d,y)=>{}};if(!this.enabled)return c;let f=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:o||"",barLength:f,lastRenderedLine:""},this.shouldStyleConsole()&&!q()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(d,y)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,d),this.activeProgressBar.total),y!==void 0)this.activeProgressBar.message=y;if(this.shouldStyleConsole()&&!q()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(d)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,d)},interrupt:(d,y="info")=>{if(!q()&&F.stdout.isTTY)F.stdout.write(`
|
|
44
44
|
`);if(this[y==="warning"?"warn":y](d),this.activeProgressBar&&this.shouldStyleConsole()&&!q()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let o=performance.now();if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?N.gray(this.formatTag(this.name)):"",f=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:f,icon:this.options.showIcons===!1?"":N.blue("\u25D0"),tag:c,message:`${N.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let f=performance.now(),u=Math.round(f-o),g=`${i} completed in ${u}ms`,h=new Date,d=this.formatConsoleTimestamp(h),b=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${g}`;if(c)b+=` ${JSON.stringify(c)}`;if(b+=`
|
|
45
45
|
`,b=b.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let S=this.options.showTags!==!1&&this.name?N.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:this.options.showIcons===!1?"":N.green("\u2713"),tag:S,message:`${g}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!q())console.error(b.trim());if(this.shouldWriteToFile())await this.writeToFile(b)}}async debug(i,...o){await this.log("debug",i,...o)}async info(i,...o){await this.log("info",i,...o)}async success(i,...o){await this.log("success",i,...o)}async warn(i,...o){await this.log("warning",i,...o)}async error(i,...o){await this.log("error",i,...o)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:o}=i;return!!o}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let o=`${this.name}:${i}`,c=new jt(o,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(c),c}createReadStream(){if(q())throw Error("createReadStream is not supported in browser environments");if(!ht(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Tn(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let o=this.config.rotation;if(!o.encrypt||typeof o.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let c=this.keys.get(this.currentKeyId);try{let f=he.isBuffer(i)?i:he.from(i,"base64"),u=f.subarray(0,16),g=f.subarray(f.length-16),h=f.subarray(16,f.length-16),d=Di("aes-256-gcm",c,u);d.setAuthTag(g);let y=d.update(h),b=d.final(),S=y.length+b.length,v=he.allocUnsafe(S);return y.copy(v,0),b.copy(v,y.length),v.toString("utf8")}catch(f){throw Error(`Decryption failed: ${f instanceof Error?f.message:String(f)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return q()}isServerMode(){return!q()}setTestEncryptionKey(i,o){this.currentKeyId=i,this.keys.set(i,o)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let o=new Date,c=this.formatConsoleTimestamp(o),f=this.formatFileTimestamp(o),{consoleText:u,fileText:g}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let d=u.split(`
|
|
46
|
-
`),y=Math.max(...d.map((
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}async prompt(i){if(q())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${N.cyan("?")} ${i} (y/n) `);let c=(f)=>{let u=f.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(""),o(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,...o){if(!this.enabled)return;let c=i;if(o&&o.length>0){let y=/%([sdijfo%])/g,b=0;if(c=i.replace(y,(S,v)=>{if(v==="%")return"%";if(b>=o.length)return S;let
|
|
48
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}renderProgressBar(i,o=!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))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=N.green("\u2501".repeat(f)),h=N.gray("\u2501".repeat(u)),d=`[${g}${h}]`,y=`${c}%`.padStart(4),b=i.message?` ${i.message}`:"",S=this.options.showIcons===!1?"":o||c===100?N.green("\u2713"):N.blue("\u25B6"),v=this.options.showTags!==!1&&this.name?` ${N.gray(this.formatTag(this.name))}`:"",
|
|
46
|
+
`),y=Math.max(...d.map((C)=>C.length))+2,b=`\u250C${"\u2500".repeat(y)}\u2510`,S=`\u2514${"\u2500".repeat(y)}\u2518`,v=d.map((C)=>this.formatConsoleMessage({timestamp:c,message:N.cyan(C),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:N.cyan(b),showTimestamp:!1})),v.forEach((C)=>console.error(C)),console.error(this.formatConsoleMessage({timestamp:c,message:N.cyan(S),showTimestamp:!1}))}else if(!q())console.error(`${f} ${this.environment}.INFO: [BOX] ${g}`);let h=`${f} ${this.environment}.INFO: [BOX] ${g}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}async prompt(i){if(q())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${N.cyan("?")} ${i} (y/n) `);let c=(f)=>{let u=f.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(""),o(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,...o){if(!this.enabled)return;let c=i;if(o&&o.length>0){let y=/%([sdijfo%])/g,b=0;if(c=i.replace(y,(S,v)=>{if(v==="%")return"%";if(b>=o.length)return S;let C=o[b++];switch(v){case"s":return String(C);case"d":case"i":return Number(C).toString();case"j":case"o":return JSON.stringify(C,null,2);default:return S}}),b<o.length)c+=` ${o.slice(b).map((S)=>typeof S==="object"?JSON.stringify(S,null,2):String(S)).join(" ")}`}let{consoleText:f,fileText:u}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?N.gray(this.formatTag(this.name)):"",b=this.options.showIcons===!1?"":`${N.blue("\u25D0")} `;console.error(`${b}${y} ${N.cyan(f)}`)}let d=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${u}
|
|
48
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}renderProgressBar(i,o=!1){if(!this.enabled||!this.shouldStyleConsole()||!F.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=N.green("\u2501".repeat(f)),h=N.gray("\u2501".repeat(u)),d=`[${g}${h}]`,y=`${c}%`.padStart(4),b=i.message?` ${i.message}`:"",S=this.options.showIcons===!1?"":o||c===100?N.green("\u2713"):N.blue("\u25B6"),v=this.options.showTags!==!1&&this.name?` ${N.gray(this.formatTag(this.name))}`:"",C=`\r${S}${v} ${d} ${y}${b}`,E=F.stdout.columns||80,A=" ".repeat(Math.max(0,E-C.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${C}${A}`,F.stdout.write(i.lastRenderedLine),o)F.stdout.write(`
|
|
49
49
|
`)}finishProgressBar(i,o){if(!this.enabled||!this.fancy||q()||!F.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(o)i.message=o;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let o=await gt(this.config.logDirectory),c=[];for(let f of o){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(f):f.startsWith(this.name))||!f.endsWith(".log"))continue;let g=Ne(this.config.logDirectory,f);if(i.before)try{if((await Pe(g)).mtime>=i.before)continue}catch(h){console.error(`Failed to get stats for file ${g}:`,h);continue}c.push(g)}if(c.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${c.length} log file(s)...`);for(let f of c)try{await dt(f),console.warn(`Deleted log file: ${f}`)}catch(u){console.error(`Failed to delete log file ${f}:`,u)}console.warn("Log clearing process finished.")}catch(o){console.error("Error during log clearing process:",o)}}}var dl=new jt("stacks");class le extends Error{timestamp;context;constructor(i,o={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=o,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([o,c])=>`${o}: ${c}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class ws extends le{code="CONFIG_NOT_FOUND";constructor(i,o,c){let f=c===void 0?[]:Array.isArray(c)?c.filter(Boolean):[c],u="";if(f.length===1)u=` or alias "${f[0]}"`;else if(f.length>1)u=` or aliases ${f.map((g)=>`"${g}"`).join(", ")}`;super(`Configuration "${i}"${u} not found`,{configName:i,alias:c,searchPaths:o,searchPathCount:o.length})}}class Ft extends le{code="CONFIG_LOAD_ERROR";constructor(i,o,c){super(`Failed to load configuration from "${i}": ${o.message}`,{configPath:i,configName:c,originalError:o.name,originalMessage:o.message});this.cause=o}}class bs extends le{code="CONFIG_VALIDATION_ERROR";constructor(i,o,c){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:c,validationErrors:o,errorCount:o.length})}}class Ss extends le{code="CONFIG_MERGE_ERROR";constructor(i,o,c,f){super(`Failed to merge configuration from "${i}" with "${o}": ${c.message}`,{sourcePath:i,targetPath:o,configName:f,originalError:c.name,originalMessage:c.message});this.cause=c}}class Fr extends le{code="ENV_VAR_ERROR";constructor(i,o,c,f){super(`Failed to parse environment variable "${i}" with value "${o}" as ${c}`,{envKey:i,envValue:o,expectedType:c,configName:f})}}class vs extends le{code="FILE_SYSTEM_ERROR";constructor(i,o,c){super(`File system ${i} failed for "${o}": ${c.message}`,{operation:i,path:o,originalError:c.name,originalMessage:c.message});this.cause=c}}class $s extends le{code="TYPE_GENERATION_ERROR";constructor(i,o,c){super(`Failed to generate types from "${i}" to "${o}": ${c.message}`,{configDir:i,outputPath:o,originalError:c.name,originalMessage:c.message});this.cause=c}}class It extends le{code="SCHEMA_VALIDATION_ERROR";constructor(i,o,c){super(`Schema validation failed${c?` for config "${c}"`:""}`,{schemaPath:i,configName:c,validationErrors:o,errorCount:o.length})}}class Es extends le{code="BROWSER_CONFIG_ERROR";constructor(i,o,c,f){super(`Failed to fetch configuration from "${i}": ${o} ${c}`,{endpoint:i,status:o,statusText:c,configName:f})}}class Cs extends le{code="PLUGIN_ERROR";constructor(i,o,c){super(`Plugin "${i}" failed during ${o}: ${c.message}`,{pluginName:i,operation:o,originalError:c.name,originalMessage:c.message});this.cause=c}}var Se={configNotFound(i,o,c){return new ws(i,o,c)},configLoad(i,o,c){return new Ft(i,o,c)},configValidation(i,o,c){return new bs(i,o,c)},configMerge(i,o,c,f){return new Ss(i,o,c,f)},envVar(i,o,c,f){return new Fr(i,o,c,f)},fileSystem(i,o,c){return new vs(i,o,c)},typeGeneration(i,o,c){return new $s(i,o,c)},schemaValidation(i,o,c){return new It(i,o,c)},browserConfig(i,o,c,f){return new Es(i,o,c,f)},plugin(i,o,c){return new Cs(i,o,c)}};async function ra(i,o={}){let{maxRetries:c=3,retryDelay:f=1000,isRetryable:u=()=>!0,fallback:g}=o,h=Error("Unknown error occurred");for(let d=0;d<=c;d++)try{return await i()}catch(y){if(h=y instanceof Error?y:Error(String(y)),d===c||!u(h))break;if(f>0)await new Promise((b)=>setTimeout(b,f))}if(g!==void 0)return g;throw h instanceof Error?h:Error(`Unknown error: ${String(h)}`)}class Ir{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,o)=>o==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let o=i.toLowerCase();return["true","1","yes"].includes(o)}},{name:"number",canParse:(i,o)=>o==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let o=Number(i);if(Number.isNaN(o))throw TypeError(`Cannot parse "${i}" as number`);return o}},{name:"array",canParse:(i,o)=>o==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let o=JSON.parse(i);if(Array.isArray(o))return o}catch{}return i.split(",").map((o)=>o.trim())}},{name:"json",canParse:(i,o)=>o==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(o){throw Error(`Cannot parse "${i}" as JSON: ${o}`)}}}]}async applyEnvironmentVariables(i,o,c={}){let{prefix:f,useCamelCase:u=!0,useBackwardCompatibility:g=!0,customParsers:h={},verbose:d=!1,trackPerformance:y=!0}=c,b=async()=>{if(!i)return{config:o,source:{type:"environment",priority:50,timestamp:new Date}};let S=f||this.generateEnvPrefix(i),v={...o};return this.processObject(v,[],S,{useCamelCase:u,useBackwardCompatibility:g,customParsers:h,verbose:d,configName:i}),{config:v,source:{type:"environment",priority:50,timestamp:new Date}}};if(y)return kr.track("applyEnvironmentVariables",b,{configName:i});return b()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,o){if(!o)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=h.map((S)=>this.formatEnvKey(S,f.useCamelCase)),y=`${c}_${d.join("_")}`,b=f.useBackwardCompatibility?`${c}_${h.map((S)=>S.toUpperCase()).join("_")}`:null;if(f.verbose);if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.processObject(g,h,c,f);else{let S=pt.env[y]||(b?pt.env[b]:void 0);if(S!==void 0){if(f.verbose){let v=pt.env[y]?y:b}try{i[u]=this.parseEnvironmentValue(S,typeof g,y,f.customParsers,f.configName)}catch(v){if(v instanceof Fr)throw v;throw Se.envVar(y,S,typeof g,f.configName)}}}}}parseEnvironmentValue(i,o,c,f,u){for(let[g,h]of Object.entries(f))try{return h(i)}catch{continue}for(let g of this.defaultParsers)if(g.canParse(i,o))try{return g.parse(i)}catch{throw Se.envVar(c,i,`${o} (via ${g.name} parser)`,u)}return i}getEnvironmentVariables(i){let o={},c=i.toUpperCase();for(let[f,u]of Object.entries(pt.env))if(f.startsWith(c)&&u!==void 0)o[f]=u;return o}validateEnvironmentVariable(i,o,c){let f=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))f.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(c)try{this.parseEnvironmentValue(i,o,c,{})}catch(u){f.push(`Cannot parse value "${o}" as ${c}: ${u}`)}return{isValid:f.length===0,errors:f}}generateEnvVarDocs(i,o,c={}){let{prefix:f,format:u="text"}=c,g=f||this.generateEnvPrefix(i),h=[];switch(this.extractEnvVarInfo(o,[],g,h),u){case"markdown":return this.formatAsMarkdown(h,i);case"json":return JSON.stringify(h,null,2);default:return this.formatAsText(h,i)}}extractEnvVarInfo(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=`${c}_${h.map((y)=>this.formatEnvKey(y,!0)).join("_")}`;if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.extractEnvVarInfo(g,h,c,f);else f.push({key:d,type:Array.isArray(g)?"array":typeof g,description:`Configuration for ${h.join(".")}`,example:this.generateExample(g)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,o){let c=`Environment Variables for ${o}:
|
|
50
50
|
|
|
51
51
|
`;for(let f of i)c+=`${f.key}
|
|
@@ -58,10 +58,10 @@ export type ConfigOf = Config
|
|
|
58
58
|
`;c+=`| Variable | Type | Description | Example |
|
|
59
59
|
`,c+=`|----------|------|-------------|----------|
|
|
60
60
|
`;for(let f of i)c+=`| \`${f.key}\` | ${f.type} | ${f.description} | \`${f.example}\` |
|
|
61
|
-
`;return c}}function na(i,o,c={}){return xs(i,o,c,new WeakMap)}function xs(i,o,c,f){let{arrayMergeMode:u="replace",skipNullish:g=!1,customMerger:h}=c;if(o===null||o===void 0)return g?i:o;if(h){let d=h(i,o);if(d!==void 0)return d}if(Array.isArray(o)||Array.isArray(i))return Ts(i,o,u,f);if(!se(o)||!se(i))return o;return aa(i,o,c,f)}function Ts(i,o,c,f){if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(i)&&!Array.isArray(o))return o;if(Array.isArray(o)&&Array.isArray(i))switch(c){case"replace":return o;case"concat":return sa(i,o);case"smart":return ia(i,o,f);default:return o}return o}function sa(i,o){let c=[...o];for(let f of i)if(!c.some((u)=>Tr(u,f)))c.push(f);return c}function ia(i,o,c){if(o.length===0)return i;if(i.length===0)return o;if(se(o[0])&&se(i[0]))return oa(i,o,c);if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}function oa(i,o,c){let f=[...o];for(let u of i){if(!se(u)){f.push(u);continue}let g=["id","name","key","path","type"],h=!1;for(let d of g)if(d in u){if(f.find((b)=>se(b)&&(d in b)&&b[d]===u[d])){h=!0;break}}if(!h)f.push(u)}return f}function aa(i,o,c,f){let u=o;if(se(u)&&f.has(u))return f.get(u);let g={...i};if(se(u))f.set(u,g);for(let h in u){if(!Object.prototype.hasOwnProperty.call(u,h))continue;let d=u[h],y=g[h];if(c.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){g[h]=d;continue}if(se(d)&&se(y))g[h]=xs(y,d,c,f);else if(Array.isArray(d)||Array.isArray(y))g[h]=Ts(y,d,c.arrayMergeMode||"smart",f);else g[h]=d}return g}function ks(i,o,c="replace"){return na(i,o,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function Tr(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!Tr(i[c],o[c]))return!1;return!0}if(se(i)&&se(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!Tr(i[u],o[u]))return!1}return!0}return!1}function se(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class As{extensions=Gn;async loadFromPath(i,o,c={}){let{arrayStrategy:f="replace",useCache:u=!0,cacheTtl:g,trackPerformance:h=!0,verbose:d=!1}=c;if(u){let b=Et.getWithFileCheck("file",i);if(b){if(d)console.log(`Configuration loaded from cache: ${i}`);return b}}let y=async()=>{if(!yt(i))return null;try{let b=`?t=${Date.now()}`,S=await import(i+b),v=S.default||S,k="default"in S,x=Object.keys(S).length>0;if(!k&&!x)throw new Ft(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof v!=="object"||v===null||Array.isArray(v))throw new Ft(i,Error("Configuration must export a valid object"),"unknown");let O={config:ks(o,v,f),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)Et.setWithFileCheck("file",O,i,g);return O}catch(b){throw b instanceof Error?Se.configLoad(i,b):Se.configLoad(i,Error(String(b)))}};if(h)return kr.track("loadFromPath",y,{path:i});return y()}async tryLoadFromPaths(i,o,c={}){for(let f of i)try{let u=await this.loadFromPath(f,o,c);if(u)return u}catch(u){if(u instanceof Error&&u.name==="ConfigLoadError")throw u;if(c.verbose)console.warn(`Failed to load config from ${f}:`,u)}return null}generateConfigPaths(i,o,c){return ei({name:i,directory:o,alias:c})}generateNamePatterns(i,o){return Yn({name:i,alias:o})}checkFileAccess(i){return ra(async()=>yt(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,o,c){let f=[];if(!yt(i))return f;if(o||c){let u=this.generateNamePatterns(o||"",c);for(let g of u)for(let h of this.extensions){let d=qn(i,`${g}${h}`);if(await this.checkFileAccess(d))f.push(d)}}else try{let{readdirSync:u}=await import("fs"),g=u(i);for(let h of g)if(this.looksLikeConfigFile(h)){let d=qn(i,h);if(await this.checkFileAccess(d))f.push(d)}}catch{return[]}return f}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((c)=>c.test(i))}async validateConfigFile(i){let o=[];try{if(!yt(i))return o.push("Configuration file does not exist"),o;let c=await import(i),f=c.default||c;if(f===void 0)o.push("Configuration file must export a default value or named exports");else if(typeof f!=="object"||f===null)o.push("Configuration must be an object");else if(Array.isArray(f))o.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),g=u(i,"utf8");JSON.parse(g)}catch(u){o.push(`Invalid JSON syntax: ${u}`)}}catch(c){o.push(`Failed to load configuration file: ${c}`)}return o}async getFileModificationTime(i){try{let{statSync:o}=await import("fs");return o(i).mtime}catch{return null}}async preloadConfigurations(i,o={}){let c=new Map;return await Promise.allSettled(i.map(async(f)=>{try{let u=await this.loadFromPath(f,{},o);if(u)c.set(f,u.config)}catch(u){if(o.verbose)console.warn(`Failed to preload ${f}:`,u)}})),c}}var la=/^https?:\/\//;class Ls{async validateConfiguration(i,o,c={}){let{stopOnFirstError:f=!1,validateRequired:u=!0,validateTypes:g=!0,customRules:h=[],trackPerformance:d=!0,verbose:y=!1}=c,b=async()=>{let S=[],v=[],k={stopOnFirstError:f,validateRequired:u,validateTypes:g,customRules:h,trackPerformance:d,verbose:y};try{if(typeof o==="string")return await this.validateWithSchemaFile(i,o,k);else if(Array.isArray(o))return this.validateWithRules(i,[...o,...h],k);else return this.validateWithJSONSchema(i,o,k)}catch(x){return S.push({path:"",message:`Validation failed: ${x}`,rule:"system"}),{isValid:!1,errors:S,warnings:v}}};if(d)return await kr.track("validateConfiguration",b);return b()}async validateWithSchemaFile(i,o,c){try{if(!ca(o))throw new It(o,[{path:"",message:"Schema file does not exist"}]);let f=await import(o),u=f.default||f;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(f){throw new It(o,[{path:"",message:`Failed to load schema: ${f}`}])}}validateWithJSONSchema(i,o,c){let f=[],u=[];return this.validateObjectAgainstSchema(i,o,"",f,u,c),{isValid:f.length===0,errors:f,warnings:u}}validateObjectAgainstSchema(i,o,c,f,u,g){if(g.validateTypes&&o.type){let h=Array.isArray(i)?"array":typeof i,d=Array.isArray(o.type)?o.type:[o.type];if(!d.includes(h)){if(f.push({path:c,message:`Expected type ${d.join(" or ")}, got ${h}`,expected:d.join(" or "),actual:h,rule:"type"}),g.stopOnFirstError)return}}if(o.enum&&!o.enum.includes(i)){if(f.push({path:c,message:`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"}),g.stopOnFirstError)return}if(typeof i==="string"){if(o.minLength!==void 0&&i.length<o.minLength)f.push({path:c,message:`String length must be at least ${o.minLength}`,expected:`>= ${o.minLength}`,actual:i.length,rule:"minLength"});if(o.maxLength!==void 0&&i.length>o.maxLength)f.push({path:c,message:`String length must not exceed ${o.maxLength}`,expected:`<= ${o.maxLength}`,actual:i.length,rule:"maxLength"});if(o.pattern){if(!new RegExp(o.pattern).test(i))f.push({path:c,message:`String does not match pattern ${o.pattern}`,expected:o.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(o.minimum!==void 0&&i<o.minimum)f.push({path:c,message:`Value must be at least ${o.minimum}`,expected:`>= ${o.minimum}`,actual:i,rule:"minimum"});if(o.maximum!==void 0&&i>o.maximum)f.push({path:c,message:`Value must not exceed ${o.maximum}`,expected:`<= ${o.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&o.items)for(let h=0;h<i.length;h++){let d=c?`${c}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema(i[h],o.items,d,f,u,g),g.stopOnFirstError&&f.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let h=i;if(g.validateRequired&&o.required){for(let d of o.required)if(!(d in h)){if(f.push({path:c?`${c}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),g.stopOnFirstError)return}}if(o.properties){for(let[d,y]of Object.entries(o.properties))if(d in h){let b=c?`${c}.${d}`:d;if(this.validateObjectAgainstSchema(h[d],y,b,f,u,g),g.stopOnFirstError&&f.length>0)return}}if(o.additionalProperties===!1){let d=new Set(Object.keys(o.properties||{}));for(let y of Object.keys(h))if(!d.has(y))u.push({path:c?`${c}.${y}`:y,message:`Additional property '${y}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,o,c){let f=[],u=[];for(let g of o)try{let h=this.getValueByPath(i,g.path),d=this.validateWithRule(h,g,g.path);if(f.push(...d),c.stopOnFirstError&&f.length>0)break}catch(h){f.push({path:g.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:f.length===0,errors:f,warnings:u}}validateWithRule(i,o,c){let f=[];if(o.required&&(i===void 0||i===null))return f.push({path:c,message:o.message||`Property '${c}' is required`,expected:"required",rule:"required"}),f;if(i===void 0||i===null)return f;if(o.type){let u=Array.isArray(i)?"array":typeof i;if(u!==o.type)f.push({path:c,message:o.message||`Expected type ${o.type}, got ${u}`,expected:o.type,actual:u,rule:"type"})}if(o.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<o.min)f.push({path:c,message:o.message||`Value must be at least ${o.min}`,expected:`>= ${o.min}`,actual:u,rule:"min"})}if(o.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>o.max)f.push({path:c,message:o.message||`Value must not exceed ${o.max}`,expected:`<= ${o.max}`,actual:u,rule:"max"})}if(o.pattern&&typeof i==="string"){if(!o.pattern.test(i))f.push({path:c,message:o.message||`Value does not match pattern ${o.pattern}`,expected:o.pattern.toString(),actual:i,rule:"pattern"})}if(o.enum&&!o.enum.includes(i))f.push({path:c,message:o.message||`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"});if(o.validator){let u=o.validator(i);if(u)f.push({path:c,message:o.message||u,rule:"custom"})}return f}getValueByPath(i,o){if(!o)return i;let c=o.split("."),f=i;for(let u of c)if(f&&typeof f==="object"&&u in f)f=f[u];else return;return f}generateRulesFromInterface(i){let o=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let f of c){let[,u,g,h]=f;o.push({path:u,required:!g,type:this.mapTypeScriptType(h)})}return o}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:la},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ae=new jt("bunfig",{showTags:!0});function fa(i){if(!i)return"";let o=Array.isArray(i)?i.filter(Boolean):[i];if(o.length===0)return"";if(o.length===1)return` or alias "${o[0]}"`;return` or aliases ${o.map((c)=>`"${c}"`).join(", ")}`}class Rs{fileLoader=new As;envProcessor=new Ir;validator=new Ls;async loadConfig(i){let o=Date.now(),{cache:c,performance:f,schema:u,validate:g,...h}=i;try{if(c?.enabled){let y=this.checkCache(h.name||"",h);if(y)return y}let d;try{d=await this.loadConfigurationStrategies(h,!0,c)}catch(y){if(h.configFile)throw y;let b=h.__strictErrorHandling;if(y instanceof Error&&y.name==="ConfigNotFoundError"){if(b)throw y;d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(y instanceof Error&&y.name==="ConfigLoadError"){let S=y.message.includes("EACCES")||y.message.includes("EPERM")||y.message.includes("permission denied"),v=!S&&(y.message.includes("syntax")||y.message.includes("Expected")||y.message.includes("Unexpected")||y.message.includes("BuildMessage")||y.message.includes("errors building")),k=y.message.includes("Configuration must export a valid object")||y.message.includes("Configuration file is empty and exports nothing");if(b&&(k||S))throw y;if(v&&(!b||!k))d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!b)d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${y.message}`]};else throw y}else d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${y instanceof Error?y.message:String(y)}`]}}if(u||g)await this.validateConfiguration(d.config,u,g,h.name);if(c?.enabled&&d)this.cacheResult(h.name||"",d,c,h);if(f?.enabled){let y={operation:"loadConfig",duration:Date.now()-o,configName:h.name,timestamp:new Date};if(f.onMetrics)f.onMetrics(y);if(f.slowThreshold&&y.duration>f.slowThreshold)ae.warn(`Slow configuration loading detected: ${y.duration}ms for ${h.name}`);d.metrics=y}return d}catch(d){if(d instanceof Error&&d.name==="ConfigNotFoundError")throw d;let y=Date.now()-o;throw ae.error(`Configuration loading failed after ${y}ms:`,[d instanceof Error?d:Error(String(d))]),d}}async loadConfigurationStrategies(i,o=!1,c){let{name:f="",alias:u,configFile:g,cwd:h,configDir:d,defaultConfig:y,checkEnv:b=!0,arrayStrategy:S="replace",verbose:v=!1}=i,k=h||_t.cwd(),x=[];if(g){let W=fe(k,g);x.push(W);let ie=b?Me(f,y,v):y,te=await this.fileLoader.tryLoadFromPaths([W],ie,{arrayStrategy:S,verbose:v,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(!te)throw Se.configNotFound(f||g,x,u);if(v)ae.success(`Configuration loaded from explicit path: ${W}`);return this.finalizeResult(te,x,b,f,v)}let R=await this.loadLocalConfiguration(f,u,k,d,y,S,v,b,c);if(R)return x.push(...this.getLocalSearchPaths(f,u,k,d)),this.finalizeResult(R,x,b,f,v);let A=await this.loadHomeConfiguration(f,u,y,S,v,b);if(A)return x.push(...this.getHomeSearchPaths(f,u)),this.finalizeResult(A,x,b,f,v);let O=await this.loadPackageJsonConfiguration(f,u,k,y,S,v,b);if(O)return x.push(fe(k,"package.json")),this.finalizeResult(O,x,b,f,v);if(x.push(...this.getAllSearchPaths(f,u,k,d)),o)throw Se.configNotFound(f,x,u);return{...await this.applyEnvironmentVariables(f,y,b,v),warnings:[`No configuration file found for "${f}"${fa(u)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,o,c,f,u,g,h,d,y){let b=d?Me(i,u,h):u,S=this.getLocalDirectories(c,f);for(let v of S){if(h)ae.info(`Searching for configuration in: ${v}`);let k=this.fileLoader.generateConfigPaths(i,v,o),x=await this.fileLoader.tryLoadFromPaths(k,b,{arrayStrategy:g,verbose:h,cacheTtl:y?.ttl,useCache:!y?.ttl||y.ttl>100});if(x){if(h)ae.success(`Configuration loaded from: ${x.source.path}`);return x}}return null}async loadHomeConfiguration(i,o,c,f,u,g){if(!i)return null;let h=g?Me(i,c,u):c,d=[fe(Ee(),".config",i),fe(Ee(),".config"),Ee()];for(let y of d){if(u)ae.info(`Checking home directory: ${y}`);let b=this.fileLoader.generateConfigPaths(i,y,o),S=await this.fileLoader.tryLoadFromPaths(b,h,{arrayStrategy:f,verbose:u});if(S){if(u)ae.success(`Configuration loaded from home directory: ${S.source.path}`);return S}}return null}async loadPackageJsonConfiguration(i,o,c,f,u,g,h){let d=h?Me(i,f,g):f;try{let y=fe(c,"package.json");if(!ri(y))return null;let b={};try{b=JSON.parse(ni(y,"utf8"))}catch(k){if(g)ae.warn("Failed to parse package.json:",[k instanceof Error?k:Error(String(k))]);return null}let S=b[i],v=i;if(!S&&o){let k=Array.isArray(o)?o:[o];for(let x of k){if(!x)continue;if(b[x]){S=b[x],v=x;break}}}if(S&&typeof S==="object"&&!Array.isArray(S)){if(g)ae.success(`Configuration loaded from package.json: ${v}`);return{config:ks(d,S,u),source:{type:"package.json",path:y,priority:30,timestamp:new Date}}}}catch(y){if(g)ae.warn("Failed to load package.json:",[y instanceof Error?y:Error(String(y))])}return null}async applyEnvironmentVariables(i,o,c,f){if(!c||!i||typeof o!=="object"||o===null||Array.isArray(o))return{config:o,source:{type:"default",priority:10,timestamp:new Date}};return{config:Me(i,o,f),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,o,c,f,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,o,c,f){let u=[];if(c){let g=c(i);if(g)u.push(...g)}if(o){let g=await this.validator.validateConfiguration(i,o);if(!g.isValid)u.push(...g.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(u.length>0)throw Se.configValidation(f||"unknown",u,f)}checkCache(i,o){let c=this.generateCacheKey(i,o);return Et.get(c)||null}cacheResult(i,o,c,f){let u=this.generateCacheKey(i,f);Et.set(u,o,void 0,c.ttl)}generateCacheKey(i,o){let c=[i];if(o.alias){let f=Array.isArray(o.alias)?o.alias.join(","):o.alias;c.push(`alias:${f}`)}if(o.cwd)c.push(`cwd:${o.cwd}`);if(o.configFile)c.push(`configFile:${o.configFile}`);if(o.configDir)c.push(`configDir:${o.configDir}`);if("checkEnv"in o)c.push(`checkEnv:${o.checkEnv}`);return c.join("|")}getLocalDirectories(i,o){return ti({cwd:i,configDir:o})}getAllSearchPaths(i,o,c,f){let u=[];return u.push(...this.getLocalSearchPaths(i,o,c,f)),u.push(...this.getHomeSearchPaths(i,o)),u.push(fe(c,"package.json")),u}getLocalSearchPaths(i,o,c,f){let u=this.getLocalDirectories(c,f),g=[];for(let h of u)g.push(...this.fileLoader.generateConfigPaths(i,h,o));return g}getHomeSearchPaths(i,o){if(!i)return[];let c=[fe(Ee(),".config",i),fe(Ee(),".config"),Ee()],f=[];for(let u of c)f.push(...this.fileLoader.generateConfigPaths(i,u,o));return f}async loadConfigWithResult(i){return this.loadConfig(i)}}var dr=new Rs;async function Os(i){let o="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let f;if(c)f=await dr.loadConfig(i);else f=await dr.loadConfig({...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}});return f?.config??o}catch(f){if(i.configFile)throw f;let u=f instanceof Error?f.name:"UnknownError",g=f instanceof Error?f.message:String(f);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||g.includes("config"))&&i.verbose)ae.warn("Unexpected error loading config, using defaults:",[f instanceof Error?f:Error(String(f))]);let d=c?{...i,defaultConfig:o}:{...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await dr.applyEnvironmentVariables(d.name||"",o,!0,d.verbose||!1))?.config??o;return o}}function Me(i,o,c=!1){let f=new Ir,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function g(h,d=[]){let y={...h};for(let[b,S]of Object.entries(h)){let v=[...d,b],k=[`${u}_${v.join("_").toUpperCase()}`,`${u}_${v.map((A)=>A.toUpperCase()).join("")}`,`${u}_${v.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],x,R;for(let A of k)if(x=_t.env[A],x!==void 0){R=A;break}if(x!==void 0&&R)if(typeof S==="boolean")y[b]=["true","1","yes"].includes(x.toLowerCase());else if(typeof S==="number"){let A=Number(x);if(!Number.isNaN(A))y[b]=A}else if(Array.isArray(S))try{y[b]=JSON.parse(x)}catch{y[b]=x.split(",").map((A)=>A.trim())}else y[b]=x;else if(S&&typeof S==="object"&&!Array.isArray(S))y[b]=g(S,v)}return y}return g(o)}var bl=fe(_t.cwd(),"config"),Sl=fe(_t.cwd(),"src/generated");function n(i=e.dialect){return i==="mysql"||i==="singlestore"||i==="vitess"}var it={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}},Fs=new Set(["__proto__","constructor","prototype"]);function Ns(i){if(i===null||typeof i!=="object"||Array.isArray(i))return!1;let o=Object.getPrototypeOf(i);return o===Object.prototype||o===null}function _r(i,o,c=new Set){let f={...i};c.add(o);for(let u of Object.keys(o)){if(Fs.has(u))continue;let g=o[u];if(Ns(g)&&!c.has(g)){let h=f[u];f[u]=_r(Ns(h)?h:{},g,c)}else f[u]=g}return c.delete(o),f}var ua=Symbol.for("bun-query-builder.config"),e=globalThis[ua]??=_r({},it),ha=Symbol.for("bun-query-builder.config-state"),Kt=globalThis[ha]??={explicit:new Set,fileLoaded:!1};function _(i){if(i)return st(i);let o=Ps.env.DB_DIALECT||Ps.env.DB_CONNECTION;if(o)return st(o);return e.dialect||"postgres"}function st(i){let o=i.trim().toLowerCase();if(o==="turso"||o==="libsql")return"sqlite";return o}function t(i){if(e.dialect==="postgres")return`$${i}`;return"?"}function s(i,o=1){if(i<=0)return"";if(e.dialect==="postgres"){let c=`$${o}`;for(let f=1;f<i;f++)c+=`, $${o+f}`;return c}return i===1?"?":`?${", ?".repeat(i-1)}`}async function I(){if(!Kt.fileLoaded){Kt.fileLoaded=!0;let i=await Os({name:"query-builder",alias:"qb",defaultConfig:it}),o={};for(let[c,f]of Object.entries(i??{}))if(!Kt.explicit.has(c))o[c]=f;Is(o)}return e}var Ye=null,Ds=new Set;function Is(i){let o=_r(e,i),c=e;for(let f of Object.keys(o)){if(Fs.has(f))continue;c[f]=o[f]}}function Le(i){if(i.dialect&&Ye&&i.dialect!==Ye){let o=`${Ye}->${i.dialect}`;if(!Ds.has(o))Ds.add(o),console.warn(`[query-builder] Configuring dialect '${i.dialect}' overrides the previously configured dialect '${Ye}'. 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)Ye=i.dialect;for(let o of Object.keys(i))Kt.explicit.add(o);Is(i)}function mn(i){return i}function at(i){return typeof i==="string"&&/^(?:libsql|https?|wss?):\/\//i.test(i.trim())}function hn(i){let o;try{o=new URL(i.trim())}catch{throw new a("Invalid libSQL URL: expected libsql://, https://, http://, ws:// or wss://",{code:"LIBSQL_INVALID_URL"})}let c=o.protocol.replace(/:$/,"").toLowerCase(),f=o.searchParams.get("tls"),u=f==="0"||f==="false",g=o.searchParams.get("authToken")??void 0,h;switch(c){case"libsql":h=u?"http":"https";break;case"https":case"wss":h="https";break;case"http":case"ws":h="http";break;default:throw new a(`Unsupported libSQL URL scheme '${c}:'`,{code:"LIBSQL_INVALID_URL"})}if(o.username||o.password)throw new a("libSQL URLs must not embed credentials; pass the token as authToken",{code:"LIBSQL_INVALID_URL"});let d=o.pathname.replace(/\/+$/,"");return{baseUrl:`${h}://${o.host}${d}`,authToken:g||void 0}}var ga=[[/^UNIQUE constraint failed/i,"SQLITE_CONSTRAINT_UNIQUE",2067],[/^NOT NULL constraint failed/i,"SQLITE_CONSTRAINT_NOTNULL",1299],[/^FOREIGN KEY constraint failed/i,"SQLITE_CONSTRAINT_FOREIGNKEY",787],[/^CHECK constraint failed/i,"SQLITE_CONSTRAINT_CHECK",275]],_s={SQLITE_ERROR:1,SQLITE_INTERNAL:2,SQLITE_PERM:3,SQLITE_ABORT:4,SQLITE_BUSY:5,SQLITE_LOCKED:6,SQLITE_NOMEM:7,SQLITE_READONLY:8,SQLITE_INTERRUPT:9,SQLITE_IOERR:10,SQLITE_CORRUPT:11,SQLITE_FULL:13,SQLITE_CANTOPEN:14,SQLITE_SCHEMA:17,SQLITE_TOOBIG:18,SQLITE_CONSTRAINT:19,SQLITE_MISMATCH:20,SQLITE_MISUSE:21,SQLITE_RANGE:25};class a extends Error{code;errno;libsqlCode;status;constructor(i,o){super(i,o.cause===void 0?void 0:{cause:o.cause});this.name="LibSQLError",this.code=o.code,this.errno=o.errno,this.libsqlCode=o.libsqlCode,this.status=o.status}}function Ke(i){let c=String(i.message??"libSQL statement failed").replace(/^SQLite error:\s*/i,""),f=i.code??void 0;for(let[u,g,h]of ga)if(u.test(c))return new a(c,{code:g,errno:h,libsqlCode:f});if(f&&f in _s)return new a(c,{code:f,errno:_s[f],libsqlCode:f});if(f==="SQL_PARSE_ERROR"||f==="SQL_INPUT_ERROR")return new a(c,{code:"SQLITE_ERROR",errno:1,libsqlCode:f});return new a(c,{code:f??"LIBSQL_ERROR",libsqlCode:f})}var da=-(2n**63n),ma=2n**63n-1n;function Mr(i){return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function Wt(i){if(i===null||i===void 0)return{type:"null"};switch(typeof i){case"string":return{type:"text",value:i};case"boolean":return{type:"integer",value:i?"1":"0"};case"number":if(!Number.isFinite(i))throw RangeError(`Cannot bind ${i} to a libSQL statement: only finite numbers are allowed`);return Number.isSafeInteger(i)?{type:"integer",value:String(i===0?0:i)}:{type:"float",value:i};case"bigint":if(i<da||i>ma)throw RangeError(`Cannot bind ${i} to a libSQL statement: it does not fit in a 64-bit integer`);return{type:"integer",value:i.toString()}}if(i instanceof Date){if(Number.isNaN(i.getTime()))throw RangeError("Cannot bind an invalid Date to a libSQL statement");return{type:"text",value:i.toISOString()}}if(i instanceof Uint8Array)return{type:"blob",base64:Mr(i)};if(i instanceof ArrayBuffer)return{type:"blob",base64:Mr(new Uint8Array(i))};if(ArrayBuffer.isView(i))return{type:"blob",base64:Mr(new Uint8Array(i.buffer,i.byteOffset,i.byteLength))};throw TypeError(`Cannot bind a value of type ${Object.prototype.toString.call(i).slice(8,-1)} to a libSQL statement; serialize it first (e.g. JSON.stringify)`)}function Ut(i,o="bigint"){switch(i.type){case"null":return null;case"integer":{let c=Number(i.value);if(Number.isSafeInteger(c))return c;return o==="string"?i.value:BigInt(i.value)}case"float":return typeof i.value==="number"?i.value:Number(i.value);case"text":return i.value;case"blob":{let c=Buffer.from(i.base64??"","base64");return new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}default:throw new a(`Unknown libSQL value type '${i.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"})}}function gn(i,o="bigint"){let c=i.cols.map((d,y)=>d.name??String(y)),f=i.rows.map((d)=>{let y={};for(let b=0;b<c.length;b++)y[c[b]]=Ut(d[b]??{type:"null"},o);return y}),u=Number(i.affected_row_count??0),g=i.last_insert_rowid==null?null:Ut({type:"integer",value:i.last_insert_rowid},o),h=(d)=>({value:d,enumerable:!1,writable:!0,configurable:!0});return Object.defineProperties(f,{changes:h(u),count:h(u>0?u:f.length),lastInsertRowid:h(g),columns:h(c)}),f}function Fe(i,o=[]){if(!Array.isArray(o)){let f=Object.entries(o).map(([u,g])=>({name:/^[:@$]/.test(u)?u:`:${u}`,value:Wt(g)}));return{sql:i,named_args:f,want_rows:!0}}let c=qt(i,[...o]);return{sql:c.sql,args:c.params.map(Wt),want_rows:!0}}var pa=/^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i,ya=/^\s*PRAGMA\s+(?:main\.)?foreign_keys\s*(?:=\s*|\(\s*)['"]?(\w+)['"]?\s*\)?\s*;?\s*$/i;function wa(i){let o=ya.exec(i);return o?o[1].toUpperCase():null}class js{baseUrl;authToken;timeoutMs;fetchImpl;constructor(i){let o=hn(i.url);this.baseUrl=o.baseUrl,this.authToken=i.authToken||o.authToken,this.timeoutMs=i.timeoutMs,this.fetchImpl=i.fetch??fetch}async pipeline(i,o,c){let f={"content-type":"application/json"};if(this.authToken)f.authorization=`Bearer ${this.authToken}`;let u;try{u=await this.fetchImpl(`${i}/v3/pipeline`,{method:"POST",headers:f,body:JSON.stringify({baton:o,requests:c}),signal:this.timeoutMs?AbortSignal.timeout(this.timeoutMs):void 0})}catch(h){let d=h instanceof Error?h.message:String(h);throw new a(`Could not reach the libSQL server at ${this.baseUrl}: ${d}`,{code:"LIBSQL_CONNECTION_FAILED",cause:h})}if(!u.ok){let h=await ba(u),d=h?` (${h})`:"";if(u.status===401||u.status===403)throw new a(`The libSQL server at ${this.baseUrl} rejected the request: HTTP ${u.status}${d}. `+(this.authToken?"The auth token was refused - check that it belongs to this database and has not expired.":"No auth token was sent - set one (TURSO_AUTH_TOKEN in Stacks)."),{code:"LIBSQL_UNAUTHORIZED",status:u.status});if(u.status===404)throw new a(`The libSQL server at ${this.baseUrl} has no Hrana v3 pipeline endpoint (HTTP 404). Check the URL, and that the server is sqld 0.21+ or Turso.`,{code:"LIBSQL_NOT_FOUND",status:404});throw new a(`The libSQL server at ${this.baseUrl} answered HTTP ${u.status}${d}`,{code:"LIBSQL_HTTP_ERROR",status:u.status})}let g=await u.json();if(!g||!Array.isArray(g.results))throw new a(`The libSQL server at ${this.baseUrl} sent a reply that is not a Hrana pipeline response`,{code:"LIBSQL_PROTOCOL_ERROR"});return g}}async function ba(i){try{let o=(await i.text()).trim();if(!o)return"";try{let c=JSON.parse(o),f=c.error??c.message;if(typeof f==="string")return f}catch{}return o.slice(0,300)}catch{return""}}class Ks{http;prelude;baton=null;baseUrl;tail=Promise.resolve();opened=!1;closed=!1;constructor(i,o){this.http=i;this.prelude=o;this.baseUrl=i.baseUrl}send(i,o={}){let c=async()=>{if(this.closed)throw new a("This libSQL stream is closed",{code:"LIBSQL_STREAM_CLOSED"});let u=this.opened?[]:this.prelude();this.opened=!0;let g=[...u,...i];if(o.close)g.push({type:"close"});let h;try{h=await this.http.pipeline(this.baseUrl,this.baton,g)}catch(d){throw this.closed=!0,d}if(this.baton=h.baton,h.base_url)this.baseUrl=h.base_url.replace(/\/+$/,"");if(o.close||h.baton===null)this.closed=!0;for(let d=0;d<u.length;d++){let y=h.results[d];if(y?.type==="error")throw Ke(y.error)}return h.results.slice(u.length,u.length+i.length)},f=this.tail.then(c,c);return this.tail=f.catch(()=>{}),f}async close(){if(this.closed)return;if(!this.opened){this.closed=!0;return}await this.send([],{close:!0})}}function Je(i){if(!i)throw new a("The libSQL server sent fewer results than requests",{code:"LIBSQL_PROTOCOL_ERROR"});if(i.type==="error")throw Ke(i.error);if(i.response.type!=="execute")throw new a(`Expected an execute result, got '${i.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});return i.response.result}function Ms(i){if(i?.type==="ok"&&i.response.type==="get_autocommit")return i.response.is_autocommit;return!1}class Vs{http;largeIntegers;foreignKeys=null;pinned=null;closed=!1;constructor(i){this.http=new js(i),this.largeIntegers=i.largeIntegers??"bigint"}prelude=()=>this.foreignKeys?[{type:"execute",stmt:{sql:`PRAGMA foreign_keys = ${this.foreignKeys}`,want_rows:!1}}]:[];openStream(){return this.assertOpen(),new Ks(this.http,this.prelude)}assertOpen(){if(this.closed)throw new a("Cannot use a closed libSQL connection",{code:"LIBSQL_CLOSED"})}rows(i){return gn(i,this.largeIntegers)}notePragma(i){let o=wa(i);if(o)this.foreignKeys=o==="OFF"||o==="0"||o==="FALSE"||o==="NO"?"OFF":"ON"}async execute(i){this.assertOpen();let o=pa.test(i.sql);if(this.pinned){let g=this.pinned,h=[{type:"execute",stmt:i}];if(o)h.push({type:"get_autocommit"});let d;try{d=await g.send(h)}catch(b){if(this.pinned===g)this.pinned=null;throw b}if(o&&Ms(d[1])){if(this.pinned===g)this.pinned=null;await g.close().catch(()=>{})}let y=this.rows(Je(d[0]));return this.notePragma(i.sql),y}if(o){let g=this.openStream(),h;try{h=await g.send([{type:"execute",stmt:i},{type:"get_autocommit"}])}catch(y){throw await g.close().catch(()=>{}),y}if(h[0]?.type!=="error"&&!Ms(h[1]))this.pinned=g;else await g.close().catch(()=>{});return this.rows(Je(h[0]))}let c=this.openStream(),[f]=await c.send([{type:"execute",stmt:i}],{close:!0}),u=this.rows(Je(f));return this.notePragma(i.sql),u}async close(){this.closed=!0;let i=this.pinned;this.pinned=null,await i?.close().catch(()=>{})}}function Ws(i,o){return{async execute(c){let[f]=await o.send([{type:"execute",stmt:c}]),u=i.rows(Je(f));return i.notePragma(c.sql),u},async sequence(c){let f=[];for(let u of c)f.push(await this.execute(u));return f}}}function Sa(i){return{execute:(o)=>i.execute(o),async sequence(o){if(i.pinned){let f=[];for(let u of o)f.push(await i.execute(u));return f}let c=i.openStream();try{let f=[];for(let u of o)f.push(await Ws(i,c).execute(u));return f}finally{await c.close().catch(()=>{})}}}}function Bs(i){return{__raw:!0,value:i,toString:()=>i}}function va(i,o){let c=i[0],f=[];for(let u=0;u<o.length;u++){let g=o[u],h=Kr(g);if(h&&typeof h.sql==="string"&&Array.isArray(h.values))c+=h.sql+(i[u+1]||""),f.push(...h.values);else if(h&&(h.__raw||h.raw)){let d=h.raw,y=h.__raw?h.value:typeof d==="string"?d:d();c+=y+(i[u+1]||"")}else if(Array.isArray(g))c+=g.map(()=>"?").join(", ")+(i[u+1]||""),f.push(...g);else c+=`?${i[u+1]||""}`,f.push(g)}return{sql:c,params:f}}function Br(i,o,c,f){let u=()=>{try{return i.target.execute(Fe(o,c))}catch(h){return Promise.reject(h)}},g={sql:o,values:c,execute:u,raw:()=>o,toString:()=>o,cancel:()=>{}};if(f)g.then=(h,d)=>u().then(h,d);return g}function jr(i){function o(c,...f){if(Array.isArray(c)&&"raw"in c){let{sql:u,params:g}=va(c,f);return Br(i,u,g,!1)}if(typeof c==="string")return Bs(c);return Br(i,"",[],!1)}return o.raw=(c)=>Bs(c),o.unsafe=(c,f=[])=>Br(i,c,f??[],!0),o.query=(c,f)=>{try{return i.target.execute(Fe(c,f??[]))}catch(u){return Promise.reject(u)}},o.file=async(c)=>{let{readFileSync:f}=await import("fs"),u=Vr(f(c,"utf-8")).map((g)=>g.trim()).filter((g)=>g&&!g.startsWith("--"));return await i.target.sequence(u.map((g)=>Fe(g))),[]},o.batch=async(c)=>{if(i.session.assertOpen(),c.length===0)return[];let f=i.stream!==null,u=c.map((k)=>Fe(k.sql,k.args??[])),g=[];if(!f)g.push({stmt:{sql:"BEGIN"}});for(let k of u)g.push({stmt:k,condition:g.length?{type:"ok",step:g.length-1}:null});if(!f){let k=g.length-1;g.push({stmt:{sql:"COMMIT"},condition:{type:"ok",step:k}}),g.push({stmt:{sql:"ROLLBACK"},condition:{type:"not",cond:{type:"ok",step:k+1}}})}let h=i.stream??i.session.openStream(),d;try{d=await h.send([{type:"batch",batch:{steps:g}}],{close:!f})}finally{if(!f)await h.close().catch(()=>{})}let y=d[0];if(!y)throw new a("The libSQL server sent no batch result",{code:"LIBSQL_PROTOCOL_ERROR"});if(y.type==="error")throw Ke(y.error);if(y.response.type!=="batch")throw new a(`Expected a batch result, got '${y.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});let{step_results:b,step_errors:S}=y.response.result,v=f?0:1;for(let k=0;k<S.length;k++){let x=S[k];if(x)throw Ke(x)}return u.map((k,x)=>{let R=b[x+v];if(!R)throw new a(`Batch statement ${x+1} did not run`,{code:"LIBSQL_BATCH_SKIPPED"});return i.session.rows(R)})},o.begin=async(c,f)=>{let u=typeof c==="function"?c:f;if(typeof u!=="function")throw TypeError("[query-builder] libsql begin(): a transaction callback is required");if(i.session.assertOpen(),i.stream){let S=`qb_sp_${i.depth}`,v=i.target;await v.execute({sql:`SAVEPOINT ${S}`});let k=jr({...i,depth:i.depth+1});try{let x=await u(k);return await v.execute({sql:`RELEASE SAVEPOINT ${S}`}),x}catch(x){try{await v.execute({sql:`ROLLBACK TO SAVEPOINT ${S}`}),await v.execute({sql:`RELEASE SAVEPOINT ${S}`})}catch{}throw x}}let g=i.session.openStream(),h=Ws(i.session,g);try{await h.execute({sql:"BEGIN"})}catch(S){throw await g.close().catch(()=>{}),S}let d=jr({session:i.session,target:h,stream:g,depth:1}),y;try{y=await u(d)}catch(S){try{await g.send([{type:"execute",stmt:{sql:"ROLLBACK"}}],{close:!0})}catch{await g.close().catch(()=>{})}throw S}let[b]=await g.send([{type:"execute",stmt:{sql:"COMMIT"}}],{close:!0});return Je(b),y},o.savepoint=o.begin,o.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on libSQL. Use begin()/transaction().")},o.close=async()=>{if(i.stream)return;await i.session.close()},o.libsql={url:i.session.http.baseUrl,transaction:i.stream!==null},o}function Vt(i){let o=new Vs(i);return jr({session:o,target:Sa(o),stream:null,depth:0})}function Vn(i){return(typeof i==="function"||typeof i==="object"&&i!==null)&&typeof i.libsql==="object"&&i.libsql!==null}var Ht=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"];function Qt(){let i=e.sqlite?.pragmas;return Array.isArray(i)?i:Ht}function C(i){for(let o of Qt())try{i.run(o)}catch{}}var $a=32,Wr=262144;function Ze(i){return`"${i.replaceAll('"','""')}"`}class Qr{database;pending=[];bytes=0;timer;closed=!1;failure;constructor(i){this.database=i}get hasPending(){return this.pending.length>0}append=(i,o)=>{if(this.failure)return Promise.reject(this.failure);if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));let c=Object.keys(o),f=c.map((h)=>{let d=o[h];if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength).slice();if(d instanceof Date)return ye(d);return d??null}),u=JSON.stringify([i,c]),g=512+u.length*2+f.reduce((h,d)=>h+(typeof d==="string"?d.length*2:ArrayBuffer.isView(d)?d.byteLength:16),0);if(this.hasPending&&(this.pending.length>=$a||this.bytes+g>Wr))this.flush();return new Promise((h,d)=>{let y={table:i,columns:c,values:f,shape:u,uncached:g>Wr,resolve:h,reject:d};if(this.database.inTransaction||g>Wr){this.writeOne(y);return}this.pending.push(y),this.bytes+=g,this.timer??=setImmediate(()=>this.flush())})};flush(){if(this.timer!==void 0)clearImmediate(this.timer),this.timer=void 0;let i=this.pending;this.pending=[],this.bytes=0;for(let o=0;o<i.length;){if(this.failure){for(let u of i.slice(o))u.reject(this.failure);return}let c=o+1;while(c<i.length&&i[c].shape===i[o].shape)c++;let f=i.slice(o,c);if(o=c,f.length===1||!f[0].columns.length||this.database.inTransaction){for(let u of f)this.writeOne(u);continue}try{this.database.transaction(()=>{let u=f[0],g=`(${u.columns.map(()=>"?").join(",")})`,h=`INSERT INTO ${Ze(u.table)} (${u.columns.map(Ze).join(",")}) VALUES ${f.map(()=>g).join(",")}`;this.database.query(h).run(...f.flatMap((d)=>d.values))})();for(let u of f)u.resolve()}catch(u){if(this.database.inTransaction){this.invalidate(u);for(let g of[...f,...i.slice(o)])g.reject(u);return}for(let g of f)this.writeOne(g)}}}writeOne(i){let o=!1;try{this.assertUsable(),o=this.database.inTransaction;let c=i.columns.length?`INSERT INTO ${Ze(i.table)} (${i.columns.map(Ze).join(",")}) VALUES (${i.columns.map(()=>"?").join(",")})`:`INSERT INTO ${Ze(i.table)} DEFAULT VALUES`,f=()=>{if(!i.uncached)return this.database.query(c).run(...i.values);let u=this.database.prepare(c);try{return u.run(...i.values)}finally{u.finalize()}};if(o)f();else this.database.transaction(f)();i.resolve()}catch(c){if(!this.failure&&!o&&this.database.inTransaction)this.invalidate(c);i.reject(c)}}assertUsable(){if(this.failure)throw this.failure}invalidate(i){this.failure=Error("SQLite connection is unusable after deferred insert rollback failed",{cause:i});try{this.database.close()}catch{}}close(){this.closed=!0,this.flush()}}function Ur(i){return p(i)}function Kr(i){return i!==null&&typeof i==="object"?i:null}function qt(i,o){if(o.length===0||!/\$\d/.test(i))return{sql:i,params:o};let c=[],f="",u=0;for(let g=0;g<i.length;g++){let h=i[g];if(h==="'"||h==='"'||h==="`"){let d=ka(i,g,h);f+=i.slice(g,d),g=d-1;continue}if(h==="-"&&i[g+1]==="-"){let d=i.indexOf(`
|
|
62
|
-
`,g),y=d===-1?i.length:d;f+=i.slice(g,y),g=y-1;continue}if(h==="/"&&i[g+1]==="*"){let d=i.indexOf("*/",g+2),y=d===-1?i.length:d+2;f+=i.slice(g,y),g=y-1;continue}if(h==="$"){let d=/^\d+/.exec(i.slice(g+1))?.[0];if(d){let y=Number(d);if(u=Math.max(u,y),y>=1&&y<=o.length){c.push(o[y-1]),f+="?",g+=d.length;continue}}}f+=h}if(u>o.length)throw Error(`SQL references $${u} but only ${o.length} value${o.length===1?" was":"s were"} provided`);if(c.length===0)return{sql:i,params:o};return{sql:f,params:c}}function ka(i,o,c){for(let f=o+1;f<i.length;f++){if(i[f]!==c)continue;if(i[f+1]===c){f++;continue}return f+1}return i.length}var qr=/^\s*(?:SELECT|WITH|INSERT|UPDATE|DELETE|REPLACE)\b/i;class Hs{db;deferredInserts;closed=!1;constructor(i){if(i!==":memory:"&&!i.startsWith(":")){let o=Ta(i);if(o&&o!==".")xa(o,{recursive:!0})}this.db=new Ca(i),
|
|
61
|
+
`;return c}}function na(i,o,c={}){return xs(i,o,c,new WeakMap)}function xs(i,o,c,f){let{arrayMergeMode:u="replace",skipNullish:g=!1,customMerger:h}=c;if(o===null||o===void 0)return g?i:o;if(h){let d=h(i,o);if(d!==void 0)return d}if(Array.isArray(o)||Array.isArray(i))return Ts(i,o,u,f);if(!se(o)||!se(i))return o;return aa(i,o,c,f)}function Ts(i,o,c,f){if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(i)&&!Array.isArray(o))return o;if(Array.isArray(o)&&Array.isArray(i))switch(c){case"replace":return o;case"concat":return sa(i,o);case"smart":return ia(i,o,f);default:return o}return o}function sa(i,o){let c=[...o];for(let f of i)if(!c.some((u)=>Tr(u,f)))c.push(f);return c}function ia(i,o,c){if(o.length===0)return i;if(i.length===0)return o;if(se(o[0])&&se(i[0]))return oa(i,o,c);if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}function oa(i,o,c){let f=[...o];for(let u of i){if(!se(u)){f.push(u);continue}let g=["id","name","key","path","type"],h=!1;for(let d of g)if(d in u){if(f.find((b)=>se(b)&&(d in b)&&b[d]===u[d])){h=!0;break}}if(!h)f.push(u)}return f}function aa(i,o,c,f){let u=o;if(se(u)&&f.has(u))return f.get(u);let g={...i};if(se(u))f.set(u,g);for(let h in u){if(!Object.prototype.hasOwnProperty.call(u,h))continue;let d=u[h],y=g[h];if(c.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){g[h]=d;continue}if(se(d)&&se(y))g[h]=xs(y,d,c,f);else if(Array.isArray(d)||Array.isArray(y))g[h]=Ts(y,d,c.arrayMergeMode||"smart",f);else g[h]=d}return g}function ks(i,o,c="replace"){return na(i,o,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function Tr(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!Tr(i[c],o[c]))return!1;return!0}if(se(i)&&se(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!Tr(i[u],o[u]))return!1}return!0}return!1}function se(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class As{extensions=Gn;async loadFromPath(i,o,c={}){let{arrayStrategy:f="replace",useCache:u=!0,cacheTtl:g,trackPerformance:h=!0,verbose:d=!1}=c;if(u){let b=Et.getWithFileCheck("file",i);if(b){if(d)console.log(`Configuration loaded from cache: ${i}`);return b}}let y=async()=>{if(!yt(i))return null;try{let b=`?t=${Date.now()}`,S=await import(i+b),v=S.default||S,C="default"in S,E=Object.keys(S).length>0;if(!C&&!E)throw new Ft(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof v!=="object"||v===null||Array.isArray(v))throw new Ft(i,Error("Configuration must export a valid object"),"unknown");let O={config:ks(o,v,f),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)Et.setWithFileCheck("file",O,i,g);return O}catch(b){throw b instanceof Error?Se.configLoad(i,b):Se.configLoad(i,Error(String(b)))}};if(h)return kr.track("loadFromPath",y,{path:i});return y()}async tryLoadFromPaths(i,o,c={}){for(let f of i)try{let u=await this.loadFromPath(f,o,c);if(u)return u}catch(u){if(u instanceof Error&&u.name==="ConfigLoadError")throw u;if(c.verbose)console.warn(`Failed to load config from ${f}:`,u)}return null}generateConfigPaths(i,o,c){return ei({name:i,directory:o,alias:c})}generateNamePatterns(i,o){return Yn({name:i,alias:o})}checkFileAccess(i){return ra(async()=>yt(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,o,c){let f=[];if(!yt(i))return f;if(o||c){let u=this.generateNamePatterns(o||"",c);for(let g of u)for(let h of this.extensions){let d=qn(i,`${g}${h}`);if(await this.checkFileAccess(d))f.push(d)}}else try{let{readdirSync:u}=await import("fs"),g=u(i);for(let h of g)if(this.looksLikeConfigFile(h)){let d=qn(i,h);if(await this.checkFileAccess(d))f.push(d)}}catch{return[]}return f}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((c)=>c.test(i))}async validateConfigFile(i){let o=[];try{if(!yt(i))return o.push("Configuration file does not exist"),o;let c=await import(i),f=c.default||c;if(f===void 0)o.push("Configuration file must export a default value or named exports");else if(typeof f!=="object"||f===null)o.push("Configuration must be an object");else if(Array.isArray(f))o.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),g=u(i,"utf8");JSON.parse(g)}catch(u){o.push(`Invalid JSON syntax: ${u}`)}}catch(c){o.push(`Failed to load configuration file: ${c}`)}return o}async getFileModificationTime(i){try{let{statSync:o}=await import("fs");return o(i).mtime}catch{return null}}async preloadConfigurations(i,o={}){let c=new Map;return await Promise.allSettled(i.map(async(f)=>{try{let u=await this.loadFromPath(f,{},o);if(u)c.set(f,u.config)}catch(u){if(o.verbose)console.warn(`Failed to preload ${f}:`,u)}})),c}}var la=/^https?:\/\//;class Ls{async validateConfiguration(i,o,c={}){let{stopOnFirstError:f=!1,validateRequired:u=!0,validateTypes:g=!0,customRules:h=[],trackPerformance:d=!0,verbose:y=!1}=c,b=async()=>{let S=[],v=[],C={stopOnFirstError:f,validateRequired:u,validateTypes:g,customRules:h,trackPerformance:d,verbose:y};try{if(typeof o==="string")return await this.validateWithSchemaFile(i,o,C);else if(Array.isArray(o))return this.validateWithRules(i,[...o,...h],C);else return this.validateWithJSONSchema(i,o,C)}catch(E){return S.push({path:"",message:`Validation failed: ${E}`,rule:"system"}),{isValid:!1,errors:S,warnings:v}}};if(d)return await kr.track("validateConfiguration",b);return b()}async validateWithSchemaFile(i,o,c){try{if(!ca(o))throw new It(o,[{path:"",message:"Schema file does not exist"}]);let f=await import(o),u=f.default||f;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(f){throw new It(o,[{path:"",message:`Failed to load schema: ${f}`}])}}validateWithJSONSchema(i,o,c){let f=[],u=[];return this.validateObjectAgainstSchema(i,o,"",f,u,c),{isValid:f.length===0,errors:f,warnings:u}}validateObjectAgainstSchema(i,o,c,f,u,g){if(g.validateTypes&&o.type){let h=Array.isArray(i)?"array":typeof i,d=Array.isArray(o.type)?o.type:[o.type];if(!d.includes(h)){if(f.push({path:c,message:`Expected type ${d.join(" or ")}, got ${h}`,expected:d.join(" or "),actual:h,rule:"type"}),g.stopOnFirstError)return}}if(o.enum&&!o.enum.includes(i)){if(f.push({path:c,message:`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"}),g.stopOnFirstError)return}if(typeof i==="string"){if(o.minLength!==void 0&&i.length<o.minLength)f.push({path:c,message:`String length must be at least ${o.minLength}`,expected:`>= ${o.minLength}`,actual:i.length,rule:"minLength"});if(o.maxLength!==void 0&&i.length>o.maxLength)f.push({path:c,message:`String length must not exceed ${o.maxLength}`,expected:`<= ${o.maxLength}`,actual:i.length,rule:"maxLength"});if(o.pattern){if(!new RegExp(o.pattern).test(i))f.push({path:c,message:`String does not match pattern ${o.pattern}`,expected:o.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(o.minimum!==void 0&&i<o.minimum)f.push({path:c,message:`Value must be at least ${o.minimum}`,expected:`>= ${o.minimum}`,actual:i,rule:"minimum"});if(o.maximum!==void 0&&i>o.maximum)f.push({path:c,message:`Value must not exceed ${o.maximum}`,expected:`<= ${o.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&o.items)for(let h=0;h<i.length;h++){let d=c?`${c}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema(i[h],o.items,d,f,u,g),g.stopOnFirstError&&f.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let h=i;if(g.validateRequired&&o.required){for(let d of o.required)if(!(d in h)){if(f.push({path:c?`${c}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),g.stopOnFirstError)return}}if(o.properties){for(let[d,y]of Object.entries(o.properties))if(d in h){let b=c?`${c}.${d}`:d;if(this.validateObjectAgainstSchema(h[d],y,b,f,u,g),g.stopOnFirstError&&f.length>0)return}}if(o.additionalProperties===!1){let d=new Set(Object.keys(o.properties||{}));for(let y of Object.keys(h))if(!d.has(y))u.push({path:c?`${c}.${y}`:y,message:`Additional property '${y}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,o,c){let f=[],u=[];for(let g of o)try{let h=this.getValueByPath(i,g.path),d=this.validateWithRule(h,g,g.path);if(f.push(...d),c.stopOnFirstError&&f.length>0)break}catch(h){f.push({path:g.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:f.length===0,errors:f,warnings:u}}validateWithRule(i,o,c){let f=[];if(o.required&&(i===void 0||i===null))return f.push({path:c,message:o.message||`Property '${c}' is required`,expected:"required",rule:"required"}),f;if(i===void 0||i===null)return f;if(o.type){let u=Array.isArray(i)?"array":typeof i;if(u!==o.type)f.push({path:c,message:o.message||`Expected type ${o.type}, got ${u}`,expected:o.type,actual:u,rule:"type"})}if(o.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<o.min)f.push({path:c,message:o.message||`Value must be at least ${o.min}`,expected:`>= ${o.min}`,actual:u,rule:"min"})}if(o.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>o.max)f.push({path:c,message:o.message||`Value must not exceed ${o.max}`,expected:`<= ${o.max}`,actual:u,rule:"max"})}if(o.pattern&&typeof i==="string"){if(!o.pattern.test(i))f.push({path:c,message:o.message||`Value does not match pattern ${o.pattern}`,expected:o.pattern.toString(),actual:i,rule:"pattern"})}if(o.enum&&!o.enum.includes(i))f.push({path:c,message:o.message||`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"});if(o.validator){let u=o.validator(i);if(u)f.push({path:c,message:o.message||u,rule:"custom"})}return f}getValueByPath(i,o){if(!o)return i;let c=o.split("."),f=i;for(let u of c)if(f&&typeof f==="object"&&u in f)f=f[u];else return;return f}generateRulesFromInterface(i){let o=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let f of c){let[,u,g,h]=f;o.push({path:u,required:!g,type:this.mapTypeScriptType(h)})}return o}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:la},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ae=new jt("bunfig",{showTags:!0});function fa(i){if(!i)return"";let o=Array.isArray(i)?i.filter(Boolean):[i];if(o.length===0)return"";if(o.length===1)return` or alias "${o[0]}"`;return` or aliases ${o.map((c)=>`"${c}"`).join(", ")}`}class Rs{fileLoader=new As;envProcessor=new Ir;validator=new Ls;async loadConfig(i){let o=Date.now(),{cache:c,performance:f,schema:u,validate:g,...h}=i;try{if(c?.enabled){let y=this.checkCache(h.name||"",h);if(y)return y}let d;try{d=await this.loadConfigurationStrategies(h,!0,c)}catch(y){if(h.configFile)throw y;let b=h.__strictErrorHandling;if(y instanceof Error&&y.name==="ConfigNotFoundError"){if(b)throw y;d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(y instanceof Error&&y.name==="ConfigLoadError"){let S=y.message.includes("EACCES")||y.message.includes("EPERM")||y.message.includes("permission denied"),v=!S&&(y.message.includes("syntax")||y.message.includes("Expected")||y.message.includes("Unexpected")||y.message.includes("BuildMessage")||y.message.includes("errors building")),C=y.message.includes("Configuration must export a valid object")||y.message.includes("Configuration file is empty and exports nothing");if(b&&(C||S))throw y;if(v&&(!b||!C))d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!b)d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${y.message}`]};else throw y}else d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${y instanceof Error?y.message:String(y)}`]}}if(u||g)await this.validateConfiguration(d.config,u,g,h.name);if(c?.enabled&&d)this.cacheResult(h.name||"",d,c,h);if(f?.enabled){let y={operation:"loadConfig",duration:Date.now()-o,configName:h.name,timestamp:new Date};if(f.onMetrics)f.onMetrics(y);if(f.slowThreshold&&y.duration>f.slowThreshold)ae.warn(`Slow configuration loading detected: ${y.duration}ms for ${h.name}`);d.metrics=y}return d}catch(d){if(d instanceof Error&&d.name==="ConfigNotFoundError")throw d;let y=Date.now()-o;throw ae.error(`Configuration loading failed after ${y}ms:`,[d instanceof Error?d:Error(String(d))]),d}}async loadConfigurationStrategies(i,o=!1,c){let{name:f="",alias:u,configFile:g,cwd:h,configDir:d,defaultConfig:y,checkEnv:b=!0,arrayStrategy:S="replace",verbose:v=!1}=i,C=h||_t.cwd(),E=[];if(g){let W=fe(C,g);E.push(W);let ie=b?Me(f,y,v):y,ee=await this.fileLoader.tryLoadFromPaths([W],ie,{arrayStrategy:S,verbose:v,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(!ee)throw Se.configNotFound(f||g,E,u);if(v)ae.success(`Configuration loaded from explicit path: ${W}`);return this.finalizeResult(ee,E,b,f,v)}let A=await this.loadLocalConfiguration(f,u,C,d,y,S,v,b,c);if(A)return E.push(...this.getLocalSearchPaths(f,u,C,d)),this.finalizeResult(A,E,b,f,v);let k=await this.loadHomeConfiguration(f,u,y,S,v,b);if(k)return E.push(...this.getHomeSearchPaths(f,u)),this.finalizeResult(k,E,b,f,v);let O=await this.loadPackageJsonConfiguration(f,u,C,y,S,v,b);if(O)return E.push(fe(C,"package.json")),this.finalizeResult(O,E,b,f,v);if(E.push(...this.getAllSearchPaths(f,u,C,d)),o)throw Se.configNotFound(f,E,u);return{...await this.applyEnvironmentVariables(f,y,b,v),warnings:[`No configuration file found for "${f}"${fa(u)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,o,c,f,u,g,h,d,y){let b=d?Me(i,u,h):u,S=this.getLocalDirectories(c,f);for(let v of S){if(h)ae.info(`Searching for configuration in: ${v}`);let C=this.fileLoader.generateConfigPaths(i,v,o),E=await this.fileLoader.tryLoadFromPaths(C,b,{arrayStrategy:g,verbose:h,cacheTtl:y?.ttl,useCache:!y?.ttl||y.ttl>100});if(E){if(h)ae.success(`Configuration loaded from: ${E.source.path}`);return E}}return null}async loadHomeConfiguration(i,o,c,f,u,g){if(!i)return null;let h=g?Me(i,c,u):c,d=[fe(Ee(),".config",i),fe(Ee(),".config"),Ee()];for(let y of d){if(u)ae.info(`Checking home directory: ${y}`);let b=this.fileLoader.generateConfigPaths(i,y,o),S=await this.fileLoader.tryLoadFromPaths(b,h,{arrayStrategy:f,verbose:u});if(S){if(u)ae.success(`Configuration loaded from home directory: ${S.source.path}`);return S}}return null}async loadPackageJsonConfiguration(i,o,c,f,u,g,h){let d=h?Me(i,f,g):f;try{let y=fe(c,"package.json");if(!ri(y))return null;let b={};try{b=JSON.parse(ni(y,"utf8"))}catch(C){if(g)ae.warn("Failed to parse package.json:",[C instanceof Error?C:Error(String(C))]);return null}let S=b[i],v=i;if(!S&&o){let C=Array.isArray(o)?o:[o];for(let E of C){if(!E)continue;if(b[E]){S=b[E],v=E;break}}}if(S&&typeof S==="object"&&!Array.isArray(S)){if(g)ae.success(`Configuration loaded from package.json: ${v}`);return{config:ks(d,S,u),source:{type:"package.json",path:y,priority:30,timestamp:new Date}}}}catch(y){if(g)ae.warn("Failed to load package.json:",[y instanceof Error?y:Error(String(y))])}return null}async applyEnvironmentVariables(i,o,c,f){if(!c||!i||typeof o!=="object"||o===null||Array.isArray(o))return{config:o,source:{type:"default",priority:10,timestamp:new Date}};return{config:Me(i,o,f),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,o,c,f,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,o,c,f){let u=[];if(c){let g=c(i);if(g)u.push(...g)}if(o){let g=await this.validator.validateConfiguration(i,o);if(!g.isValid)u.push(...g.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(u.length>0)throw Se.configValidation(f||"unknown",u,f)}checkCache(i,o){let c=this.generateCacheKey(i,o);return Et.get(c)||null}cacheResult(i,o,c,f){let u=this.generateCacheKey(i,f);Et.set(u,o,void 0,c.ttl)}generateCacheKey(i,o){let c=[i];if(o.alias){let f=Array.isArray(o.alias)?o.alias.join(","):o.alias;c.push(`alias:${f}`)}if(o.cwd)c.push(`cwd:${o.cwd}`);if(o.configFile)c.push(`configFile:${o.configFile}`);if(o.configDir)c.push(`configDir:${o.configDir}`);if("checkEnv"in o)c.push(`checkEnv:${o.checkEnv}`);return c.join("|")}getLocalDirectories(i,o){return ti({cwd:i,configDir:o})}getAllSearchPaths(i,o,c,f){let u=[];return u.push(...this.getLocalSearchPaths(i,o,c,f)),u.push(...this.getHomeSearchPaths(i,o)),u.push(fe(c,"package.json")),u}getLocalSearchPaths(i,o,c,f){let u=this.getLocalDirectories(c,f),g=[];for(let h of u)g.push(...this.fileLoader.generateConfigPaths(i,h,o));return g}getHomeSearchPaths(i,o){if(!i)return[];let c=[fe(Ee(),".config",i),fe(Ee(),".config"),Ee()],f=[];for(let u of c)f.push(...this.fileLoader.generateConfigPaths(i,u,o));return f}async loadConfigWithResult(i){return this.loadConfig(i)}}var dr=new Rs;async function Os(i){let o="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let f;if(c)f=await dr.loadConfig(i);else f=await dr.loadConfig({...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}});return f?.config??o}catch(f){if(i.configFile)throw f;let u=f instanceof Error?f.name:"UnknownError",g=f instanceof Error?f.message:String(f);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||g.includes("config"))&&i.verbose)ae.warn("Unexpected error loading config, using defaults:",[f instanceof Error?f:Error(String(f))]);let d=c?{...i,defaultConfig:o}:{...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await dr.applyEnvironmentVariables(d.name||"",o,!0,d.verbose||!1))?.config??o;return o}}function Me(i,o,c=!1){let f=new Ir,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function g(h,d=[]){let y={...h};for(let[b,S]of Object.entries(h)){let v=[...d,b],C=[`${u}_${v.join("_").toUpperCase()}`,`${u}_${v.map((k)=>k.toUpperCase()).join("")}`,`${u}_${v.map((k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],E,A;for(let k of C)if(E=_t.env[k],E!==void 0){A=k;break}if(E!==void 0&&A)if(typeof S==="boolean")y[b]=["true","1","yes"].includes(E.toLowerCase());else if(typeof S==="number"){let k=Number(E);if(!Number.isNaN(k))y[b]=k}else if(Array.isArray(S))try{y[b]=JSON.parse(E)}catch{y[b]=E.split(",").map((k)=>k.trim())}else y[b]=E;else if(S&&typeof S==="object"&&!Array.isArray(S))y[b]=g(S,v)}return y}return g(o)}var bl=fe(_t.cwd(),"config"),Sl=fe(_t.cwd(),"src/generated");function n(i=e.dialect){return i==="mysql"||i==="singlestore"||i==="vitess"}var it={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}},Fs=new Set(["__proto__","constructor","prototype"]);function Ns(i){if(i===null||typeof i!=="object"||Array.isArray(i))return!1;let o=Object.getPrototypeOf(i);return o===Object.prototype||o===null}function _r(i,o,c=new Set){let f={...i};c.add(o);for(let u of Object.keys(o)){if(Fs.has(u))continue;let g=o[u];if(Ns(g)&&!c.has(g)){let h=f[u];f[u]=_r(Ns(h)?h:{},g,c)}else f[u]=g}return c.delete(o),f}var ua=Symbol.for("bun-query-builder.config"),e=globalThis[ua]??=_r({},it),ha=Symbol.for("bun-query-builder.config-state"),Kt=globalThis[ha]??={explicit:new Set,fileLoaded:!1};function I(i){if(i)return st(i);let o=Ps.env.DB_DIALECT||Ps.env.DB_CONNECTION;if(o)return st(o);return e.dialect||"postgres"}function st(i){let o=i.trim().toLowerCase();if(o==="turso"||o==="libsql")return"sqlite";return o}function t(i){if(e.dialect==="postgres")return`$${i}`;return"?"}function s(i,o=1){if(i<=0)return"";if(e.dialect==="postgres"){let c=`$${o}`;for(let f=1;f<i;f++)c+=`, $${o+f}`;return c}return i===1?"?":`?${", ?".repeat(i-1)}`}async function L(){if(!Kt.fileLoaded){Kt.fileLoaded=!0;let i=await Os({name:"query-builder",alias:"qb",defaultConfig:it}),o={};for(let[c,f]of Object.entries(i??{}))if(!Kt.explicit.has(c))o[c]=f;Is(o)}return e}var Ye=null,Ds=new Set;function Is(i){let o=_r(e,i),c=e;for(let f of Object.keys(o)){if(Fs.has(f))continue;c[f]=o[f]}}function Le(i){if(i.dialect&&Ye&&i.dialect!==Ye){let o=`${Ye}->${i.dialect}`;if(!Ds.has(o))Ds.add(o),console.warn(`[query-builder] Configuring dialect '${i.dialect}' overrides the previously configured dialect '${Ye}'. 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)Ye=i.dialect;for(let o of Object.keys(i))Kt.explicit.add(o);Is(i)}function mn(i){return i}function at(i){return typeof i==="string"&&/^(?:libsql|https?|wss?):\/\//i.test(i.trim())}function hn(i){let o;try{o=new URL(i.trim())}catch{throw new a("Invalid libSQL URL: expected libsql://, https://, http://, ws:// or wss://",{code:"LIBSQL_INVALID_URL"})}let c=o.protocol.replace(/:$/,"").toLowerCase(),f=o.searchParams.get("tls"),u=f==="0"||f==="false",g=o.searchParams.get("authToken")??void 0,h;switch(c){case"libsql":h=u?"http":"https";break;case"https":case"wss":h="https";break;case"http":case"ws":h="http";break;default:throw new a(`Unsupported libSQL URL scheme '${c}:'`,{code:"LIBSQL_INVALID_URL"})}if(o.username||o.password)throw new a("libSQL URLs must not embed credentials; pass the token as authToken",{code:"LIBSQL_INVALID_URL"});let d=o.pathname.replace(/\/+$/,"");return{baseUrl:`${h}://${o.host}${d}`,authToken:g||void 0}}var ga=[[/^UNIQUE constraint failed/i,"SQLITE_CONSTRAINT_UNIQUE",2067],[/^NOT NULL constraint failed/i,"SQLITE_CONSTRAINT_NOTNULL",1299],[/^FOREIGN KEY constraint failed/i,"SQLITE_CONSTRAINT_FOREIGNKEY",787],[/^CHECK constraint failed/i,"SQLITE_CONSTRAINT_CHECK",275]],_s={SQLITE_ERROR:1,SQLITE_INTERNAL:2,SQLITE_PERM:3,SQLITE_ABORT:4,SQLITE_BUSY:5,SQLITE_LOCKED:6,SQLITE_NOMEM:7,SQLITE_READONLY:8,SQLITE_INTERRUPT:9,SQLITE_IOERR:10,SQLITE_CORRUPT:11,SQLITE_FULL:13,SQLITE_CANTOPEN:14,SQLITE_SCHEMA:17,SQLITE_TOOBIG:18,SQLITE_CONSTRAINT:19,SQLITE_MISMATCH:20,SQLITE_MISUSE:21,SQLITE_RANGE:25};class a extends Error{code;errno;libsqlCode;status;constructor(i,o){super(i,o.cause===void 0?void 0:{cause:o.cause});this.name="LibSQLError",this.code=o.code,this.errno=o.errno,this.libsqlCode=o.libsqlCode,this.status=o.status}}function Ke(i){let c=String(i.message??"libSQL statement failed").replace(/^SQLite error:\s*/i,""),f=i.code??void 0;for(let[u,g,h]of ga)if(u.test(c))return new a(c,{code:g,errno:h,libsqlCode:f});if(f&&f in _s)return new a(c,{code:f,errno:_s[f],libsqlCode:f});if(f==="SQL_PARSE_ERROR"||f==="SQL_INPUT_ERROR")return new a(c,{code:"SQLITE_ERROR",errno:1,libsqlCode:f});return new a(c,{code:f??"LIBSQL_ERROR",libsqlCode:f})}var da=-(2n**63n),ma=2n**63n-1n;function Mr(i){return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function Wt(i){if(i===null||i===void 0)return{type:"null"};switch(typeof i){case"string":return{type:"text",value:i};case"boolean":return{type:"integer",value:i?"1":"0"};case"number":if(!Number.isFinite(i))throw RangeError(`Cannot bind ${i} to a libSQL statement: only finite numbers are allowed`);return Number.isSafeInteger(i)?{type:"integer",value:String(i===0?0:i)}:{type:"float",value:i};case"bigint":if(i<da||i>ma)throw RangeError(`Cannot bind ${i} to a libSQL statement: it does not fit in a 64-bit integer`);return{type:"integer",value:i.toString()}}if(i instanceof Date){if(Number.isNaN(i.getTime()))throw RangeError("Cannot bind an invalid Date to a libSQL statement");return{type:"text",value:i.toISOString()}}if(i instanceof Uint8Array)return{type:"blob",base64:Mr(i)};if(i instanceof ArrayBuffer)return{type:"blob",base64:Mr(new Uint8Array(i))};if(ArrayBuffer.isView(i))return{type:"blob",base64:Mr(new Uint8Array(i.buffer,i.byteOffset,i.byteLength))};throw TypeError(`Cannot bind a value of type ${Object.prototype.toString.call(i).slice(8,-1)} to a libSQL statement; serialize it first (e.g. JSON.stringify)`)}function Ut(i,o="bigint"){switch(i.type){case"null":return null;case"integer":{let c=Number(i.value);if(Number.isSafeInteger(c))return c;return o==="string"?i.value:BigInt(i.value)}case"float":return typeof i.value==="number"?i.value:Number(i.value);case"text":return i.value;case"blob":{let c=Buffer.from(i.base64??"","base64");return new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}default:throw new a(`Unknown libSQL value type '${i.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"})}}function gn(i,o="bigint"){let c=i.cols.map((d,y)=>d.name??String(y)),f=i.rows.map((d)=>{let y={};for(let b=0;b<c.length;b++)y[c[b]]=Ut(d[b]??{type:"null"},o);return y}),u=Number(i.affected_row_count??0),g=i.last_insert_rowid==null?null:Ut({type:"integer",value:i.last_insert_rowid},o),h=(d)=>({value:d,enumerable:!1,writable:!0,configurable:!0});return Object.defineProperties(f,{changes:h(u),count:h(u>0?u:f.length),lastInsertRowid:h(g),columns:h(c)}),f}function Fe(i,o=[]){if(!Array.isArray(o)){let f=Object.entries(o).map(([u,g])=>({name:/^[:@$]/.test(u)?u:`:${u}`,value:Wt(g)}));return{sql:i,named_args:f,want_rows:!0}}let c=qt(i,[...o]);return{sql:c.sql,args:c.params.map(Wt),want_rows:!0}}var pa=/^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i,ya=/^\s*PRAGMA\s+(?:main\.)?foreign_keys\s*(?:=\s*|\(\s*)['"]?(\w+)['"]?\s*\)?\s*;?\s*$/i;function wa(i){let o=ya.exec(i);return o?o[1].toUpperCase():null}class js{baseUrl;authToken;timeoutMs;fetchImpl;constructor(i){let o=hn(i.url);this.baseUrl=o.baseUrl,this.authToken=i.authToken||o.authToken,this.timeoutMs=i.timeoutMs,this.fetchImpl=i.fetch??fetch}async pipeline(i,o,c){let f={"content-type":"application/json"};if(this.authToken)f.authorization=`Bearer ${this.authToken}`;let u;try{u=await this.fetchImpl(`${i}/v3/pipeline`,{method:"POST",headers:f,body:JSON.stringify({baton:o,requests:c}),signal:this.timeoutMs?AbortSignal.timeout(this.timeoutMs):void 0})}catch(h){let d=h instanceof Error?h.message:String(h);throw new a(`Could not reach the libSQL server at ${this.baseUrl}: ${d}`,{code:"LIBSQL_CONNECTION_FAILED",cause:h})}if(!u.ok){let h=await ba(u),d=h?` (${h})`:"";if(u.status===401||u.status===403)throw new a(`The libSQL server at ${this.baseUrl} rejected the request: HTTP ${u.status}${d}. `+(this.authToken?"The auth token was refused - check that it belongs to this database and has not expired.":"No auth token was sent - set one (TURSO_AUTH_TOKEN in Stacks)."),{code:"LIBSQL_UNAUTHORIZED",status:u.status});if(u.status===404)throw new a(`The libSQL server at ${this.baseUrl} has no Hrana v3 pipeline endpoint (HTTP 404). Check the URL, and that the server is sqld 0.21+ or Turso.`,{code:"LIBSQL_NOT_FOUND",status:404});throw new a(`The libSQL server at ${this.baseUrl} answered HTTP ${u.status}${d}`,{code:"LIBSQL_HTTP_ERROR",status:u.status})}let g=await u.json();if(!g||!Array.isArray(g.results))throw new a(`The libSQL server at ${this.baseUrl} sent a reply that is not a Hrana pipeline response`,{code:"LIBSQL_PROTOCOL_ERROR"});return g}}async function ba(i){try{let o=(await i.text()).trim();if(!o)return"";try{let c=JSON.parse(o),f=c.error??c.message;if(typeof f==="string")return f}catch{}return o.slice(0,300)}catch{return""}}class Ks{http;prelude;baton=null;baseUrl;tail=Promise.resolve();opened=!1;closed=!1;constructor(i,o){this.http=i;this.prelude=o;this.baseUrl=i.baseUrl}send(i,o={}){let c=async()=>{if(this.closed)throw new a("This libSQL stream is closed",{code:"LIBSQL_STREAM_CLOSED"});let u=this.opened?[]:this.prelude();this.opened=!0;let g=[...u,...i];if(o.close)g.push({type:"close"});let h;try{h=await this.http.pipeline(this.baseUrl,this.baton,g)}catch(d){throw this.closed=!0,d}if(this.baton=h.baton,h.base_url)this.baseUrl=h.base_url.replace(/\/+$/,"");if(o.close||h.baton===null)this.closed=!0;for(let d=0;d<u.length;d++){let y=h.results[d];if(y?.type==="error")throw Ke(y.error)}return h.results.slice(u.length,u.length+i.length)},f=this.tail.then(c,c);return this.tail=f.catch(()=>{}),f}async close(){if(this.closed)return;if(!this.opened){this.closed=!0;return}await this.send([],{close:!0})}}function Je(i){if(!i)throw new a("The libSQL server sent fewer results than requests",{code:"LIBSQL_PROTOCOL_ERROR"});if(i.type==="error")throw Ke(i.error);if(i.response.type!=="execute")throw new a(`Expected an execute result, got '${i.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});return i.response.result}function Ms(i){if(i?.type==="ok"&&i.response.type==="get_autocommit")return i.response.is_autocommit;return!1}class Vs{http;largeIntegers;foreignKeys=null;pinned=null;closed=!1;constructor(i){this.http=new js(i),this.largeIntegers=i.largeIntegers??"bigint"}prelude=()=>this.foreignKeys?[{type:"execute",stmt:{sql:`PRAGMA foreign_keys = ${this.foreignKeys}`,want_rows:!1}}]:[];openStream(){return this.assertOpen(),new Ks(this.http,this.prelude)}assertOpen(){if(this.closed)throw new a("Cannot use a closed libSQL connection",{code:"LIBSQL_CLOSED"})}rows(i){return gn(i,this.largeIntegers)}notePragma(i){let o=wa(i);if(o)this.foreignKeys=o==="OFF"||o==="0"||o==="FALSE"||o==="NO"?"OFF":"ON"}async execute(i){this.assertOpen();let o=pa.test(i.sql);if(this.pinned){let g=this.pinned,h=[{type:"execute",stmt:i}];if(o)h.push({type:"get_autocommit"});let d;try{d=await g.send(h)}catch(b){if(this.pinned===g)this.pinned=null;throw b}if(o&&Ms(d[1])){if(this.pinned===g)this.pinned=null;await g.close().catch(()=>{})}let y=this.rows(Je(d[0]));return this.notePragma(i.sql),y}if(o){let g=this.openStream(),h;try{h=await g.send([{type:"execute",stmt:i},{type:"get_autocommit"}])}catch(y){throw await g.close().catch(()=>{}),y}if(h[0]?.type!=="error"&&!Ms(h[1]))this.pinned=g;else await g.close().catch(()=>{});return this.rows(Je(h[0]))}let c=this.openStream(),[f]=await c.send([{type:"execute",stmt:i}],{close:!0}),u=this.rows(Je(f));return this.notePragma(i.sql),u}async close(){this.closed=!0;let i=this.pinned;this.pinned=null,await i?.close().catch(()=>{})}}function Ws(i,o){return{async execute(c){let[f]=await o.send([{type:"execute",stmt:c}]),u=i.rows(Je(f));return i.notePragma(c.sql),u},async sequence(c){let f=[];for(let u of c)f.push(await this.execute(u));return f}}}function Sa(i){return{execute:(o)=>i.execute(o),async sequence(o){if(i.pinned){let f=[];for(let u of o)f.push(await i.execute(u));return f}let c=i.openStream();try{let f=[];for(let u of o)f.push(await Ws(i,c).execute(u));return f}finally{await c.close().catch(()=>{})}}}}function Bs(i){return{__raw:!0,value:i,toString:()=>i}}function va(i,o){let c=i[0],f=[];for(let u=0;u<o.length;u++){let g=o[u],h=Kr(g);if(h&&typeof h.sql==="string"&&Array.isArray(h.values))c+=h.sql+(i[u+1]||""),f.push(...h.values);else if(h&&(h.__raw||h.raw)){let d=h.raw,y=h.__raw?h.value:typeof d==="string"?d:d();c+=y+(i[u+1]||"")}else if(Array.isArray(g))c+=g.map(()=>"?").join(", ")+(i[u+1]||""),f.push(...g);else c+=`?${i[u+1]||""}`,f.push(g)}return{sql:c,params:f}}function Br(i,o,c,f){let u=()=>{try{return i.target.execute(Fe(o,c))}catch(h){return Promise.reject(h)}},g={sql:o,values:c,execute:u,raw:()=>o,toString:()=>o,cancel:()=>{}};if(f)g.then=(h,d)=>u().then(h,d);return g}function jr(i){function o(c,...f){if(Array.isArray(c)&&"raw"in c){let{sql:u,params:g}=va(c,f);return Br(i,u,g,!1)}if(typeof c==="string")return Bs(c);return Br(i,"",[],!1)}return o.raw=(c)=>Bs(c),o.unsafe=(c,f=[])=>Br(i,c,f??[],!0),o.query=(c,f)=>{try{return i.target.execute(Fe(c,f??[]))}catch(u){return Promise.reject(u)}},o.file=async(c)=>{let{readFileSync:f}=await import("fs"),u=Vr(f(c,"utf-8")).map((g)=>g.trim()).filter((g)=>g&&!g.startsWith("--"));return await i.target.sequence(u.map((g)=>Fe(g))),[]},o.batch=async(c)=>{if(i.session.assertOpen(),c.length===0)return[];let f=i.stream!==null,u=c.map((C)=>Fe(C.sql,C.args??[])),g=[];if(!f)g.push({stmt:{sql:"BEGIN"}});for(let C of u)g.push({stmt:C,condition:g.length?{type:"ok",step:g.length-1}:null});if(!f){let C=g.length-1;g.push({stmt:{sql:"COMMIT"},condition:{type:"ok",step:C}}),g.push({stmt:{sql:"ROLLBACK"},condition:{type:"not",cond:{type:"ok",step:C+1}}})}let h=i.stream??i.session.openStream(),d;try{d=await h.send([{type:"batch",batch:{steps:g}}],{close:!f})}finally{if(!f)await h.close().catch(()=>{})}let y=d[0];if(!y)throw new a("The libSQL server sent no batch result",{code:"LIBSQL_PROTOCOL_ERROR"});if(y.type==="error")throw Ke(y.error);if(y.response.type!=="batch")throw new a(`Expected a batch result, got '${y.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});let{step_results:b,step_errors:S}=y.response.result,v=f?0:1;for(let C=0;C<S.length;C++){let E=S[C];if(E)throw Ke(E)}return u.map((C,E)=>{let A=b[E+v];if(!A)throw new a(`Batch statement ${E+1} did not run`,{code:"LIBSQL_BATCH_SKIPPED"});return i.session.rows(A)})},o.begin=async(c,f)=>{let u=typeof c==="function"?c:f;if(typeof u!=="function")throw TypeError("[query-builder] libsql begin(): a transaction callback is required");if(i.session.assertOpen(),i.stream){let S=`qb_sp_${i.depth}`,v=i.target;await v.execute({sql:`SAVEPOINT ${S}`});let C=jr({...i,depth:i.depth+1});try{let E=await u(C);return await v.execute({sql:`RELEASE SAVEPOINT ${S}`}),E}catch(E){try{await v.execute({sql:`ROLLBACK TO SAVEPOINT ${S}`}),await v.execute({sql:`RELEASE SAVEPOINT ${S}`})}catch{}throw E}}let g=i.session.openStream(),h=Ws(i.session,g);try{await h.execute({sql:"BEGIN"})}catch(S){throw await g.close().catch(()=>{}),S}let d=jr({session:i.session,target:h,stream:g,depth:1}),y;try{y=await u(d)}catch(S){try{await g.send([{type:"execute",stmt:{sql:"ROLLBACK"}}],{close:!0})}catch{await g.close().catch(()=>{})}throw S}let[b]=await g.send([{type:"execute",stmt:{sql:"COMMIT"}}],{close:!0});return Je(b),y},o.savepoint=o.begin,o.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on libSQL. Use begin()/transaction().")},o.close=async()=>{if(i.stream)return;await i.session.close()},o.libsql={url:i.session.http.baseUrl,transaction:i.stream!==null},o}function Vt(i){let o=new Vs(i);return jr({session:o,target:Sa(o),stream:null,depth:0})}function Vn(i){return(typeof i==="function"||typeof i==="object"&&i!==null)&&typeof i.libsql==="object"&&i.libsql!==null}var Ht=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"];function Qt(){let i=e.sqlite?.pragmas;return Array.isArray(i)?i:Ht}function R(i){for(let o of Qt())try{i.run(o)}catch{}}var $a=32,Wr=262144;function Ze(i){return`"${i.replaceAll('"','""')}"`}class Qr{database;pending=[];bytes=0;timer;closed=!1;failure;constructor(i){this.database=i}get hasPending(){return this.pending.length>0}append=(i,o)=>{if(this.failure)return Promise.reject(this.failure);if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));let c=Object.keys(o),f=c.map((h)=>{let d=o[h];if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength).slice();if(d instanceof Date)return ye(d);return d??null}),u=JSON.stringify([i,c]),g=512+u.length*2+f.reduce((h,d)=>h+(typeof d==="string"?d.length*2:ArrayBuffer.isView(d)?d.byteLength:16),0);if(this.hasPending&&(this.pending.length>=$a||this.bytes+g>Wr))this.flush();return new Promise((h,d)=>{let y={table:i,columns:c,values:f,shape:u,uncached:g>Wr,resolve:h,reject:d};if(this.database.inTransaction||g>Wr){this.writeOne(y);return}this.pending.push(y),this.bytes+=g,this.timer??=setImmediate(()=>this.flush())})};flush(){if(this.timer!==void 0)clearImmediate(this.timer),this.timer=void 0;let i=this.pending;this.pending=[],this.bytes=0;for(let o=0;o<i.length;){if(this.failure){for(let u of i.slice(o))u.reject(this.failure);return}let c=o+1;while(c<i.length&&i[c].shape===i[o].shape)c++;let f=i.slice(o,c);if(o=c,f.length===1||!f[0].columns.length||this.database.inTransaction){for(let u of f)this.writeOne(u);continue}try{this.database.transaction(()=>{let u=f[0],g=`(${u.columns.map(()=>"?").join(",")})`,h=`INSERT INTO ${Ze(u.table)} (${u.columns.map(Ze).join(",")}) VALUES ${f.map(()=>g).join(",")}`;this.database.query(h).run(...f.flatMap((d)=>d.values))})();for(let u of f)u.resolve()}catch(u){if(this.database.inTransaction){this.invalidate(u);for(let g of[...f,...i.slice(o)])g.reject(u);return}for(let g of f)this.writeOne(g)}}}writeOne(i){let o=!1;try{this.assertUsable(),o=this.database.inTransaction;let c=i.columns.length?`INSERT INTO ${Ze(i.table)} (${i.columns.map(Ze).join(",")}) VALUES (${i.columns.map(()=>"?").join(",")})`:`INSERT INTO ${Ze(i.table)} DEFAULT VALUES`,f=()=>{if(!i.uncached)return this.database.query(c).run(...i.values);let u=this.database.prepare(c);try{return u.run(...i.values)}finally{u.finalize()}};if(o)f();else this.database.transaction(f)();i.resolve()}catch(c){if(!this.failure&&!o&&this.database.inTransaction)this.invalidate(c);i.reject(c)}}assertUsable(){if(this.failure)throw this.failure}invalidate(i){this.failure=Error("SQLite connection is unusable after deferred insert rollback failed",{cause:i});try{this.database.close()}catch{}}close(){this.closed=!0,this.flush()}}function Ur(i){return p(i)}function Kr(i){return i!==null&&typeof i==="object"?i:null}function qt(i,o){if(o.length===0||!/\$\d/.test(i))return{sql:i,params:o};let c=[],f="",u=0;for(let g=0;g<i.length;g++){let h=i[g];if(h==="'"||h==='"'||h==="`"){let d=ka(i,g,h);f+=i.slice(g,d),g=d-1;continue}if(h==="-"&&i[g+1]==="-"){let d=i.indexOf(`
|
|
62
|
+
`,g),y=d===-1?i.length:d;f+=i.slice(g,y),g=y-1;continue}if(h==="/"&&i[g+1]==="*"){let d=i.indexOf("*/",g+2),y=d===-1?i.length:d+2;f+=i.slice(g,y),g=y-1;continue}if(h==="$"){let d=/^\d+/.exec(i.slice(g+1))?.[0];if(d){let y=Number(d);if(u=Math.max(u,y),y>=1&&y<=o.length){c.push(o[y-1]),f+="?",g+=d.length;continue}}}f+=h}if(u>o.length)throw Error(`SQL references $${u} but only ${o.length} value${o.length===1?" was":"s were"} provided`);if(c.length===0)return{sql:i,params:o};return{sql:f,params:c}}function ka(i,o,c){for(let f=o+1;f<i.length;f++){if(i[f]!==c)continue;if(i[f+1]===c){f++;continue}return f+1}return i.length}var qr=/^\s*(?:SELECT|WITH|INSERT|UPDATE|DELETE|REPLACE)\b/i;class Hs{db;deferredInserts;closed=!1;constructor(i){if(i!==":memory:"&&!i.startsWith(":")){let o=Ta(i);if(o&&o!==".")xa(o,{recursive:!0})}this.db=new Ca(i),R(this.db)}deferInsert=(i,o)=>{if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));if(!this.deferredInserts){let c=this.deferredInserts=new Qr(this.db),f=this.query.bind(this),u=this.run.bind(this),g=(h)=>{if(c.hasPending&&!qr.test(h))c.flush();c.assertUsable()};this.query=(h,d)=>(g(h),f(h,d)),this.run=(h,d)=>(g(h),u(h,d))}return this.deferredInserts.append(i,o)};flushDeferredInserts(){this.deferredInserts?.flush()}query(i,o=[]){let c=qt(i,o),f=c.params.length>0||qr.test(c.sql),u=f?this.db.query(c.sql):this.db.prepare(c.sql);return(f&&c.params.length===0&&u.paramsCount>0?this.db.prepare(c.sql):u).all(...c.params)}run(i,o=[]){let c=qt(i,o),f=c.params.length>0||qr.test(c.sql),u=f?this.db.query(c.sql):this.db.prepare(c.sql);return(f&&c.params.length===0&&u.paramsCount>0?this.db.prepare(c.sql):u).run(...c.params)}close(){this.closed=!0,this.deferredInserts?.close(),this.db.close()}get database(){return this.db}}function Qs(i){return{__raw:!0,value:i,toString:()=>i}}function Us(i){let o=i.trimStart();for(;;)if(o.startsWith("--")){let c=o.indexOf(`
|
|
63
63
|
`);o=c===-1?"":o.slice(c+1).trimStart()}else if(o.startsWith("/*")){let c=o.indexOf("*/");o=c===-1?"":o.slice(c+2).trimStart()}else return o}function Vr(i){let o=[],c="",f=!1,u=!1,g=!1,h=!1;for(let y=0;y<i.length;y++){let b=i[y],S=i[y+1];if(!f&&!u&&!h&&b==="-"&&S==="-"){g=!0,c+=b;continue}if(g&&(b===`
|
|
64
|
-
`||b==="\r")){g=!1,c+=b;continue}if(!f&&!u&&!g&&b==="/"&&S==="*"){h=!0,c+=b;continue}if(h&&b==="*"&&S==="/"){h=!1,c+=b+S,y++;continue}if(g||h){c+=b;continue}if(b==="'"&&!u){if(f&&S==="'"){c+=b+S,y++;continue}f=!f,c+=b;continue}if(b==='"'&&!f){u=!u,c+=b;continue}if(b===";"&&!f&&!u){let v=Us(c.trim());if(v)o.push(v);c="";continue}c+=b}let d=Us(c.trim());if(d)o.push(d);return o}function qs(i){let o=new Hs(i);function c(h,d){let y=h.trim().toUpperCase();if(y.startsWith("SELECT")||y.startsWith("PRAGMA")||/\bRETURNING\b/.test(y))return o.query(h,Ur(d));return o.run(h,Ur(d))}function f(h,...d){let y=h[0],b=[];for(let v=0;v<d.length;v++){let
|
|
64
|
+
`||b==="\r")){g=!1,c+=b;continue}if(!f&&!u&&!g&&b==="/"&&S==="*"){h=!0,c+=b;continue}if(h&&b==="*"&&S==="/"){h=!1,c+=b+S,y++;continue}if(g||h){c+=b;continue}if(b==="'"&&!u){if(f&&S==="'"){c+=b+S,y++;continue}f=!f,c+=b;continue}if(b==='"'&&!f){u=!u,c+=b;continue}if(b===";"&&!f&&!u){let v=Us(c.trim());if(v)o.push(v);c="";continue}c+=b}let d=Us(c.trim());if(d)o.push(d);return o}function qs(i){let o=new Hs(i);function c(h,d){let y=h.trim().toUpperCase();if(y.startsWith("SELECT")||y.startsWith("PRAGMA")||/\bRETURNING\b/.test(y))return o.query(h,Ur(d));return o.run(h,Ur(d))}function f(h,...d){let y=h[0],b=[];for(let v=0;v<d.length;v++){let C=d[v],E=Kr(C);if(E&&typeof E.sql==="string"&&Array.isArray(E.values))y+=E.sql+(h[v+1]||""),b.push(...E.values);else if(E&&(E.__raw||E.raw)){let A=E.raw,k=E.__raw?E.value:typeof A==="string"?A:A();y+=k+(h[v+1]||"")}else if(Array.isArray(C)){let A=C.map(()=>"?").join(", ");y+=A+(h[v+1]||""),b.push(...C)}else y+=`?${h[v+1]||""}`,b.push(C)}let S=()=>c(y,b);return{sql:y,values:b,executeSync:S,execute:()=>{try{return Promise.resolve(S())}catch(v){return Promise.reject(v)}},raw:()=>y,toString:()=>y,cancel:()=>{}}}function u(h,...d){if(Array.isArray(h)&&"raw"in h)return f(h,...d);if(typeof h==="string")return Qs(h);return f([""])}u.raw=(h)=>Qs(h),u.unsafe=(h,d=[])=>{let y=()=>c(h,d),b=()=>{try{return Promise.resolve(y())}catch(S){return Promise.reject(S)}};return{sql:h,values:d,execute:b,executeSync:y,then:(S,v)=>b().then(S,v),raw:()=>h,toString:()=>h,cancel:()=>{}}},u.deferInsert=o.deferInsert,u.flushDeferredInserts=()=>o.flushDeferredInserts(),u.close=()=>(o.close(),Promise.resolve()),u.query=(h,d)=>{try{let y=o.query(h,Ur(d||[]));return Promise.resolve(y)}catch(y){return Promise.reject(y)}},u.file=async(h,d)=>{try{let{readFileSync:y}=await import("fs"),b=y(h,"utf-8"),S=Vr(b);for(let v of S){let C=v.trim();if(!C||C.startsWith("--"))continue;let E=C.toUpperCase();if(E.startsWith("SELECT")||E.startsWith("PRAGMA"))o.query(v);else o.run(v)}return Promise.resolve([])}catch(y){return Promise.reject(y)}};let g=0;return u.begin=async(h,d)=>{let y=typeof h==="function"?h:d;if(typeof y!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let b=g>0,S=`qb_sp_${g}`;if(b)o.run(`SAVEPOINT ${S}`);else o.run("BEGIN");g++;try{let v=await y(u);if(g--,b)o.run(`RELEASE SAVEPOINT ${S}`);else o.run("COMMIT");return v}catch(v){g--;try{if(b)o.run(`ROLLBACK TO SAVEPOINT ${S}`),o.run(`RELEASE SAVEPOINT ${S}`);else o.run("ROLLBACK")}catch{}throw v}},u.savepoint=u.begin,u.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},u._wrapper=o,u}function Aa(i){let o=i.replace(/^(?:sqlite|sqlite3|file):/i,"");if(o===i)return i;return(o.startsWith("///")?o.slice(2):o.startsWith("//")?o.slice(2):o)||":memory:"}function je(i=e.database){let o=Xe.env.DB_DATABASE||i?.database||"";return String(o).replace(/^['"]|['"]$/g,"")}function La(i,o){if((i==="postgres"||i==="mysql"||i==="singlestore"||i==="vitess")&&Xe.env.DB_CONNECTION===i){let b=Xe.env,S=(b.DB_DATABASE||o.database||"").replace(/^['"]|['"]$/g,""),v=b.DB_USERNAME||o.username,C=b.DB_PASSWORD??o.password??"",E=b.DB_HOST||o.host||"localhost",A=b.DB_PORT||o.port,k=i==="postgres"?"postgres":"mysql",O=b.DB_SSL==="true"||b.DB_SSL==="1"||o.ssl?"?ssl=true":"";return`${k}://${v}:${C}@${E}${A?`:${A}`:""}/${S}${O}`}if(o.url)return i==="sqlite"?Aa(o.url):o.url;let{database:c,username:f,password:u,host:g="localhost",port:h,ssl:d}=o,y=d||Xe.env.DB_SSL==="true"||Xe.env.DB_SSL==="1"?"?ssl=true":"";switch(i){case"postgres":return`postgres://${f}:${u}@${g}${h?`:${h}`:""}/${c}${y}`;case"mysql":case"singlestore":case"vitess":return`mysql://${f}:${u}@${g}${h?`:${h}`:""}/${c}${y}`;case"sqlite":if(c===":memory:")return":memory:";return c||":memory:";default:throw Error(`Unsupported dialect: ${i}`)}}function zs(i){if(!i)return{};let o={},c=(f)=>Math.max(0,Math.round(f/1000));if(typeof i.max==="number"&&Number.isFinite(i.max))o.max=i.max;if(typeof i.idleTimeoutMs==="number"&&Number.isFinite(i.idleTimeoutMs))o.idleTimeout=c(i.idleTimeoutMs);if(typeof i.acquireTimeoutMs==="number"&&Number.isFinite(i.acquireTimeoutMs))o.connectionTimeout=c(i.acquireTimeoutMs);if(typeof i.maxLifetimeMs==="number"&&Number.isFinite(i.maxLifetimeMs))o.maxLifetime=c(i.maxLifetimeMs);if(typeof i.preparedStatements==="boolean")o.prepare=i.preparedStatements;return o}function K(i=e.database,o=e.dialect){if(o!=="sqlite"||!i)return null;let c=at(i.url)?i.url:at(i.database)?i.database:null;if(!c)return null;return{url:c,authToken:i.authToken||void 0}}function Ra(){let i=e.dialect,o=K(e.database,i);if(o)return Vt(o);let c=La(i,e.database);try{if(i==="sqlite")return qs(c);let f=zs(e.database.pool),u=decodeURIComponent(new URL(c).pathname.slice(1)),g=new Ea(c,{...f,...u?{database:u}:{}});return _(g)}catch(f){if(console.error(`[query-builder] Failed to create database connection for dialect '${i}': ${f.message}`),i==="sqlite")return qs(":memory:");throw f}}var _e=null,Hr=null;function Oa(){let i=e.database;return JSON.stringify({dialect:e.dialect,database:i.database,username:i.username,password:i.password,host:i.host,port:i.port,url:i.url,authToken:i.authToken,pool:zs(i.pool)})}function T(i=!1){let o=Oa();if(i||_e!==null&&Hr!==o||!_e)Gs(),_e=Ra(),Hr=o;return _e}function Gs(){let i=_e;return i?.flushDeferredInserts?.(),_e=null,Hr=null,i}async function Pa(i){if(!i||typeof i.close!=="function")return;await i.close()}function pn(){Pa(Gs()).catch((o)=>{console.error(`[query-builder] Failed to close database connection: ${o.message}`)})}async function ot(i){try{return await i(T())}catch(o){if(o?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||o?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let c=T(!0);return await i(c)}throw o}}function Na(){return new Proxy(function(){},{get(i,o){let c=T(),f=c[o];if(typeof f==="function")return f.bind(c);return f},apply(i,o,c){return T()(...c)}})}var r=Na();function qe(i){let o=String(i).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(o.endsWith("y")&&!/[aeou]y$/.test(o))return`${o.slice(0,-1)}ies`;if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return`${o}es`;return`${o}s`}function w(i){return typeof i?.table==="string"&&i.table.length>0?i.table:qe(String(i?.name??""))}function yn(i){return i.endsWith("s")?i.slice(0,-1):i}function bn(i){if(i.endsWith("ies")&&i.length>3){let o=i.slice(0,-3),c=o[o.length-1];if(c&&!"aeiou".includes(c))return`${o}y`}if(i.endsWith("es")&&i.length>2){let o=i.slice(0,-2);if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return o}if(i.endsWith("s")&&!i.endsWith("ss")&&!i.endsWith("us")&&!i.endsWith("is"))return i.slice(0,-1);return i}function m(i){if(i==="none")return(o)=>o;if(i==="inflect")return bn;return yn}var Gt="1 = 0";function x(i){if(i.length===0)return"";let o=[];for(let c of i)if(c.conn==="OR"&&o.length>0)o[o.length-1].push(c);else o.push([c]);return o.map((c,f)=>{let u=c.map((h)=>h.sql).join(" OR "),g=c.length>1&&o.length>1?`(${u})`:u;return f===0?g:`${c[0].conn} ${g}`}).join(" ")}function l(i,o,c,f){if(o.length===0)return c?"1 = 1":"1 = 0";return`${i} ${c?"NOT IN":"IN"} (${f})`}function lt(i,o){if(o!=="postgres")return i;return We(i,(c)=>`$${c}`).text}function te(i){return We(i,()=>{return}).count}function We(i,o){let c="",f=0,u=0,g=0;while(g<i.length){let h=i[g],d=-1;if(h==="'"||h==='"'||h==="`")d=Da(i,g,h);else if(h==="-"&&i[g+1]==="-"){let y=i.indexOf(`
|
|
65
65
|
`,g+2);d=y===-1?i.length:y}else if(h==="/"&&i[g+1]==="*"){let y=1;d=g+2;while(d<i.length&&y>0)if(i[d]==="/"&&i[d+1]==="*")y++,d+=2;else if(i[d]==="*"&&i[d+1]==="/")y--,d+=2;else d++}else if(h==="$"){let y=i.slice(g).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(y){let b=i.indexOf(y,g+y.length);d=b===-1?i.length:b+y.length}}if(d!==-1){g=d;continue}if(h==="?"){f++;let y=o(f);if(y!==void 0)c+=i.slice(u,g)+y,u=g+1}g++}return{text:u===0?i:c+i.slice(u),count:f}}function Da(i,o,c){let f=o+1;while(f<i.length){if(i[f]===c){if(i[f+1]===c){f+=2;continue}return f+1}f++}return i.length}function Ue(i,o,c=Number.POSITIVE_INFINITY){let f=[],u=0,g=(h)=>h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||h===95;for(let h=0;h<i.length;h++){let d=i.charCodeAt(h);if(d===45&&i.charCodeAt(h+1)===45){let b=i.indexOf(`
|
|
66
66
|
`,h+2);if(b===-1)return f;h=b;continue}if(d===47&&i.charCodeAt(h+1)===42){let b=1,S=h+2;while(S<i.length&&b>0)if(i[S]==="/"&&i[S+1]==="*")b++,S+=2;else if(i[S]==="*"&&i[S+1]==="/")b--,S+=2;else S++;h=S-1;continue}if(d===39||d===34||d===96){let b=h+1;while(b<i.length){if(i.charCodeAt(b)===d){if(i.charCodeAt(b+1)===d){b+=2;continue}break}b++}h=b;continue}if(d===36){let b=/^\$(?:[A-Z_][A-Z0-9_]*)?\$/i.exec(i.slice(h));if(b){let S=i.indexOf(b[0],h+b[0].length);h=S===-1?i.length:S+b[0].length-1;continue}}if(d===40){u++;continue}if(d===41){u=Math.max(0,u-1);continue}if(u!==0)continue;if(h===0)continue;let y=d&-33;if(y<65||y>90)continue;if(g(i.charCodeAt(h-1)))continue;for(let{key:b,pattern:S}of o){S.lastIndex=h;let v=S.exec(i);if(!v)continue;if(f.push({key:b,start:h,length:v[0].length}),f.length>=c)return f;h+=v[0].length-1;break}}return f}
|
|
67
|
-
export{p,
|
|
67
|
+
export{p,_,n,it,e,I,st,t,s,L,Le,mn,at,hn,a,Ke,Wt,Ut,gn,Fe,Vt,Vn,Ht,Qt,R,je,K,T,pn,ot,r,qe,w,yn,bn,m,Gt,x,l,lt,te,We,Ue};
|