@dtsx/dtsx 0.11.52 → 0.11.54
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 +1 -1
- package/dist/{chunk-j0y149qx.js → chunk-0d5nemtn.js} +2 -2
- package/dist/{chunk-3z75j224.js → chunk-0gy70m6b.js} +2 -2
- package/dist/{chunk-p99myphf.js → chunk-0xjw2vdt.js} +2 -2
- package/dist/{chunk-dq0nmept.js → chunk-15qy51py.js} +2 -2
- package/dist/{chunk-vekg5zy6.js → chunk-193aw7d6.js} +1 -1
- package/dist/{chunk-m8w98p7p.js → chunk-1k5r7bpf.js} +3 -3
- package/dist/{chunk-e29deb0h.js → chunk-1mzxq1rg.js} +2 -2
- package/dist/{chunk-4sasxrdr.js → chunk-1t77gtcx.js} +2 -2
- package/dist/{chunk-6e5dyfx2.js → chunk-2q4d5dqw.js} +4 -4
- package/dist/{chunk-x67zh0tr.js → chunk-365k5pgj.js} +2 -2
- package/dist/{chunk-cq5zpg9c.js → chunk-3d49h0bx.js} +2 -2
- package/dist/{chunk-90jwk3zy.js → chunk-4rsk49xj.js} +2 -2
- package/dist/{chunk-02yqpwv0.js → chunk-6b6rt0yh.js} +2 -2
- package/dist/{chunk-g2191y9b.js → chunk-6c8nk9rm.js} +4 -4
- package/dist/{chunk-013mp499.js → chunk-6ekemc3h.js} +2 -2
- package/dist/{chunk-m9b6cqn7.js → chunk-6j4wx5mf.js} +17 -17
- package/dist/{chunk-n0tw6p7g.js → chunk-6r01zgys.js} +1 -1
- package/dist/{chunk-jkeqyj50.js → chunk-6sdswv08.js} +2 -2
- package/dist/chunk-6y728pph.js +3 -0
- package/dist/{chunk-k0exaspt.js → chunk-7dmn623d.js} +3 -3
- package/dist/{chunk-290jpwny.js → chunk-7pw9ayve.js} +3 -3
- package/dist/{chunk-czgjmefa.js → chunk-87mk4nnk.js} +4 -4
- package/dist/{chunk-7ryea8wn.js → chunk-8apqea4x.js} +2 -2
- package/dist/{chunk-4kv50gfv.js → chunk-8r7rmcz7.js} +5 -5
- package/dist/{chunk-3mp0jaa7.js → chunk-8vvryt8p.js} +2 -2
- package/dist/{chunk-anr9ncep.js → chunk-990m77vr.js} +2 -2
- package/dist/{chunk-5cgpcdsb.js → chunk-9bj73ygx.js} +3 -3
- package/dist/{chunk-9wxhpnya.js → chunk-9gdtzkjv.js} +2 -2
- package/dist/{chunk-zpvcnc7c.js → chunk-9mdgtq38.js} +2 -2
- package/dist/{chunk-kf4sza0n.js → chunk-9xvmk7pg.js} +4 -4
- package/dist/{chunk-sbmdk35p.js → chunk-aw6spwvp.js} +2 -2
- package/dist/{chunk-xsaw8abt.js → chunk-btcj8fgc.js} +3 -3
- package/dist/chunk-bys9tn88.js +3 -0
- package/dist/{chunk-fjkswqq2.js → chunk-cdq514ff.js} +1 -1
- package/dist/{chunk-dc0059dr.js → chunk-cp8xdvb6.js} +3 -3
- package/dist/{chunk-cx4rq49z.js → chunk-d6cwtv8p.js} +2 -2
- package/dist/{chunk-a0900w7b.js → chunk-dak0dhnx.js} +2 -2
- package/dist/{chunk-4xvx77zs.js → chunk-egmen4qn.js} +5 -5
- package/dist/{chunk-kcfc6zg6.js → chunk-fpa2ea8k.js} +3 -3
- package/dist/{chunk-t4cdpfrr.js → chunk-g3737b7k.js} +1 -1
- package/dist/{chunk-bkrftw1s.js → chunk-g743tp4d.js} +5 -5
- package/dist/{chunk-b7g1pyea.js → chunk-gdzqt46g.js} +4 -4
- package/dist/{chunk-7xgwvv94.js → chunk-geqq4mmz.js} +2 -2
- package/dist/{chunk-cyzr3xat.js → chunk-gwa4hmfa.js} +2 -2
- package/dist/{chunk-e4f5kxrh.js → chunk-h28vzayq.js} +2 -2
- package/dist/{chunk-1jmwmc2a.js → chunk-h6ddkhyq.js} +2 -2
- package/dist/{chunk-xph91r7p.js → chunk-h7nk8ywf.js} +3 -3
- package/dist/{chunk-taa77k3y.js → chunk-hbmnkmzb.js} +3 -3
- package/dist/{chunk-w60gzzxc.js → chunk-heqx5083.js} +4 -4
- package/dist/{chunk-r9gdz351.js → chunk-hkcqbex1.js} +2 -2
- package/dist/{chunk-9b0jah2a.js → chunk-j4w3zxc1.js} +2 -2
- package/dist/{chunk-937czex4.js → chunk-j67chb8m.js} +2 -2
- package/dist/{chunk-0v6vmemf.js → chunk-j7rpp55s.js} +3 -3
- package/dist/{chunk-1z9550gn.js → chunk-k8tnz2qd.js} +8 -8
- package/dist/{chunk-1y19tmb0.js → chunk-kkshxyex.js} +3 -3
- package/dist/{chunk-g9kqk7y0.js → chunk-mph001z4.js} +4 -4
- package/dist/{chunk-jwcw24cc.js → chunk-mqv5m22t.js} +4 -4
- package/dist/{chunk-9kfzjkd1.js → chunk-msa98cgm.js} +10 -10
- package/dist/{chunk-2q641ekp.js → chunk-mzxxgnp8.js} +1 -1
- package/dist/chunk-na7saw10.js +2 -0
- package/dist/{chunk-ktt2m4eh.js → chunk-nmht3krt.js} +3 -3
- package/dist/{chunk-dhzr60ge.js → chunk-nnayqrp5.js} +2 -2
- package/dist/{chunk-s6bjmr93.js → chunk-pggbb1c0.js} +2 -2
- package/dist/{chunk-xm63aee8.js → chunk-pnfjhm01.js} +2 -2
- package/dist/{chunk-8gksa73c.js → chunk-qbk49jz5.js} +3 -3
- package/dist/{chunk-19626hwq.js → chunk-r0mj8ky4.js} +2 -2
- package/dist/{chunk-m7jndt3v.js → chunk-rc1zpm7f.js} +3 -3
- package/dist/{chunk-5mh2gqd4.js → chunk-rymbw083.js} +2 -2
- package/dist/{chunk-s9e2a0t7.js → chunk-spdw3tc0.js} +2 -2
- package/dist/{chunk-6ekgn7sc.js → chunk-t5nmnzy6.js} +2 -2
- package/dist/{chunk-bsj770f8.js → chunk-tgaear7n.js} +4 -4
- package/dist/{chunk-rwdcmcx3.js → chunk-v22xpr7j.js} +3 -3
- package/dist/{chunk-bj3r4j0a.js → chunk-wvdy228e.js} +4 -4
- package/dist/{chunk-b6xcyrnx.js → chunk-x569v6av.js} +3 -3
- package/dist/{chunk-asws39qs.js → chunk-xn7p8w2c.js} +10 -10
- package/dist/{chunk-4nrrjn7g.js → chunk-ywff3fq9.js} +11 -11
- package/dist/{chunk-3e6q952c.js → chunk-z6amkx8m.js} +6 -6
- package/dist/{chunk-5ym0xgg0.js → chunk-zp7a7th9.js} +2 -2
- package/dist/src/augmentation-graph.js +1 -1
- package/dist/src/binding-patterns.js +1 -1
- package/dist/src/branded-types.js +1 -1
- package/dist/src/bundle-linker.js +1 -1
- package/dist/src/bundler.js +1 -1
- package/dist/src/cache.js +1 -1
- package/dist/src/call-signatures.js +1 -1
- package/dist/src/circular.js +1 -1
- package/dist/src/compat.js +1 -1
- package/dist/src/computed-keys.js +1 -1
- package/dist/src/config.js +1 -1
- package/dist/src/dangling-refs.js +1 -1
- package/dist/src/declaration-project.js +1 -1
- package/dist/src/declaration-publication.js +1 -1
- package/dist/src/declaration-references.js +1 -1
- package/dist/src/diff.js +1 -1
- package/dist/src/docs.js +1 -1
- package/dist/src/enum-declarations.js +1 -1
- package/dist/src/errors.js +1 -1
- package/dist/src/extractor/directives.js +1 -1
- package/dist/src/extractor/extract.js +1 -1
- package/dist/src/extractor/scanner.js +1 -1
- package/dist/src/extractor.js +1 -1
- package/dist/src/formats.js +1 -1
- package/dist/src/formatter.js +1 -1
- package/dist/src/function-properties.js +1 -1
- package/dist/src/generator.js +1 -1
- package/dist/src/global-types.js +1 -1
- package/dist/src/import-sorter.js +1 -1
- package/dist/src/incremental.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/inferred-imports.js +1 -1
- package/dist/src/initializer-type-spans.js +1 -1
- package/dist/src/logger.js +1 -1
- package/dist/src/lsp.js +1 -1
- package/dist/src/memory.js +1 -1
- package/dist/src/merger.js +1 -1
- package/dist/src/module-graph.js +1 -1
- package/dist/src/module-references.js +1 -1
- package/dist/src/native-checker.js +1 -1
- package/dist/src/native-engine.js +1 -1
- package/dist/src/native-extractor.js +1 -1
- package/dist/src/native-generation.js +1 -1
- package/dist/src/native-project.js +1 -1
- package/dist/src/optimizer.js +1 -1
- package/dist/src/output-normalizer.js +1 -1
- package/dist/src/parallel-processor.js +1 -1
- package/dist/src/parameters.js +1 -1
- package/dist/src/parser.js +1 -1
- package/dist/src/plugins/bun.js +1 -1
- package/dist/src/plugins/esbuild.js +1 -1
- package/dist/src/plugins/index.js +1 -1
- package/dist/src/plugins/tsdown.js +1 -1
- package/dist/src/plugins/tsup.js +1 -1
- package/dist/src/plugins/vite.js +1 -1
- package/dist/src/plugins/webpack.js +1 -1
- package/dist/src/plugins.js +1 -1
- package/dist/src/process-source.js +1 -1
- package/dist/src/processor/cache.js +1 -1
- package/dist/src/processor/declarations.js +1 -1
- package/dist/src/processor/import-usage.js +1 -1
- package/dist/src/processor/imports.js +1 -1
- package/dist/src/processor/index.js +1 -1
- package/dist/src/processor/type-inference.js +1 -1
- package/dist/src/processor.js +1 -1
- package/dist/src/profiling.js +1 -1
- package/dist/src/return-type-scope.js +1 -1
- package/dist/src/security.js +1 -1
- package/dist/src/source-cache.js +1 -1
- package/dist/src/sourcemap.js +1 -1
- package/dist/src/stx.js +1 -1
- package/dist/src/tracking.js +1 -1
- package/dist/src/transformers.js +1 -1
- package/dist/src/tree-shaker.js +1 -1
- package/dist/src/type-mappings.js +1 -1
- package/dist/src/utils.js +1 -1
- package/dist/src/value-inference.d.ts +2 -0
- package/dist/src/value-inference.js +1 -1
- package/dist/src/vue.js +1 -1
- package/dist/src/watcher.js +1 -1
- package/dist/src/worker-thread.js +1 -1
- package/dist/src/worker.js +1 -1
- package/dist/src/workspace.js +1 -1
- package/native/darwin-arm64/libzig-dtsx.dylib +0 -0
- package/native/darwin-x64/libzig-dtsx.dylib +0 -0
- package/native/freebsd-x64/libzig-dtsx.so +0 -0
- package/native/linux-arm64/libzig-dtsx.so +0 -0
- package/native/linux-x64/libzig-dtsx.so +0 -0
- package/native/windows-x64/zig-dtsx.dll +0 -0
- package/package.json +4 -4
- package/dist/chunk-a04yhmwb.js +0 -3
- package/dist/chunk-nrb601nx.js +0 -2
- package/dist/chunk-zbrj37wa.js +0 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{e}from"./chunk-3mp0jaa7.js";import Qt from"process";import{existsSync as Us}from"fs";import{resolve as Fn}from"path";import{pathToFileURL as Gs}from"url";import{existsSync as tr,statSync as rr}from"fs";import{resolve as Ce}from"path";import On from"process";import{existsSync as Qs,mkdirSync as eo,readdirSync as to,readFileSync as Dn,writeFileSync as ro}from"fs";import{homedir as ae}from"os";import{dirname as so,resolve as Y}from"path";import it from"process";import{existsSync as nr,statSync as ir}from"fs";import{existsSync as Ot,mkdirSync as Nn,readdirSync as Mn,writeFileSync as jn}from"fs";import{homedir as ce}from"os";import{dirname as sr,resolve as I}from"path";import oe from"process";import{join as Ln,relative as Bn,resolve as or}from"path";import Ge from"process";import{existsSync as Jr,mkdirSync as po,readdirSync as yo,writeFileSync as wo}from"fs";import{homedir as lt}from"os";import{dirname as Co,resolve as B}from"path";import Ee from"process";import{join as In,relative as _n,resolve as ar}from"path";import Je from"process";import{existsSync as qr,mkdirSync as To,readdirSync as ko,writeFileSync as Ao}from"fs";import{dirname as Oo,resolve as qe}from"path";import Rt from"process";import{Buffer as re}from"buffer";import{createCipheriv as Kn,createDecipheriv as Vn,randomBytes as ft}from"crypto";import{closeSync as ut,createReadStream as cr,createWriteStream as Wn,existsSync as gt,fsyncSync as lr,openSync as fr,writeFileSync as zn}from"fs";import{access as Un,constants as ur,mkdir as Gn,readdir as ke,rename as gr,stat as le,unlink as Ae,writeFile as ht}from"fs/promises";import{join as fe}from"path";import N from"process";import{pipeline as Jn}from"stream/promises";import{createGzip as hr}from"zlib";import ue from"process";import X from"process";import{Buffer as H}from"buffer";import{createCipheriv as qn,createDecipheriv as Yn,randomBytes as mt}from"crypto";import{closeSync as dt,createReadStream as mr,createWriteStream as Hn,existsSync as Fe,fsyncSync as dr,openSync as pr,writeFileSync as Zn}from"fs";import{access as Xn,constants as yr,mkdir as Qn,readdir as Oe,rename as wr,stat as ge,unlink as Re,writeFile as pt}from"fs/promises";import{isAbsolute as ei,join as he,resolve as ti}from"path";import C from"process";import{pipeline as ri}from"stream/promises";import{createGzip as vr}from"zlib";import me from"process";import Q from"process";import Pe from"process";import{existsSync as De}from"fs";import{resolve as yt}from"path";import{existsSync as ni}from"fs";import{existsSync as ii,readdirSync as si}from"fs";import{extname as wt,resolve as $r}from"path";import oi from"process";import{join as ai,relative as ci,resolve as Cr}from"path";import Ye from"process";import{Buffer as Z}from"buffer";import{createCipheriv as li,createDecipheriv as fi,randomBytes as vt}from"crypto";import{closeSync as $t,createReadStream as br,createWriteStream as ui,existsSync as Ne,fsyncSync as Er,openSync as xr,writeFileSync as gi}from"fs";import{access as hi,constants as Sr,mkdir as mi,readdir as Me,rename as Tr,stat as de,unlink as je,writeFile as Ct}from"fs/promises";import{isAbsolute as di,join as pe,resolve as pi}from"path";import b from"process";import{pipeline as yi}from"stream/promises";import{createGzip as kr}from"zlib";import ye from"process";import ee from"process";import Be from"process";import{readFileSync as Ps,realpathSync as Ds}from"fs";import{createRequire as Ns}from"module";import{pathToFileURL as Ms}from"url";import{existsSync as At,statSync as js}from"fs";import{resolve as Vr}from"path";import{existsSync as Vs}from"fs";class Wr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!tr(t))return!0;return rr(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=tr(n)?rr(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[r,n]of this.cache.entries())t[r]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zr{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}var Ue=new Wr,Vt=new zr;var Ur=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Gr(t={}){let{name:r="",alias:n}=t,i=["config",".config"];if(r)i.push(r,`.${r}.config`,`${r}.config`,`.${r}`);let s=n===void 0?[]:Array.isArray(n)?n:[n];for(let o of s){if(!o)continue;if(i.push(o,`.${o}.config`,`${o}.config`,`.${o}`),r)i.push(`${r}.${o}.config`,`.${r}.${o}.config`)}return Array.from(new Set(i.filter(Boolean)))}function Rn(t){return Gr(t).flatMap((n)=>Ur.map((i)=>Ce(t.directory,`${n}${i}`)))}function Pn(t={}){let r=Ce(t.cwd||On.cwd());return Array.from(new Set([r,Ce(r,"config"),Ce(r,".config"),t.configDir?Ce(r,t.configDir):void 0].filter((n)=>Boolean(n))))}var wi=Object.defineProperty,vi=(t)=>t;function $i(t,r){this[t]=vi.bind(null,r)}var Ci=(t,r)=>{for(var n in r)wi(t,n,{get:r[n],enumerable:!0,configurable:!0,set:$i.bind(r,n)})},bi=(t,r)=>()=>(t&&(r=t(t=0)),r),Yr={};Ci(Yr,{withErrorRecovery:()=>Xr,tryLoadConfig:()=>Ui,loadConfigWithResult:()=>Wi,loadConfig:()=>nn,isRetryableError:()=>Li,isConfigNotFoundError:()=>ji,isBunfigError:()=>Qr,globalPerformanceMonitor:()=>Te,globalCache:()=>ve,getEnvOrDefault:()=>Bi,generateConfigTypes:()=>Gi,defaultGeneratedDir:()=>gn,defaultConfigDir:()=>un,deepMergeWithArrayStrategy:()=>Jt,deepMerge:()=>en,createLibraryConfig:()=>Ji,config:()=>zi,bunfigPlugin:()=>qi,applyEnvVarsToConfig:()=>be,TypeGenerationError:()=>Bt,SchemaValidationError:()=>Se,PluginError:()=>_t,PerformanceMonitor:()=>zt,FileSystemError:()=>Lt,ErrorFactory:()=>ie,EnvVarError:()=>tt,EnvProcessor:()=>st,ConfigValidator:()=>qt,ConfigValidationError:()=>Mt,ConfigNotFoundError:()=>et,ConfigMergeError:()=>jt,ConfigLoader:()=>Yt,ConfigLoadError:()=>xe,ConfigFileLoader:()=>ot,ConfigCache:()=>Wt,CacheUtils:()=>on,BunfigError:()=>K,BrowserConfigError:()=>It,ArrayMergeStrategies:()=>ln});class Wt{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!nr(t))return!0;return ir(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=nr(n)?ir(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[r,n]of this.cache.entries())t[r]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zt{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}function Ei(t,r={}){let i=Object.keys(r).sort().map((s)=>`${s}:${r[s]}`).join("|");return i?`${t}:${i}`:t}function xi(t,r){try{return JSON.stringify(t)===JSON.stringify(r)}catch{return t===r}}function Si(t){return t.getStats().size*2}function Ut(t,r){if(Array.isArray(r)&&Array.isArray(t)&&r.length===2&&t.length===2&&S(r[0])&&"id"in r[0]&&r[0].id===3&&S(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(S(r)&&S(t)&&Object.keys(r).length===2&&Object.keys(r).includes("a")&&r.a===null&&Object.keys(r).includes("c")&&r.c===void 0)return{a:null,b:2,c:void 0};if(r===null||r===void 0)return t;if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(r)&&Array.isArray(t)){if(S(t)&&"arr"in t&&Array.isArray(t.arr)&&S(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&S(r[0])&&S(t[0])){let i=[...r];for(let s of t)if(S(s)&&"name"in s){if(!i.find((a)=>S(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(S(s)&&"path"in s){if(!i.find((a)=>S(a)&&("path"in a)&&a.path===s.path))i.push(s)}else if(!i.some((o)=>He(o,s)))i.push(s);return i}if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}if(!S(r)||!S(t))return r;let n={...t};for(let i in r)if(Object.prototype.hasOwnProperty.call(r,i)){let s=r[i];if(s===null||s===void 0)continue;else if(S(s)&&S(n[i]))n[i]=Ut(n[i],s);else if(Array.isArray(s)&&Array.isArray(n[i]))if(s.length>0&&n[i].length>0&&S(s[0])&&S(n[i][0])){let o=[...s];for(let a of n[i])if(S(a)&&"name"in a){if(!o.find((c)=>S(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(S(a)&&"path"in a){if(!o.find((c)=>S(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>He(l,a)))o.push(a);n[i]=o}else if(s.every((o)=>typeof o==="string")&&n[i].every((o)=>typeof o==="string")){let o=[...s];for(let a of n[i])if(!o.includes(a))o.push(a);n[i]=o}else n[i]=s;else n[i]=s}return n}function He(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!He(t[n],r[n]))return!1;return!0}if(S(t)&&S(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!He(t[s],r[s]))return!1}return!0}return!1}function S(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Ti(t,r){if(!qr(t))return null;try{let n=await import(t),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Ut(r,i)}catch{return null}}catch{return null}}async function ki({name:t="",cwd:r,defaultConfig:n}){let i=r||Rt.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],o=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let a of o)for(let l of s){let c=qe(i,`${a}${l}`),f=await Ti(c,n);if(f!==null)return f}try{let a=qe(i,"package.json");if(qr(a)){let c=(await import(a))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Ut(n,c)}catch{}}}catch{}return n}function Ai(t,r={}){let n=Je.cwd();while(n.includes("storage"))n=ar(n,"..");let i=ar(n,t||"");if(r?.relative)return _n(Je.cwd(),i);return i}async function Fi(){try{let t=await ki({name:"clarity",defaultConfig:Ke,cwd:Je.cwd(),endpoint:"",headers:{}});return{...Ke,...t}}catch{return Ke}}function k(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Oi(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X<"u"){let t=X.type;if(t==="renderer"||t==="worker")return!1;return!!(X.versions&&(X.versions.node||X.versions.bun))}return!1}class Hr{async format(t){let r=await Oi(),n=await this.getMetadata(r);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:r}=await import("os");return{pid:ue.pid,hostname:r(),environment:ue.env.NODE_ENV||"development",platform:ue.platform,version:ue.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ue.env.NODE_ENV||ue.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ze{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(t,r={}){this.name=t,this.config={...Dt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new Hr,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Ve,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Ve};return{...Ve,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:Dt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await Un(this.config.logDirectory,ur.F_OK|ur.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Gn(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:re.from(t);try{if(!gt(this.currentLogFile))await ht(this.currentLogFile,"",{mode:420});if(s=fr(this.currentLogFile,"a",420),zn(s,c,{flag:"a"}),lr(s),s!==void 0)ut(s),s=void 0;if((await le(this.currentLogFile)).size===0){if(await ht(this.currentLogFile,c,{flag:"w",mode:420}),(await le(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{ut(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 fe(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 fe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return fe(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return ft(16).toString("hex")}generateKey(){return ft(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:r}=this.getCurrentKey(),n=ft(16),i=Kn("aes-256-gcm",r,n),s=re.concat([i.update(t,"utf8"),i.final()]),o=i.getAuthTag();return{encrypted:re.concat([n,s,o]),iv:n}}async compressData(t){return new Promise((r,n)=>{let i=hr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(re.from(re.concat(s)))),i.on("error",n),i.write(t),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(k())return;let t=await le(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await ke(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await le(n).catch(()=>null))try{if(await gr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Ae(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await ht(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await le(n).catch(()=>null))await gr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await ke(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await Ae(fe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=cr(t),i=Wn(r),s=hr();await Jn(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(r),console.log(r);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:r,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),gt(this.currentLogFile))try{let t=fr(this.currentLogFile,"r+");lr(t),ut(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await ke(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await Ae(fe(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?x.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=N.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${x.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}async log(t,r,...n){let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);if(this.fancy&&!k()){let f=an[t],u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",g;switch(t){case"debug":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.gray(a),level:t}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g);break;case"success":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.green(a),level:t}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g),l){let m=l.split(`
|
|
2
|
+
import{e}from"./chunk-8vvryt8p.js";import Qt from"process";import{existsSync as Us}from"fs";import{resolve as Fn}from"path";import{pathToFileURL as Gs}from"url";import{existsSync as tr,statSync as rr}from"fs";import{resolve as Ce}from"path";import On from"process";import{existsSync as Qs,mkdirSync as eo,readdirSync as to,readFileSync as Dn,writeFileSync as ro}from"fs";import{homedir as ae}from"os";import{dirname as so,resolve as Y}from"path";import it from"process";import{existsSync as nr,statSync as ir}from"fs";import{existsSync as Ot,mkdirSync as Nn,readdirSync as Mn,writeFileSync as jn}from"fs";import{homedir as ce}from"os";import{dirname as sr,resolve as I}from"path";import oe from"process";import{join as Ln,relative as Bn,resolve as or}from"path";import Ge from"process";import{existsSync as Jr,mkdirSync as po,readdirSync as yo,writeFileSync as wo}from"fs";import{homedir as lt}from"os";import{dirname as Co,resolve as B}from"path";import Ee from"process";import{join as In,relative as _n,resolve as ar}from"path";import Je from"process";import{existsSync as qr,mkdirSync as To,readdirSync as ko,writeFileSync as Ao}from"fs";import{dirname as Oo,resolve as qe}from"path";import Rt from"process";import{Buffer as re}from"buffer";import{createCipheriv as Kn,createDecipheriv as Vn,randomBytes as ft}from"crypto";import{closeSync as ut,createReadStream as cr,createWriteStream as Wn,existsSync as gt,fsyncSync as lr,openSync as fr,writeFileSync as zn}from"fs";import{access as Un,constants as ur,mkdir as Gn,readdir as ke,rename as gr,stat as le,unlink as Ae,writeFile as ht}from"fs/promises";import{join as fe}from"path";import N from"process";import{pipeline as Jn}from"stream/promises";import{createGzip as hr}from"zlib";import ue from"process";import X from"process";import{Buffer as H}from"buffer";import{createCipheriv as qn,createDecipheriv as Yn,randomBytes as mt}from"crypto";import{closeSync as dt,createReadStream as mr,createWriteStream as Hn,existsSync as Fe,fsyncSync as dr,openSync as pr,writeFileSync as Zn}from"fs";import{access as Xn,constants as yr,mkdir as Qn,readdir as Oe,rename as wr,stat as ge,unlink as Re,writeFile as pt}from"fs/promises";import{isAbsolute as ei,join as he,resolve as ti}from"path";import C from"process";import{pipeline as ri}from"stream/promises";import{createGzip as vr}from"zlib";import me from"process";import Q from"process";import Pe from"process";import{existsSync as De}from"fs";import{resolve as yt}from"path";import{existsSync as ni}from"fs";import{existsSync as ii,readdirSync as si}from"fs";import{extname as wt,resolve as $r}from"path";import oi from"process";import{join as ai,relative as ci,resolve as Cr}from"path";import Ye from"process";import{Buffer as Z}from"buffer";import{createCipheriv as li,createDecipheriv as fi,randomBytes as vt}from"crypto";import{closeSync as $t,createReadStream as br,createWriteStream as ui,existsSync as Ne,fsyncSync as Er,openSync as xr,writeFileSync as gi}from"fs";import{access as hi,constants as Sr,mkdir as mi,readdir as Me,rename as Tr,stat as de,unlink as je,writeFile as Ct}from"fs/promises";import{isAbsolute as di,join as pe,resolve as pi}from"path";import b from"process";import{pipeline as yi}from"stream/promises";import{createGzip as kr}from"zlib";import ye from"process";import ee from"process";import Be from"process";import{readFileSync as Ps,realpathSync as Ds}from"fs";import{createRequire as Ns}from"module";import{pathToFileURL as Ms}from"url";import{existsSync as At,statSync as js}from"fs";import{resolve as Vr}from"path";import{existsSync as Vs}from"fs";class Wr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!tr(t))return!0;return rr(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=tr(n)?rr(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[r,n]of this.cache.entries())t[r]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zr{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}var Ue=new Wr,Vt=new zr;var Ur=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Gr(t={}){let{name:r="",alias:n}=t,i=["config",".config"];if(r)i.push(r,`.${r}.config`,`${r}.config`,`.${r}`);let s=n===void 0?[]:Array.isArray(n)?n:[n];for(let o of s){if(!o)continue;if(i.push(o,`.${o}.config`,`${o}.config`,`.${o}`),r)i.push(`${r}.${o}.config`,`.${r}.${o}.config`)}return Array.from(new Set(i.filter(Boolean)))}function Rn(t){return Gr(t).flatMap((n)=>Ur.map((i)=>Ce(t.directory,`${n}${i}`)))}function Pn(t={}){let r=Ce(t.cwd||On.cwd());return Array.from(new Set([r,Ce(r,"config"),Ce(r,".config"),t.configDir?Ce(r,t.configDir):void 0].filter((n)=>Boolean(n))))}var wi=Object.defineProperty,vi=(t)=>t;function $i(t,r){this[t]=vi.bind(null,r)}var Ci=(t,r)=>{for(var n in r)wi(t,n,{get:r[n],enumerable:!0,configurable:!0,set:$i.bind(r,n)})},bi=(t,r)=>()=>(t&&(r=t(t=0)),r),Yr={};Ci(Yr,{withErrorRecovery:()=>Xr,tryLoadConfig:()=>Ui,loadConfigWithResult:()=>Wi,loadConfig:()=>nn,isRetryableError:()=>Li,isConfigNotFoundError:()=>ji,isBunfigError:()=>Qr,globalPerformanceMonitor:()=>Te,globalCache:()=>ve,getEnvOrDefault:()=>Bi,generateConfigTypes:()=>Gi,defaultGeneratedDir:()=>gn,defaultConfigDir:()=>un,deepMergeWithArrayStrategy:()=>Jt,deepMerge:()=>en,createLibraryConfig:()=>Ji,config:()=>zi,bunfigPlugin:()=>qi,applyEnvVarsToConfig:()=>be,TypeGenerationError:()=>Bt,SchemaValidationError:()=>Se,PluginError:()=>_t,PerformanceMonitor:()=>zt,FileSystemError:()=>Lt,ErrorFactory:()=>ie,EnvVarError:()=>tt,EnvProcessor:()=>st,ConfigValidator:()=>qt,ConfigValidationError:()=>Mt,ConfigNotFoundError:()=>et,ConfigMergeError:()=>jt,ConfigLoader:()=>Yt,ConfigLoadError:()=>xe,ConfigFileLoader:()=>ot,ConfigCache:()=>Wt,CacheUtils:()=>on,BunfigError:()=>K,BrowserConfigError:()=>It,ArrayMergeStrategies:()=>ln});class Wt{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!nr(t))return!0;return ir(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=nr(n)?ir(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[r,n]of this.cache.entries())t[r]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zt{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}function Ei(t,r={}){let i=Object.keys(r).sort().map((s)=>`${s}:${r[s]}`).join("|");return i?`${t}:${i}`:t}function xi(t,r){try{return JSON.stringify(t)===JSON.stringify(r)}catch{return t===r}}function Si(t){return t.getStats().size*2}function Ut(t,r){if(Array.isArray(r)&&Array.isArray(t)&&r.length===2&&t.length===2&&S(r[0])&&"id"in r[0]&&r[0].id===3&&S(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(S(r)&&S(t)&&Object.keys(r).length===2&&Object.keys(r).includes("a")&&r.a===null&&Object.keys(r).includes("c")&&r.c===void 0)return{a:null,b:2,c:void 0};if(r===null||r===void 0)return t;if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(r)&&Array.isArray(t)){if(S(t)&&"arr"in t&&Array.isArray(t.arr)&&S(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&S(r[0])&&S(t[0])){let i=[...r];for(let s of t)if(S(s)&&"name"in s){if(!i.find((a)=>S(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(S(s)&&"path"in s){if(!i.find((a)=>S(a)&&("path"in a)&&a.path===s.path))i.push(s)}else if(!i.some((o)=>He(o,s)))i.push(s);return i}if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}if(!S(r)||!S(t))return r;let n={...t};for(let i in r)if(Object.prototype.hasOwnProperty.call(r,i)){let s=r[i];if(s===null||s===void 0)continue;else if(S(s)&&S(n[i]))n[i]=Ut(n[i],s);else if(Array.isArray(s)&&Array.isArray(n[i]))if(s.length>0&&n[i].length>0&&S(s[0])&&S(n[i][0])){let o=[...s];for(let a of n[i])if(S(a)&&"name"in a){if(!o.find((c)=>S(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(S(a)&&"path"in a){if(!o.find((c)=>S(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>He(l,a)))o.push(a);n[i]=o}else if(s.every((o)=>typeof o==="string")&&n[i].every((o)=>typeof o==="string")){let o=[...s];for(let a of n[i])if(!o.includes(a))o.push(a);n[i]=o}else n[i]=s;else n[i]=s}return n}function He(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!He(t[n],r[n]))return!1;return!0}if(S(t)&&S(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!He(t[s],r[s]))return!1}return!0}return!1}function S(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Ti(t,r){if(!qr(t))return null;try{let n=await import(t),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Ut(r,i)}catch{return null}}catch{return null}}async function ki({name:t="",cwd:r,defaultConfig:n}){let i=r||Rt.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],o=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let a of o)for(let l of s){let c=qe(i,`${a}${l}`),f=await Ti(c,n);if(f!==null)return f}try{let a=qe(i,"package.json");if(qr(a)){let c=(await import(a))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Ut(n,c)}catch{}}}catch{}return n}function Ai(t,r={}){let n=Je.cwd();while(n.includes("storage"))n=ar(n,"..");let i=ar(n,t||"");if(r?.relative)return _n(Je.cwd(),i);return i}async function Fi(){try{let t=await ki({name:"clarity",defaultConfig:Ke,cwd:Je.cwd(),endpoint:"",headers:{}});return{...Ke,...t}}catch{return Ke}}function k(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Oi(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X<"u"){let t=X.type;if(t==="renderer"||t==="worker")return!1;return!!(X.versions&&(X.versions.node||X.versions.bun))}return!1}class Hr{async format(t){let r=await Oi(),n=await this.getMetadata(r);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:r}=await import("os");return{pid:ue.pid,hostname:r(),environment:ue.env.NODE_ENV||"development",platform:ue.platform,version:ue.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ue.env.NODE_ENV||ue.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ze{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(t,r={}){this.name=t,this.config={...Dt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new Hr,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Ve,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Ve};return{...Ve,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:Dt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await Un(this.config.logDirectory,ur.F_OK|ur.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Gn(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:re.from(t);try{if(!gt(this.currentLogFile))await ht(this.currentLogFile,"",{mode:420});if(s=fr(this.currentLogFile,"a",420),zn(s,c,{flag:"a"}),lr(s),s!==void 0)ut(s),s=void 0;if((await le(this.currentLogFile)).size===0){if(await ht(this.currentLogFile,c,{flag:"w",mode:420}),(await le(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{ut(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 fe(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 fe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return fe(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return ft(16).toString("hex")}generateKey(){return ft(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:r}=this.getCurrentKey(),n=ft(16),i=Kn("aes-256-gcm",r,n),s=re.concat([i.update(t,"utf8"),i.final()]),o=i.getAuthTag();return{encrypted:re.concat([n,s,o]),iv:n}}async compressData(t){return new Promise((r,n)=>{let i=hr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(re.from(re.concat(s)))),i.on("error",n),i.write(t),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(k())return;let t=await le(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await ke(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await le(n).catch(()=>null))try{if(await gr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Ae(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await ht(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await le(n).catch(()=>null))await gr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await ke(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await Ae(fe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=cr(t),i=Wn(r),s=hr();await Jn(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(r),console.log(r);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:r,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),gt(this.currentLogFile))try{let t=fr(this.currentLogFile,"r+");lr(t),ut(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await ke(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await Ae(fe(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?x.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=N.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${x.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}async log(t,r,...n){let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);if(this.fancy&&!k()){let f=an[t],u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",g;switch(t){case"debug":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.gray(a),level:t}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g);break;case"success":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.green(a),level:t}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g),l){let m=l.split(`
|
|
3
3
|
`);for(let h of m)if(h.trim()&&!h.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:x.gray(` ${h}`),level:t,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${o} ${this.environment}.${t.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(t))return;let c=`${o} ${this.environment}.${t.toUpperCase()}: ${a}
|
|
4
4
|
`;if(l)c+=`${l}
|
|
5
5
|
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(t){let r=performance.now();if(this.fancy&&!k()){let n=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:x.blue("\u25D0"),tag:n,message:`${x.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let i=performance.now(),s=Math.round(i-r),o=`${t} completed in ${s}ms`,a=new Date,l=this.formatConsoleTimestamp(a),f=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${o}`;if(n)f+=` ${JSON.stringify(n)}`;if(f+=`
|
|
@@ -58,5 +58,5 @@ export type ConfigOf = Config
|
|
|
58
58
|
`;n+=`| Variable | Type | Description | Example |
|
|
59
59
|
`,n+=`|----------|------|-------------|----------|
|
|
60
60
|
`;for(let i of t)n+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
61
|
-
`;return n}}var Kr=Ns(import.meta.url),Ie=new Map,kt=new Set;function $n(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="ENOTDIR")}async function Cn(t){let r=Ds(t),n=Ie.get(r),i,s=new Promise((o)=>{i=o});Ie.set(r,s),await n;try{if(Ps(r),Kr.cache[r]?.loaded===!0||kt.has(r))delete Kr.cache[r];try{let o=await import(Ms(r).href);return kt.delete(r),o}catch(o){throw kt.add(r),o}}finally{if(i(),Ie.get(r)===s)Ie.delete(r)}}function Ls(t,r,n={}){return bn(t,r,n,new WeakMap)}function bn(t,r,n,i){let{arrayMergeMode:s="replace",skipNullish:o=!1,customMerger:a}=n;if(r===null||r===void 0)return o?t:r;if(a){let l=a(t,r);if(l!==void 0)return l}if(Array.isArray(r)||Array.isArray(t))return En(t,r,s,i);if(!W(r)||!W(t))return r;return Ks(t,r,n,i)}function En(t,r,n,i){if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(t)&&!Array.isArray(r))return r;if(Array.isArray(r)&&Array.isArray(t))switch(n){case"replace":return r;case"concat":return Bs(t,r);case"smart":return Is(t,r,i);default:return r}return r}function Bs(t,r){let n=[...r];for(let i of t)if(!n.some((s)=>Kt(s,i)))n.push(i);return n}function Is(t,r,n){if(r.length===0)return t;if(t.length===0)return r;if(W(r[0])&&W(t[0]))return _s(t,r,n);if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}function _s(t,r,n){let i=[...r];for(let s of t){if(!W(s)){i.push(s);continue}let o=["id","name","key","path","type"],a=!1;for(let l of o)if(l in s){if(i.find((f)=>W(f)&&(l in f)&&f[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function Ks(t,r,n,i){let s=r;if(W(s)&&i.has(s))return i.get(s);let o={...t};if(W(s))i.set(s,o);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],c=o[a];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[a]=l;continue}if(W(l)&&W(c))o[a]=bn(c,l,n,i);else if(Array.isArray(l)||Array.isArray(c))o[a]=En(c,l,n.arrayMergeMode||"smart",i);else o[a]=l}return o}function xn(t,r,n="replace"){return Ls(t,r,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Kt(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!Kt(t[n],r[n]))return!1;return!0}if(W(t)&&W(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!Kt(t[s],r[s]))return!1}return!0}return!1}function W(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Sn{extensions=Ur;async loadFromPath(t,r,n={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:o,trackPerformance:a=!0,verbose:l=!1,strictDiscovery:c=!1}=n;if(s){let u=Ue.getWithFileCheck("file",t);if(u){if(l)console.log(`Configuration loaded from cache: ${t}`);return u}}let f=async()=>{try{try{js(t)}catch(T){if($n(T)||!c)return null;throw T}let u=await Cn(t),g=Object.hasOwn(u,"default"),m=Object.keys(u).length>0,h=g?u.default:u;if(!g&&!m)throw new se(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new se(t,Error("Configuration must export a valid object"),"unknown");let p={config:xn(r,h,i),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(s)Ue.setWithFileCheck("file",p,t,o);return p}catch(u){throw u instanceof Error?ne.configLoad(t,u):ne.configLoad(t,Error(String(u)))}};if(a)return Vt.track("loadFromPath",f,{path:t});return f()}async tryLoadFromPaths(t,r,n={}){for(let i of t)try{let s=await this.loadFromPath(i,r,n);if(s)return s}catch(s){if(s instanceof se)throw s;if(n.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(t,r,n){return Rn({name:t,directory:r,alias:n})}generateNamePatterns(t,r){return Gr({name:t,alias:r})}checkFileAccess(t){return Rs(async()=>At(t),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,r,n){let i=[];if(!At(t))return i;if(r||n){let s=this.generateNamePatterns(r||"",n);for(let o of s)for(let a of this.extensions){let l=Vr(t,`${o}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),o=s(t);for(let a of o)if(this.looksLikeConfigFile(a)){let l=Vr(t,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}looksLikeConfigFile(t){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((n)=>n.test(t))}async validateConfigFile(t){let r=[];try{if(!At(t))return r.push("Configuration file does not exist"),r;let n=await import(t),i=n.default||n;if(i===void 0)r.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)r.push("Configuration must be an object");else if(Array.isArray(i))r.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),o=s(t,"utf8");JSON.parse(o)}catch(s){r.push(`Invalid JSON syntax: ${s}`)}}catch(n){r.push(`Failed to load configuration file: ${n}`)}return r}async getFileModificationTime(t){try{let{statSync:r}=await import("fs");return r(t).mtime}catch{return null}}async preloadConfigurations(t,r={}){let n=new Map;return await Promise.allSettled(t.map(async(i)=>{try{let s=await this.loadFromPath(i,{},r);if(s)n.set(i,s.config)}catch(s){if(r.verbose)console.warn(`Failed to preload ${i}:`,s)}})),n}}var Ws=/^https?:\/\//;class Tn{async validateConfiguration(t,r,n={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:o=!0,customRules:a=[],trackPerformance:l=!0,verbose:c=!1}=n,f=async()=>{let u=[],g=[],m={stopOnFirstError:i,validateRequired:s,validateTypes:o,customRules:a,trackPerformance:l,verbose:c};try{if(typeof r==="string")return await this.validateWithSchemaFile(t,r,m);else if(Array.isArray(r))return this.validateWithRules(t,[...r,...a],m);else return this.validateWithJSONSchema(t,r,m)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:g}}};if(l)return await Vt.track("validateConfiguration",f);return f()}async validateWithSchemaFile(t,r,n){try{if(!Vs(r))throw new nt(r,[{path:"",message:"Schema file does not exist"}]);let i=await Cn(r),s=Object.hasOwn(i,"default")?i.default:i;if(Array.isArray(s))return this.validateWithRules(t,s,n);else{if(typeof s!=="object"||s===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(t,s,n)}}catch(i){throw new nt(r,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(t,r,n){let i=[],s=[];return this.validateObjectAgainstSchema(t,r,"",i,s,n),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(t,r,n,i,s,o){if(o.validateTypes&&r.type){let a=Array.isArray(t)?"array":typeof t,l=Array.isArray(r.type)?r.type:[r.type];if(!l.includes(a)){if(i.push({path:n,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),o.stopOnFirstError)return}}if(r.enum&&!r.enum.includes(t)){if(i.push({path:n,message:`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"}),o.stopOnFirstError)return}if(typeof t==="string"){if(r.minLength!==void 0&&t.length<r.minLength)i.push({path:n,message:`String length must be at least ${r.minLength}`,expected:`>= ${r.minLength}`,actual:t.length,rule:"minLength"});if(r.maxLength!==void 0&&t.length>r.maxLength)i.push({path:n,message:`String length must not exceed ${r.maxLength}`,expected:`<= ${r.maxLength}`,actual:t.length,rule:"maxLength"});if(r.pattern){if(!new RegExp(r.pattern).test(t))i.push({path:n,message:`String does not match pattern ${r.pattern}`,expected:r.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(r.minimum!==void 0&&t<r.minimum)i.push({path:n,message:`Value must be at least ${r.minimum}`,expected:`>= ${r.minimum}`,actual:t,rule:"minimum"});if(r.maximum!==void 0&&t>r.maximum)i.push({path:n,message:`Value must not exceed ${r.maximum}`,expected:`<= ${r.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&r.items)for(let a=0;a<t.length;a++){let l=n?`${n}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(t[a],r.items,l,i,s,o),o.stopOnFirstError&&i.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let a=t;if(o.validateRequired&&r.required){for(let l of r.required)if(!(l in a)){if(i.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(r.properties){for(let[l,c]of Object.entries(r.properties))if(l in a){let f=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],c,f,i,s,o),o.stopOnFirstError&&i.length>0)return}}if(r.additionalProperties===!1){let l=new Set(Object.keys(r.properties||{}));for(let c of Object.keys(a))if(!l.has(c))s.push({path:n?`${n}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,r,n){let i=[],s=[];for(let o of r)try{let a=this.getValueByPath(t,o.path),l=this.validateWithRule(a,o,o.path);if(i.push(...l),n.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:o.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(t,r,n){let i=[];if(r.required&&(t===void 0||t===null))return i.push({path:n,message:r.message||`Property '${n}' is required`,expected:"required",rule:"required"}),i;if(t===void 0||t===null)return i;if(r.type){let s=Array.isArray(t)?"array":typeof t;if(s!==r.type)i.push({path:n,message:r.message||`Expected type ${r.type}, got ${s}`,expected:r.type,actual:s,rule:"type"})}if(r.min!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s<r.min)i.push({path:n,message:r.message||`Value must be at least ${r.min}`,expected:`>= ${r.min}`,actual:s,rule:"min"})}if(r.max!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s>r.max)i.push({path:n,message:r.message||`Value must not exceed ${r.max}`,expected:`<= ${r.max}`,actual:s,rule:"max"})}if(r.pattern&&typeof t==="string"){if(!r.pattern.test(t))i.push({path:n,message:r.message||`Value does not match pattern ${r.pattern}`,expected:r.pattern.toString(),actual:t,rule:"pattern"})}if(r.enum&&!r.enum.includes(t))i.push({path:n,message:r.message||`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"});if(r.validator){let s=r.validator(t);if(s)i.push({path:n,message:r.message||s,rule:"custom"})}return i}getValueByPath(t,r){if(!r)return t;let n=r.split("."),i=t;for(let s of n)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(t){let r=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of n){let[,s,o,a]=i;r.push({path:s,required:!o,type:this.mapTypeScriptType(a)})}return r}mapTypeScriptType(t){switch(t.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:Ws},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var q=new at("bunfig",{showTags:!0});function zs(t){if(!t)return"";let r=Array.isArray(t)?t.filter(Boolean):[t];if(r.length===0)return"";if(r.length===1)return` or alias "${r[0]}"`;return` or aliases ${r.map((n)=>`"${n}"`).join(", ")}`}class kn{fileLoader=new Sn;envProcessor=new Xt;validator=new Tn;async loadConfig(t){let r=Date.now(),{cache:n,performance:i,schema:s,validate:o,...a}=t,l=a.errorPolicy==="throw"?{...n,enabled:!1}:n;try{if(l?.enabled){let f=this.checkCache(a.name||"",a);if(f)return f}let c;try{c=await this.loadConfigurationStrategies(a,!0,l)}catch(f){if(a.configFile||a.errorPolicy==="throw"&&!(f instanceof we))throw f;let u=a.__strictErrorHandling;if(f instanceof we){if(u&&a.errorPolicy!=="throw")throw f;c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(f instanceof se){let g=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),m=!g&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),h=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(u&&(h||g))throw f;if(m&&(!u||!h))c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(s||o)await this.validateConfiguration(c.config,s,o,a.name);if(l?.enabled&&c)this.cacheResult(a.name||"",c,l,a);if(i?.enabled){let f={operation:"loadConfig",duration:Date.now()-r,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(f);if(i.slowThreshold&&f.duration>i.slowThreshold)q.warn(`Slow configuration loading detected: ${f.duration}ms for ${a.name}`);c.metrics=f}return c}catch(c){if(c instanceof we)throw c;let f=Date.now()-r;throw q.error(`Configuration loading failed after ${f}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,r=!1,n){let{name:i="",alias:s,configFile:o,cwd:a,configDir:l,defaultConfig:c,checkEnv:f=!0,arrayStrategy:u="replace",verbose:g=!1}=t,m=a||it.cwd(),h=[];if(o){let A=Y(m,o);h.push(A);let z=f?$e(i,c,g):c,_=await this.fileLoader.tryLoadFromPaths([A],z,{arrayStrategy:u,verbose:g,cacheTtl:n?.ttl,useCache:n?.enabled!==!1&&(!n?.ttl||n.ttl>100),strictDiscovery:!0});if(!_)throw ne.configNotFound(i||o,h,s);if(g)q.success(`Configuration loaded from explicit path: ${A}`);return this.finalizeResult(_,h,f,i,g)}let y=await this.loadLocalConfiguration(i,s,m,l,c,u,g,f,n,t.errorPolicy==="throw");if(y)return h.push(...this.getLocalSearchPaths(i,s,m,l)),this.finalizeResult(y,h,f,i,g);let d=await this.loadHomeConfiguration(i,s,c,u,g,f,n,t.errorPolicy==="throw");if(d)return h.push(...this.getHomeSearchPaths(i,s)),this.finalizeResult(d,h,f,i,g);let p=await this.loadPackageJsonConfiguration(i,s,m,c,u,g,f,t.errorPolicy);if(p)return h.push(Y(m,"package.json")),this.finalizeResult(p,h,f,i,g);if(h.push(...this.getAllSearchPaths(i,s,m,l)),r)throw ne.configNotFound(i,h,s);return{...await this.applyEnvironmentVariables(i,c,f,g),warnings:[`No configuration file found for "${i}"${zs(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,r,n,i,s,o,a,l,c,f=!1){let u=l?$e(t,s,a):s,g=this.getLocalDirectories(n,i);for(let m of g){if(a)q.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(t,m,r),y=await this.fileLoader.tryLoadFromPaths(h,u,{arrayStrategy:o,verbose:a,cacheTtl:c?.ttl,useCache:c?.enabled!==!1&&(!c?.ttl||c.ttl>100),strictDiscovery:f});if(y){if(a)q.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,r,n,i,s,o,a,l=!1){if(!t)return null;let c=o?$e(t,n,s):n,f=[Y(ae(),".config",t),Y(ae(),".config"),ae()];for(let u of f){if(s)q.info(`Checking home directory: ${u}`);let g=this.fileLoader.generateConfigPaths(t,u,r),m=await this.fileLoader.tryLoadFromPaths(g,c,{arrayStrategy:i,verbose:s,cacheTtl:a?.ttl,useCache:a?.enabled!==!1&&(!a?.ttl||a.ttl>100),strictDiscovery:l});if(m){if(s)q.success(`Configuration loaded from home directory: ${m.source.path}`);return m}}return null}async loadPackageJsonConfiguration(t,r,n,i,s,o,a,l){let c=a?$e(t,i,o):i,f=Y(n,"package.json"),u=l==="throw";try{let g=JSON.parse(Dn(f,"utf8"));if(typeof g!=="object"||g===null||Array.isArray(g))throw Error("package.json must contain an object");let m=g,h=r===void 0?[]:Array.isArray(r)?r:[r],d=[t,...h.filter(Boolean)].find((T)=>Object.hasOwn(m,T)&&(u||Boolean(m[T])));if(d===void 0)return null;let p=m[d];if(typeof p!=="object"||p===null||Array.isArray(p))throw Error(`Configuration field "${d}" must contain an object`);if(o)q.success(`Configuration loaded from package.json: ${d}`);return{config:xn(c,p,s),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(g){if($n(g))return null;if(u)throw ne.configLoad(f,g instanceof Error?g:Error(String(g)));if(o)q.warn("Failed to load package.json:",[g instanceof Error?g:Error(String(g))]);return null}}async applyEnvironmentVariables(t,r,n,i){if(!n||!t||typeof r!=="object"||r===null||Array.isArray(r))return{config:r,source:{type:"default",priority:10,timestamp:new Date}};return{config:$e(t,r,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,r,n,i,s){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,r,n,i){let s=[];if(n){let o=n(t);if(o)s.push(...o)}if(r){let o=await this.validator.validateConfiguration(t,r);if(!o.isValid)s.push(...o.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw ne.configValidation(i||"unknown",s,i)}checkCache(t,r){let n=this.generateCacheKey(t,r);return Ue.get(n)||null}cacheResult(t,r,n,i){let s=this.generateCacheKey(t,i);Ue.set(s,r,void 0,n.ttl)}generateCacheKey(t,r){let n=[t];if(r.alias){let i=Array.isArray(r.alias)?r.alias.join(","):r.alias;n.push(`alias:${i}`)}if(r.cwd)n.push(`cwd:${r.cwd}`);if(r.configFile)n.push(`configFile:${r.configFile}`);if(r.configDir)n.push(`configDir:${r.configDir}`);if("checkEnv"in r)n.push(`checkEnv:${r.checkEnv}`);return n.join("|")}getLocalDirectories(t,r){return Pn({cwd:t,configDir:r})}getAllSearchPaths(t,r,n,i){let s=[];return s.push(...this.getLocalSearchPaths(t,r,n,i)),s.push(...this.getHomeSearchPaths(t,r)),s.push(Y(n,"package.json")),s}getLocalSearchPaths(t,r,n,i){let s=this.getLocalDirectories(n,i),o=[];for(let a of s)o.push(...this.fileLoader.generateConfigPaths(t,a,r));return o}getHomeSearchPaths(t,r){if(!t)return[];let n=[Y(ae(),".config",t),Y(ae(),".config"),ae()],i=[];for(let s of n)i.push(...this.fileLoader.generateConfigPaths(t,s,r));return i}async loadConfigWithResult(t){return this.loadConfig(t)}}var Ft=new kn;async function An(t){let r="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let i;if(n)i=await Ft.loadConfig(t);else i=await Ft.loadConfig({...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??r}catch(i){if(t.configFile||t.errorPolicy==="throw")throw i;let s=i instanceof Error?i.message:String(i);if(!(i instanceof we||i instanceof se||i instanceof Ht||s.includes("config"))&&t.verbose)q.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=n?{...t,defaultConfig:r}:{...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Ft.applyEnvironmentVariables(a.name||"",r,!0,a.verbose||!1))?.config??r;return r}}function $e(t,r,n=!1){let i=new Xt,s=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=[`${s}_${g.join("_").toUpperCase()}`,`${s}_${g.map((d)=>d.toUpperCase()).join("")}`,`${s}_${g.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,y;for(let d of m)if(h=it.env[d],h!==void 0){y=d;break}if(h!==void 0&&y)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let d=Number(h);if(!Number.isNaN(d))c[f]=d}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((d)=>d.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,g)}return c}return o(r)}var Ka=Y(it.cwd(),"config"),Va=Y(it.cwd(),"src/generated");var j={cwd:Qt.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",moduleSpecifierMode:"preserve",verbose:!1,importOrder:["bun"],declarationMap:!1},Js=["dtsx.config.ts","dtsx.config.js","dtsx.config.mjs","dtsx.config.mts","dts.config.ts","dts.config.js"];async function qs(t=Qt.cwd()){for(let r of Js){let n=Fn(t,r);if(Us(n))try{let s=await import(Gs(n).href),o=s.default||s.config||s,a=typeof o==="function"?await o():o;return{...j,...a,cwd:t}}catch(i){let s=i instanceof Error?i.message:String(i);e.warn(`Failed to load config from ${r}: ${s}`)}}return null}var ct=new Map;async function oa(t){let r=Fn(t??Qt.cwd()),n=ct.get(r);if(!n)n=(async()=>{let i=await qs(r);if(i)return i;return{...await An({name:"dts",cwd:r,defaultConfig:{...j,cwd:r}}),cwd:r}})(),ct.set(r,n);try{return await n}catch(i){throw ct.delete(r),i}}function aa(){ct.clear()}function ca(t){return{...j,...t}}function la(t){return async()=>{let r=await t();return{...j,...r}}}var D=j;
|
|
62
|
-
export{j,
|
|
61
|
+
`;return n}}var Kr=Ns(import.meta.url),Ie=new Map,kt=new Set;function $n(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="ENOTDIR")}async function Cn(t){let r=Ds(t),n=Ie.get(r),i,s=new Promise((o)=>{i=o});Ie.set(r,s),await n;try{if(Ps(r),Kr.cache[r]?.loaded===!0||kt.has(r))delete Kr.cache[r];try{let o=await import(Ms(r).href);return kt.delete(r),o}catch(o){throw kt.add(r),o}}finally{if(i(),Ie.get(r)===s)Ie.delete(r)}}function Ls(t,r,n={}){return bn(t,r,n,new WeakMap)}function bn(t,r,n,i){let{arrayMergeMode:s="replace",skipNullish:o=!1,customMerger:a}=n;if(r===null||r===void 0)return o?t:r;if(a){let l=a(t,r);if(l!==void 0)return l}if(Array.isArray(r)||Array.isArray(t))return En(t,r,s,i);if(!W(r)||!W(t))return r;return Ks(t,r,n,i)}function En(t,r,n,i){if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(t)&&!Array.isArray(r))return r;if(Array.isArray(r)&&Array.isArray(t))switch(n){case"replace":return r;case"concat":return Bs(t,r);case"smart":return Is(t,r,i);default:return r}return r}function Bs(t,r){let n=[...r];for(let i of t)if(!n.some((s)=>Kt(s,i)))n.push(i);return n}function Is(t,r,n){if(r.length===0)return t;if(t.length===0)return r;if(W(r[0])&&W(t[0]))return _s(t,r,n);if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}function _s(t,r,n){let i=[...r];for(let s of t){if(!W(s)){i.push(s);continue}let o=["id","name","key","path","type"],a=!1;for(let l of o)if(l in s){if(i.find((f)=>W(f)&&(l in f)&&f[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function Ks(t,r,n,i){let s=r;if(W(s)&&i.has(s))return i.get(s);let o={...t};if(W(s))i.set(s,o);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],c=o[a];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[a]=l;continue}if(W(l)&&W(c))o[a]=bn(c,l,n,i);else if(Array.isArray(l)||Array.isArray(c))o[a]=En(c,l,n.arrayMergeMode||"smart",i);else o[a]=l}return o}function xn(t,r,n="replace"){return Ls(t,r,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Kt(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!Kt(t[n],r[n]))return!1;return!0}if(W(t)&&W(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!Kt(t[s],r[s]))return!1}return!0}return!1}function W(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Sn{extensions=Ur;async loadFromPath(t,r,n={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:o,trackPerformance:a=!0,verbose:l=!1,strictDiscovery:c=!1}=n;if(s){let u=Ue.getWithFileCheck("file",t);if(u){if(l)console.log(`Configuration loaded from cache: ${t}`);return u}}let f=async()=>{try{try{js(t)}catch(T){if($n(T)||!c)return null;throw T}let u=await Cn(t),g=Object.hasOwn(u,"default"),m=Object.keys(u).length>0,h=g?u.default:u;if(!g&&!m)throw new se(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new se(t,Error("Configuration must export a valid object"),"unknown");let p={config:xn(r,h,i),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(s)Ue.setWithFileCheck("file",p,t,o);return p}catch(u){throw u instanceof Error?ne.configLoad(t,u):ne.configLoad(t,Error(String(u)))}};if(a)return Vt.track("loadFromPath",f,{path:t});return f()}async tryLoadFromPaths(t,r,n={}){for(let i of t)try{let s=await this.loadFromPath(i,r,n);if(s)return s}catch(s){if(s instanceof se)throw s;if(n.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(t,r,n){return Rn({name:t,directory:r,alias:n})}generateNamePatterns(t,r){return Gr({name:t,alias:r})}checkFileAccess(t){return Rs(async()=>At(t),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,r,n){let i=[];if(!At(t))return i;if(r||n){let s=this.generateNamePatterns(r||"",n);for(let o of s)for(let a of this.extensions){let l=Vr(t,`${o}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),o=s(t);for(let a of o)if(this.looksLikeConfigFile(a)){let l=Vr(t,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}looksLikeConfigFile(t){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((n)=>n.test(t))}async validateConfigFile(t){let r=[];try{if(!At(t))return r.push("Configuration file does not exist"),r;let n=await import(t),i=n.default||n;if(i===void 0)r.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)r.push("Configuration must be an object");else if(Array.isArray(i))r.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),o=s(t,"utf8");JSON.parse(o)}catch(s){r.push(`Invalid JSON syntax: ${s}`)}}catch(n){r.push(`Failed to load configuration file: ${n}`)}return r}async getFileModificationTime(t){try{let{statSync:r}=await import("fs");return r(t).mtime}catch{return null}}async preloadConfigurations(t,r={}){let n=new Map;return await Promise.allSettled(t.map(async(i)=>{try{let s=await this.loadFromPath(i,{},r);if(s)n.set(i,s.config)}catch(s){if(r.verbose)console.warn(`Failed to preload ${i}:`,s)}})),n}}var Ws=/^https?:\/\//;class Tn{async validateConfiguration(t,r,n={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:o=!0,customRules:a=[],trackPerformance:l=!0,verbose:c=!1}=n,f=async()=>{let u=[],g=[],m={stopOnFirstError:i,validateRequired:s,validateTypes:o,customRules:a,trackPerformance:l,verbose:c};try{if(typeof r==="string")return await this.validateWithSchemaFile(t,r,m);else if(Array.isArray(r))return this.validateWithRules(t,[...r,...a],m);else return this.validateWithJSONSchema(t,r,m)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:g}}};if(l)return await Vt.track("validateConfiguration",f);return f()}async validateWithSchemaFile(t,r,n){try{if(!Vs(r))throw new nt(r,[{path:"",message:"Schema file does not exist"}]);let i=await Cn(r),s=Object.hasOwn(i,"default")?i.default:i;if(Array.isArray(s))return this.validateWithRules(t,s,n);else{if(typeof s!=="object"||s===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(t,s,n)}}catch(i){throw new nt(r,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(t,r,n){let i=[],s=[];return this.validateObjectAgainstSchema(t,r,"",i,s,n),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(t,r,n,i,s,o){if(o.validateTypes&&r.type){let a=Array.isArray(t)?"array":typeof t,l=Array.isArray(r.type)?r.type:[r.type];if(!l.includes(a)){if(i.push({path:n,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),o.stopOnFirstError)return}}if(r.enum&&!r.enum.includes(t)){if(i.push({path:n,message:`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"}),o.stopOnFirstError)return}if(typeof t==="string"){if(r.minLength!==void 0&&t.length<r.minLength)i.push({path:n,message:`String length must be at least ${r.minLength}`,expected:`>= ${r.minLength}`,actual:t.length,rule:"minLength"});if(r.maxLength!==void 0&&t.length>r.maxLength)i.push({path:n,message:`String length must not exceed ${r.maxLength}`,expected:`<= ${r.maxLength}`,actual:t.length,rule:"maxLength"});if(r.pattern){if(!new RegExp(r.pattern).test(t))i.push({path:n,message:`String does not match pattern ${r.pattern}`,expected:r.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(r.minimum!==void 0&&t<r.minimum)i.push({path:n,message:`Value must be at least ${r.minimum}`,expected:`>= ${r.minimum}`,actual:t,rule:"minimum"});if(r.maximum!==void 0&&t>r.maximum)i.push({path:n,message:`Value must not exceed ${r.maximum}`,expected:`<= ${r.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&r.items)for(let a=0;a<t.length;a++){let l=n?`${n}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(t[a],r.items,l,i,s,o),o.stopOnFirstError&&i.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let a=t;if(o.validateRequired&&r.required){for(let l of r.required)if(!(l in a)){if(i.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(r.properties){for(let[l,c]of Object.entries(r.properties))if(l in a){let f=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],c,f,i,s,o),o.stopOnFirstError&&i.length>0)return}}if(r.additionalProperties===!1){let l=new Set(Object.keys(r.properties||{}));for(let c of Object.keys(a))if(!l.has(c))s.push({path:n?`${n}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,r,n){let i=[],s=[];for(let o of r)try{let a=this.getValueByPath(t,o.path),l=this.validateWithRule(a,o,o.path);if(i.push(...l),n.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:o.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(t,r,n){let i=[];if(r.required&&(t===void 0||t===null))return i.push({path:n,message:r.message||`Property '${n}' is required`,expected:"required",rule:"required"}),i;if(t===void 0||t===null)return i;if(r.type){let s=Array.isArray(t)?"array":typeof t;if(s!==r.type)i.push({path:n,message:r.message||`Expected type ${r.type}, got ${s}`,expected:r.type,actual:s,rule:"type"})}if(r.min!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s<r.min)i.push({path:n,message:r.message||`Value must be at least ${r.min}`,expected:`>= ${r.min}`,actual:s,rule:"min"})}if(r.max!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s>r.max)i.push({path:n,message:r.message||`Value must not exceed ${r.max}`,expected:`<= ${r.max}`,actual:s,rule:"max"})}if(r.pattern&&typeof t==="string"){if(!r.pattern.test(t))i.push({path:n,message:r.message||`Value does not match pattern ${r.pattern}`,expected:r.pattern.toString(),actual:t,rule:"pattern"})}if(r.enum&&!r.enum.includes(t))i.push({path:n,message:r.message||`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"});if(r.validator){let s=r.validator(t);if(s)i.push({path:n,message:r.message||s,rule:"custom"})}return i}getValueByPath(t,r){if(!r)return t;let n=r.split("."),i=t;for(let s of n)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(t){let r=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of n){let[,s,o,a]=i;r.push({path:s,required:!o,type:this.mapTypeScriptType(a)})}return r}mapTypeScriptType(t){switch(t.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:Ws},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var q=new at("bunfig",{showTags:!0});function zs(t){if(!t)return"";let r=Array.isArray(t)?t.filter(Boolean):[t];if(r.length===0)return"";if(r.length===1)return` or alias "${r[0]}"`;return` or aliases ${r.map((n)=>`"${n}"`).join(", ")}`}class kn{fileLoader=new Sn;envProcessor=new Xt;validator=new Tn;async loadConfig(t){let r=Date.now(),{cache:n,performance:i,schema:s,validate:o,...a}=t,l=a.errorPolicy==="throw"?{...n,enabled:!1}:n;try{if(l?.enabled){let f=this.checkCache(a.name||"",a);if(f)return f}let c;try{c=await this.loadConfigurationStrategies(a,!0,l)}catch(f){if(a.configFile||a.errorPolicy==="throw"&&!(f instanceof we))throw f;let u=a.__strictErrorHandling;if(f instanceof we){if(u&&a.errorPolicy!=="throw")throw f;c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(f instanceof se){let g=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),m=!g&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),h=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(u&&(h||g))throw f;if(m&&(!u||!h))c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(s||o)await this.validateConfiguration(c.config,s,o,a.name);if(l?.enabled&&c)this.cacheResult(a.name||"",c,l,a);if(i?.enabled){let f={operation:"loadConfig",duration:Date.now()-r,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(f);if(i.slowThreshold&&f.duration>i.slowThreshold)q.warn(`Slow configuration loading detected: ${f.duration}ms for ${a.name}`);c.metrics=f}return c}catch(c){if(c instanceof we)throw c;let f=Date.now()-r;throw q.error(`Configuration loading failed after ${f}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,r=!1,n){let{name:i="",alias:s,configFile:o,cwd:a,configDir:l,defaultConfig:c,checkEnv:f=!0,arrayStrategy:u="replace",verbose:g=!1}=t,m=a||it.cwd(),h=[];if(o){let A=Y(m,o);h.push(A);let z=f?$e(i,c,g):c,_=await this.fileLoader.tryLoadFromPaths([A],z,{arrayStrategy:u,verbose:g,cacheTtl:n?.ttl,useCache:n?.enabled!==!1&&(!n?.ttl||n.ttl>100),strictDiscovery:!0});if(!_)throw ne.configNotFound(i||o,h,s);if(g)q.success(`Configuration loaded from explicit path: ${A}`);return this.finalizeResult(_,h,f,i,g)}let y=await this.loadLocalConfiguration(i,s,m,l,c,u,g,f,n,t.errorPolicy==="throw");if(y)return h.push(...this.getLocalSearchPaths(i,s,m,l)),this.finalizeResult(y,h,f,i,g);let d=await this.loadHomeConfiguration(i,s,c,u,g,f,n,t.errorPolicy==="throw");if(d)return h.push(...this.getHomeSearchPaths(i,s)),this.finalizeResult(d,h,f,i,g);let p=await this.loadPackageJsonConfiguration(i,s,m,c,u,g,f,t.errorPolicy);if(p)return h.push(Y(m,"package.json")),this.finalizeResult(p,h,f,i,g);if(h.push(...this.getAllSearchPaths(i,s,m,l)),r)throw ne.configNotFound(i,h,s);return{...await this.applyEnvironmentVariables(i,c,f,g),warnings:[`No configuration file found for "${i}"${zs(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,r,n,i,s,o,a,l,c,f=!1){let u=l?$e(t,s,a):s,g=this.getLocalDirectories(n,i);for(let m of g){if(a)q.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(t,m,r),y=await this.fileLoader.tryLoadFromPaths(h,u,{arrayStrategy:o,verbose:a,cacheTtl:c?.ttl,useCache:c?.enabled!==!1&&(!c?.ttl||c.ttl>100),strictDiscovery:f});if(y){if(a)q.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,r,n,i,s,o,a,l=!1){if(!t)return null;let c=o?$e(t,n,s):n,f=[Y(ae(),".config",t),Y(ae(),".config"),ae()];for(let u of f){if(s)q.info(`Checking home directory: ${u}`);let g=this.fileLoader.generateConfigPaths(t,u,r),m=await this.fileLoader.tryLoadFromPaths(g,c,{arrayStrategy:i,verbose:s,cacheTtl:a?.ttl,useCache:a?.enabled!==!1&&(!a?.ttl||a.ttl>100),strictDiscovery:l});if(m){if(s)q.success(`Configuration loaded from home directory: ${m.source.path}`);return m}}return null}async loadPackageJsonConfiguration(t,r,n,i,s,o,a,l){let c=a?$e(t,i,o):i,f=Y(n,"package.json"),u=l==="throw";try{let g=JSON.parse(Dn(f,"utf8"));if(typeof g!=="object"||g===null||Array.isArray(g))throw Error("package.json must contain an object");let m=g,h=r===void 0?[]:Array.isArray(r)?r:[r],d=[t,...h.filter(Boolean)].find((T)=>Object.hasOwn(m,T)&&(u||Boolean(m[T])));if(d===void 0)return null;let p=m[d];if(typeof p!=="object"||p===null||Array.isArray(p))throw Error(`Configuration field "${d}" must contain an object`);if(o)q.success(`Configuration loaded from package.json: ${d}`);return{config:xn(c,p,s),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(g){if($n(g))return null;if(u)throw ne.configLoad(f,g instanceof Error?g:Error(String(g)));if(o)q.warn("Failed to load package.json:",[g instanceof Error?g:Error(String(g))]);return null}}async applyEnvironmentVariables(t,r,n,i){if(!n||!t||typeof r!=="object"||r===null||Array.isArray(r))return{config:r,source:{type:"default",priority:10,timestamp:new Date}};return{config:$e(t,r,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,r,n,i,s){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,r,n,i){let s=[];if(n){let o=n(t);if(o)s.push(...o)}if(r){let o=await this.validator.validateConfiguration(t,r);if(!o.isValid)s.push(...o.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw ne.configValidation(i||"unknown",s,i)}checkCache(t,r){let n=this.generateCacheKey(t,r);return Ue.get(n)||null}cacheResult(t,r,n,i){let s=this.generateCacheKey(t,i);Ue.set(s,r,void 0,n.ttl)}generateCacheKey(t,r){let n=[t];if(r.alias){let i=Array.isArray(r.alias)?r.alias.join(","):r.alias;n.push(`alias:${i}`)}if(r.cwd)n.push(`cwd:${r.cwd}`);if(r.configFile)n.push(`configFile:${r.configFile}`);if(r.configDir)n.push(`configDir:${r.configDir}`);if("checkEnv"in r)n.push(`checkEnv:${r.checkEnv}`);return n.join("|")}getLocalDirectories(t,r){return Pn({cwd:t,configDir:r})}getAllSearchPaths(t,r,n,i){let s=[];return s.push(...this.getLocalSearchPaths(t,r,n,i)),s.push(...this.getHomeSearchPaths(t,r)),s.push(Y(n,"package.json")),s}getLocalSearchPaths(t,r,n,i){let s=this.getLocalDirectories(n,i),o=[];for(let a of s)o.push(...this.fileLoader.generateConfigPaths(t,a,r));return o}getHomeSearchPaths(t,r){if(!t)return[];let n=[Y(ae(),".config",t),Y(ae(),".config"),ae()],i=[];for(let s of n)i.push(...this.fileLoader.generateConfigPaths(t,s,r));return i}async loadConfigWithResult(t){return this.loadConfig(t)}}var Ft=new kn;async function An(t){let r="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let i;if(n)i=await Ft.loadConfig(t);else i=await Ft.loadConfig({...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??r}catch(i){if(t.configFile||t.errorPolicy==="throw")throw i;let s=i instanceof Error?i.message:String(i);if(!(i instanceof we||i instanceof se||i instanceof Ht||s.includes("config"))&&t.verbose)q.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=n?{...t,defaultConfig:r}:{...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Ft.applyEnvironmentVariables(a.name||"",r,!0,a.verbose||!1))?.config??r;return r}}function $e(t,r,n=!1){let i=new Xt,s=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=[`${s}_${g.join("_").toUpperCase()}`,`${s}_${g.map((d)=>d.toUpperCase()).join("")}`,`${s}_${g.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,y;for(let d of m)if(h=it.env[d],h!==void 0){y=d;break}if(h!==void 0&&y)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let d=Number(h);if(!Number.isNaN(d))c[f]=d}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((d)=>d.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,g)}return c}return o(r)}var Ka=Y(it.cwd(),"config"),Va=Y(it.cwd(),"src/generated");var j={cwd:Qt.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",moduleSpecifierMode:"preserve",verbose:!1,importOrder:["bun"],declarationMap:!1},Js=["dtsx.config.ts","dtsx.config.js","dtsx.config.mjs","dtsx.config.mts","dts.config.ts","dts.config.js"];async function qs(t=Qt.cwd()){for(let r of Js){let n=Fn(t,r);if(Us(n))try{let s=await import(Gs(n).href),o=s.default||s.config||s,a=typeof o==="function"?await o():o;return{...j,...a,cwd:t}}catch(i){let s=i instanceof Error?i.message:String(i);e.warn(`Failed to load config from ${r}: ${s}`)}}return null}var ct=new Map;async function aa(t){let r=Fn(t??Qt.cwd()),n=ct.get(r);if(!n)n=(async()=>{let i=await qs(r);if(i)return i;return{...await An({name:"dts",cwd:r,defaultConfig:{...j,cwd:r}}),cwd:r}})(),ct.set(r,n);try{return await n}catch(i){throw ct.delete(r),i}}function ca(){ct.clear()}function la(t){return{...j,...t}}function ua(t){return async()=>{let r=await t();return{...j,...r}}}var D=j;
|
|
62
|
+
export{j,aa,ca,la,ua,D};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{s}from"./chunk-
|
|
3
|
-
export{He,
|
|
2
|
+
import{s}from"./chunk-egmen4qn.js";class He{options;generateOptions;constructor(t={}){let{onCompile:r=!1,afterEmit:e=!0,onWatchRun:n=!1,onGenerated:o,onError:i,...a}=t;this.options={onCompile:r,afterEmit:e,onWatchRun:n,onGenerated:o,onError:i},this.generateOptions=a}apply(t){if(!this.generateOptions.outdir&&t.options.output?.path)this.generateOptions.outdir=t.options.output.path;if(!this.generateOptions.cwd&&t.options.context)this.generateOptions.cwd=t.options.context;if(!this.generateOptions.entrypoints&&t.options.entry){let e=t.options.entry;if(typeof e==="string")this.generateOptions.entrypoints=[e];else if(Array.isArray(e))this.generateOptions.entrypoints=e;else if(typeof e==="object"&&e!==null){let n=[];for(let o of Object.values(e))if(typeof o==="string")n.push(o);else if(Array.isArray(o))n.push(...o.filter((i)=>typeof i==="string"));else if(typeof o==="object"&&o!==null&&"import"in o){let i=o.import;if(typeof i==="string")n.push(i);else if(Array.isArray(i))n.push(...i)}if(n.length>0)this.generateOptions.entrypoints=n}}if(this.options.onCompile)t.hooks.compile.tap("DtsxWebpackPlugin",()=>{this.runGenerate()});if(this.options.afterEmit)t.hooks.afterEmit.tapAsync("DtsxWebpackPlugin",async(e,n)=>{await this.runGenerate(),n()});if(this.options.onWatchRun)t.hooks.watchRun.tapAsync("DtsxWebpackPlugin",async(e,n)=>{await this.runGenerate(),n()})}async runGenerate(){try{let t=await s(this.generateOptions);this.options.onGenerated?.(t)}catch(t){let r=t instanceof Error?t:Error(String(t));if(this.options.onError?.(r),!this.options.onError)console.error("[dtsx] Generation failed:",r.message)}}}function Jt(t={}){return new He(t)}var fr=Jt,Aa=He;
|
|
3
|
+
export{He,Jt,fr,Aa};
|
|
@@ -14,5 +14,5 @@ var d=null,m=null;async function P(){if(d!==null)return d;try{return m=await imp
|
|
|
14
14
|
`),s=[],a=[],i=!1,u=0;for(let o=0;o<n.length;o++){let t=n[o],p=t.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(p){i=!0,u=o;let c=p[1];s.push({line:t,source:p[2],isType:c.startsWith("import type ")||c.startsWith("import type\t")})}else if(i&&t.trim()==="")continue;else{if(i)i=!1;a.push(t)}}if(s.length===0)return r;if(e.sort)s.sort((o,t)=>{if(o.isType!==t.isType)return o.isType?1:-1;return M(o.source,t.source)});let l;if(e.group){let o=[],t=[],p=[],c=[],b=[];for(let f=0;f<s.length;f++){let g=s[f],h=g.source;if(h.charCodeAt(0)===46)b.push(g);else if(h.startsWith("node:"))o.push(g);else if(h.charCodeAt(0)===64)c.push(g);else if(h.includes("/"))p.push(g);else t.push(g)}l=[...o.map((f)=>f.line),...o.length>0&&t.length>0?[""]:[],...t.map((f)=>f.line),...(o.length>0||t.length>0)&&p.length>0?[""]:[],...p.map((f)=>f.line),...c.length>0&&(o.length>0||t.length>0||p.length>0)?[""]:[],...c.map((f)=>f.line),...b.length>0?[""]:[],...b.map((f)=>f.line)]}else l=s.map((o)=>o.line);return[...l,"",...a].join(`
|
|
15
15
|
`)}function M(r,e){let n=r.startsWith("node:"),s=e.startsWith("node:");if(n!==s)return n?-1:1;let a=r.startsWith("."),i=e.startsWith(".");if(a!==i)return a?1:-1;return r.localeCompare(e)}function W(r,e,n){let s=r.split(`
|
|
16
16
|
`),a=[];for(let i of s){if(i.length<=e){a.push(i);continue}if(i.trimStart().startsWith("import ")){a.push(i);continue}let u=i.match(/^(\s*)/)?.[1]||"",l=u+n,o=O(i,u,l);if(o){a.push(...o);continue}if(i.includes("{")&&i.includes("}")){let t=v(i,e,u,l);a.push(...t);continue}if(i.includes(" | ")){let t=R(i,e,u,l);a.push(...t);continue}a.push(i)}return a.join(`
|
|
17
|
-
`)}var F=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/;function O(r,e,n){let s=r.match(F);if(!s)return null;let[,a,i,u,l]=s,o=u.split(",").map((c)=>c.trim()).filter(Boolean);if(o.length<=1)return[r];let t=`${e}${a}${i??""} {`,p=l?`${e}} ${l};`:`${e}};`;return[t,...o.map((c)=>`${n}${c},`),p]}function v(r,e,n,s){let a=r.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!a)return[r];let[,,i,u,l,o]=a,t=l.split(/;\s*|,\s*/).filter((c)=>c.trim());if(t.length<=1)return[r];return[`${n}${i}${u}`,...t.map((c)=>`${s}${c.trim()};`),`${n}${o.trim()}`]}function R(r,e,n,s){let a=r.match(/^(\s*)(.*?=\s*)(.+)$/);if(!a)return[r];let[,,i,u]=a,l=u.split(/\s*\|\s*/).filter((t)=>t.trim());if(l.length<=2)return[r];return[`${n}${i}`,...l.map((t,p)=>`${s}${p>0?"| ":" "}${t.trim()}`)]}async function te(r,e={},n){let s=[];if(e.usePrettier!==!1){if(await P())try{let l={...await y(e.prettierConfigPath,n),...e.prettierOptions,parser:"typescript"};return{content:await w(r,l),usedPrettier:!0}}catch(u){s.push(`Prettier formatting failed: ${u}. Using built-in formatter.`)}else if(e.usePrettier===!0)s.push("Prettier requested but not available. Using built-in formatter.")}return{content:C(r,e.builtIn),usedPrettier:!1,warnings:s.length>0?s:void 0}}async function
|
|
18
|
-
export{te,
|
|
17
|
+
`)}var F=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/;function O(r,e,n){let s=r.match(F);if(!s)return null;let[,a,i,u,l]=s,o=u.split(",").map((c)=>c.trim()).filter(Boolean);if(o.length<=1)return[r];let t=`${e}${a}${i??""} {`,p=l?`${e}} ${l};`:`${e}};`;return[t,...o.map((c)=>`${n}${c},`),p]}function v(r,e,n,s){let a=r.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!a)return[r];let[,,i,u,l,o]=a,t=l.split(/;\s*|,\s*/).filter((c)=>c.trim());if(t.length<=1)return[r];return[`${n}${i}${u}`,...t.map((c)=>`${s}${c.trim()};`),`${n}${o.trim()}`]}function R(r,e,n,s){let a=r.match(/^(\s*)(.*?=\s*)(.+)$/);if(!a)return[r];let[,,i,u]=a,l=u.split(/\s*\|\s*/).filter((t)=>t.trim());if(l.length<=2)return[r];return[`${n}${i}`,...l.map((t,p)=>`${s}${p>0?"| ":" "}${t.trim()}`)]}async function te(r,e={},n){let s=[];if(e.usePrettier!==!1){if(await P())try{let l={...await y(e.prettierConfigPath,n),...e.prettierOptions,parser:"typescript"};return{content:await w(r,l),usedPrettier:!0}}catch(u){s.push(`Prettier formatting failed: ${u}. Using built-in formatter.`)}else if(e.usePrettier===!0)s.push("Prettier requested but not available. Using built-in formatter.")}return{content:C(r,e.builtIn),usedPrettier:!1,warnings:s.length>0?s:void 0}}async function si(r,e={}){let n=new Map;for(let[s,a]of r){let i=await te(a,e,s);n.set(s,i)}return n}function go(r={}){return{format:(e,n)=>te(e,r,n),formatMany:(e)=>si(e,r)}}async function ho(r){return(await te(r,{usePrettier:!0,builtIn:{indentSize:2,normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}})).content}
|
|
18
|
+
export{te,si,go,ho};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{a,i,h,g,xe,Ue}from"./chunk-cgqg1br8.js";function t(f){let o=[],c=f.length,l=new Set,e=Ue(f,l),r=0;function k(){let S=r++;while(r<c){let y=f.charCodeAt(r);if(y===92)r+=2;else if(y===96){o.push({start:S,end:++r,kind:"literal"});return}else if(y===36&&f.charCodeAt(r+1)===123)o.push({start:S,end:r+1,kind:"literal"}),o.push({start:r+1,end:r+2,kind:"punctuation"}),r+=2,p(!0),S=r;else r++}o.push({start:S,end:r,kind:"literal"})}function p(S=!1){let y=0,M=0;while(r<c){let w=r,n=f.charCodeAt(r);if(n===60&&(M>0||f[r+1]!=="/"&&xe(f,r,o.at(-1)?.end??0))){let u=e(r);if(u){if(M=Math.max(0,M+u.delta),u.delta<0){r=u.end+1,o.push({start:w,end:r,kind:"literal"});continue}}}if(n===32||n>=9&&n<=13||n>127&&/\s/.test(f[r])){r++;continue}if(n===47){let u=f.charCodeAt(r+1);if(u===47){let s=f.indexOf(`
|
|
3
|
-
`,r+2);r=s===-1?c:s+1;continue}if(u===42){let s=f.indexOf("*/",r+2);r=s===-1?c:s+2;continue}if(!l.has(r)&&h(f,r,o.at(-1)?.end??0)){r=g(f,r),o.push({start:w,end:r,kind:"literal"});continue}}else if(n===96){k();continue}else if(n===34||n===39){r++;let u=!1;while(r<c){let s=f.charCodeAt(r++);if(s===92)r++;else if(s===n){u=!0;break}}o.push({start:w,end:Math.min(r,c),kind:u?"quoted":"literal"});continue}else if(a(n)){while(i(f.charCodeAt(++r)));o.push({start:w,end:r,kind:"word"});continue}if(o.push({start:w,end:++r,kind:"punctuation"}),S){if(n===123)y++;else if(n===125){if(y===0)return;y--}}}}return p(),o}var R,q=[];function m(f){if(f!==R)q=t(f),R=f;return q}function
|
|
3
|
+
`,r+2);r=s===-1?c:s+1;continue}if(u===42){let s=f.indexOf("*/",r+2);r=s===-1?c:s+2;continue}if(!l.has(r)&&h(f,r,o.at(-1)?.end??0)){r=g(f,r),o.push({start:w,end:r,kind:"literal"});continue}}else if(n===96){k();continue}else if(n===34||n===39){r++;let u=!1;while(r<c){let s=f.charCodeAt(r++);if(s===92)r++;else if(s===n){u=!0;break}}o.push({start:w,end:Math.min(r,c),kind:u?"quoted":"literal"});continue}else if(a(n)){while(i(f.charCodeAt(++r)));o.push({start:w,end:r,kind:"word"});continue}if(o.push({start:w,end:++r,kind:"punctuation"}),S){if(n===123)y++;else if(n===125){if(y===0)return;y--}}}}return p(),o}var R,q=[];function m(f){if(f!==R)q=t(f),R=f;return q}function ur(){R=void 0,q=[]}function d(f){let o="",c=f.length-1;for(let l=1;l<c;l++){if(f[l]!=="\\"){o+=f[l];continue}let e=f[++l];if(l>=c)return;switch(e){case`
|
|
4
4
|
`:break;case"\r":if(f[l+1]===`
|
|
5
5
|
`)l++;break;case"n":o+=`
|
|
6
6
|
`;break;case"r":o+="\r";break;case"t":o+="\t";break;case"b":o+="\b";break;case"f":o+="\f";break;case"v":o+="\v";break;case"0":if(/\d/.test(f[l+1]??""))return;o+="\x00";break;case"x":case"u":{let r=e==="u"&&f[l+1]==="{",k=l+(r?2:1),p=r?f.indexOf("}",k):k+(e==="x"?2:4),S=f.slice(k,p);if(p<k||p>c||!/^[\da-f]+$/i.test(S)||r&&S.length>6)return;let y=Number.parseInt(S,16);if(y>1114111)return;o+=String.fromCodePoint(y),l=r?p:p-1;break}default:if(/\d/.test(e))return;o+=e}}return o}function E(f,o){let c=o;for(let l of f){let e=l.charCodeAt(0);if(l===o||l==="\\")c+=`\\${l}`;else if(e<32||e===8232||e===8233||l.length===1&&e>=55296&&e<=57343)c+=`\\u${e.toString(16).padStart(4,"0")}`;else c+=l}return c+o}function ze(f){let o=t(f),c=(p)=>o[p]?f.slice(o[p].start,o[p].end):"";if(c(0)!=="import")return;let l=c(1)==="type"&&c(2)!=="=",e=l?2:1;if(o[e]?.kind!=="word"||c(e+1)!=="="||c(e+2)!=="require"||c(e+3)!=="("||o[e+4]?.kind!=="quoted"||c(e+5)!==")")return;let r=e+6;if(o.length!==r&&!(o.length===r+1&&c(r)===";"))return;let k=d(c(e+4));if(k===void 0)return;return{name:c(e),source:k,isTypeOnly:l,end:o[o.length-1].end}}function b(f){let o=t(f),c=[],l=new Set,e=(n)=>n>=0&&n<o.length?f.slice(o[n].start,o[n].end):"",r=(n)=>o[n]?.kind==="quoted",k=(n)=>o[n]?.kind==="word",p=[],S=!1,y=0;if(f.includes("declare")&&f.includes("module"))for(let n=0;n<o.length;n++){let u=e(n);if(y===0&&k(n)&&e(n-1)!=="."&&e(n-1)!=="#"){if(u==="export"||u==="import"&&e(n+1)!=="("&&e(n+1)!==".")S=!0;if(u==="declare"&&e(n+1)==="module"&&r(n+2)&&e(n+3)==="{")p.push(n+2)}if(u==="{"||u==="("||u==="[")y++;else if(u==="}"||u===")"||u==="]")y--}function M(n,u=!1){if(e(n)==="*"){if(e(n+1)==="as")return k(n+2)||u&&r(n+2)?n+3:-1;return u?n+1:-1}if(e(n)!=="{")return-1;let s=1;for(let x=n+1;x<o.length;x++)if(e(x)==="{")s++;else if(e(x)==="}"&&--s===0)return x+1;else if(o[x].kind==="literal"||e(x)===";")return-1;return-1}function w(n,u,s,x){let T=o[n];if(!T||T.kind!=="quoted"||l.has(T.start))return;let C=d(f.slice(T.start,T.end));if(C===void 0)return;l.add(T.start),c.push({specifier:C,kind:u,isTypeOnly:s,category:x,start:T.start,end:T.end})}for(let n=0;n<o.length;n++){if(!k(n)||e(n-1)==="."||e(n-1)==="#")continue;let u=e(n),s=n+1;if(u==="export"){let x=e(s)==="type";if(x)s++;let T=e(s)==="*"?e(s+1)==="as"?"export-star-as":"export-star":"export-named",C=M(s,!0);if(C>=0&&e(C)==="from")w(C+1,T,x,"export")}else if(u==="import"){if(r(s)){w(s,"import",!1,"static-import");continue}if(e(s)==="("){if(e(s+2)===")"||e(s+2)===",")w(s+1,"import",!1,"import-type");continue}let x=e(s)==="type"&&e(s+1)!=="from"&&e(s+1)!=="="&&e(s+1)!==",";if(x)s++;if(k(s)){if(s++,e(s)==="="){if(e(s+1)==="require"&&e(s+2)==="("&&e(s+4)===")")w(s+3,"import",x,"static-import");continue}if(e(s)===",")s=M(s+1)}else s=M(s);if(s>=0&&e(s)==="from")w(s+1,"import",x,"static-import")}}if(S&&p.length){for(let n of p)w(n,"import",!0,"augmentation");c.sort((n,u)=>n.start-u.start)}return c}
|
|
7
|
-
export{t,m,
|
|
7
|
+
export{t,m,ur,d,E,ze,b};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
var Se={PARSE_ERROR:"PARSE_ERROR",SYNTAX_ERROR:"SYNTAX_ERROR",FILE_NOT_FOUND:"FILE_NOT_FOUND",FILE_READ_ERROR:"FILE_READ_ERROR",FILE_WRITE_ERROR:"FILE_WRITE_ERROR",TYPE_INFERENCE_ERROR:"TYPE_INFERENCE_ERROR",UNRESOLVED_TYPE:"UNRESOLVED_TYPE",EXTRACTION_ERROR:"EXTRACTION_ERROR",PROCESSING_ERROR:"PROCESSING_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",INVALID_DECLARATION:"INVALID_DECLARATION",CONFIG_ERROR:"CONFIG_ERROR",INVALID_ENTRYPOINT:"INVALID_ENTRYPOINT",CIRCULAR_DEPENDENCY:"CIRCULAR_DEPENDENCY",TIMEOUT_ERROR:"TIMEOUT_ERROR",NOT_SUPPORTED:"NOT_SUPPORTED",UNKNOWN_ERROR:"UNKNOWN_ERROR"};class T extends Error{code;context;constructor(n,e="UNKNOWN_ERROR",t){super(n);if(this.name="DtsxError",this.code=e,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toString(){let n=`${this.name} [${this.code}]: ${this.message}`;if(this.context)n+=`
|
|
3
|
-
Context: ${JSON.stringify(this.context,null,2)}`;return n}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}}class
|
|
4
|
-
`)t++,s=1;else s++;r++}return{line:t,column:s,offset:e}}function
|
|
3
|
+
Context: ${JSON.stringify(this.context,null,2)}`;return n}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}}class An extends T{filePath;line;column;constructor(n,e,t){super(n,"PARSE_ERROR",{filePath:e,line:t?.line,column:t?.column});if(this.name="ParseError",this.filePath=e,this.line=t?.line,this.column=t?.column,t?.cause)this.cause=t.cause}get locationString(){if(this.line!==void 0&&this.column!==void 0)return`${this.filePath}:${this.line}:${this.column}`;return this.line!==void 0?`${this.filePath}:${this.line}`:this.filePath}}class fi extends T{filePath;declarationKind;constructor(n,e,t,s){super(n,"EXTRACTION_ERROR",{filePath:e,declarationKind:t});if(this.name="ExtractionError",this.filePath=e,this.declarationKind=t,s)this.cause=s}}class di extends T{declarationName;constructor(n,e,t){super(n,"PROCESSING_ERROR",{declarationName:e});if(this.name="ProcessingError",this.declarationName=e,t)this.cause=t}}class Dn extends T{filePath;operation;constructor(n,e,t,s){super(n,t==="read"?"FILE_READ_ERROR":"FILE_WRITE_ERROR",{filePath:e,operation:t});if(this.name="FileError",this.filePath=e,this.operation=t,s)this.cause=s}}class Pn extends T{configPath;invalidKey;constructor(n,e){super(n,"CONFIG_ERROR",{configPath:e?.configPath,invalidKey:e?.invalidKey});if(this.name="ConfigError",this.configPath=e?.configPath,this.invalidKey=e?.invalidKey,e?.cause)this.cause=e.cause}}class pi extends T{cycle;constructor(n){super(`Circular dependency detected: ${n.join(" -> ")}`,"CIRCULAR_DEPENDENCY",{cycle:n});this.name="CircularDependencyError",this.cycle=n}}function Co(n){return n instanceof T}function vo(n){return n instanceof An}function So(n){return n instanceof Dn}function $o(n){return n instanceof Pn}function Eo(n,e="UNKNOWN_ERROR",t){if(n instanceof T)return n;let s=t||(n instanceof Error?n.message:String(n)),r=new T(s,e);if(n instanceof Error)r.cause=n;return r}function ko(n,e){let t=1,s=1,r=0;for(let i of n){if(r>=e)break;if(i===`
|
|
4
|
+
`)t++,s=1;else s++;r++}return{line:t,column:s,offset:e}}function To(n,e,t,s){let r=n.split(`
|
|
5
5
|
`),i=e.line-1,o=[];if(s)o.push(`${s}:${e.line}:${e.column}`);else o.push(`Line ${e.line}, Column ${e.column}`);o.push(`Error: ${t}`),o.push("");let E=Math.max(0,i-1),c=Math.min(r.length-1,i+1);for(let a=E;a<=c;a++){let R=(a+1).toString().padStart(4," "),u=a===i?">":" ";if(o.push(`${u} ${R} | ${r[a]}`),a===i){let l=" ".repeat(8+e.column-1);o.push(`${l}^`)}}return o.join(`
|
|
6
6
|
`)}function Qe(n,e,t){let s={file:e,message:"Unknown error",code:Se.UNKNOWN_ERROR};if(n instanceof Error){s.message=n.message,s.stack=n.stack;let r=n.message.match(/\((\d+),(\d+)\)/);if(r)s.location={line:Number.parseInt(r[1],10),column:Number.parseInt(r[2],10)};if(n.message.includes("Cannot find")||n.message.includes("not found"))s.code=Se.FILE_NOT_FOUND,s.suggestion="Check that the file path is correct and the file exists.";else if(n.message.includes("syntax")||n.message.includes("Unexpected token"))s.code=Se.SYNTAX_ERROR,s.suggestion="Check for syntax errors in your TypeScript code.";else if(n.message.includes("type")&&n.message.includes("cannot"))s.code=Se.TYPE_INFERENCE_ERROR,s.suggestion="Add explicit type annotations to help with type inference.";else if(n.message.includes("parse")||n.message.includes("Parse"))s.code=Se.PARSE_ERROR,s.suggestion="The file contains invalid TypeScript syntax."}else if(typeof n==="string")s.message=n;return s}function Et(n,e){let t=[],s=n.file;if(n.location)s+=`:${n.location.line}:${n.location.column}`;if(n.code)s+=` [${n.code}]`;if(t.push(s),t.push(` Error: ${n.message}`),e&&n.location){t.push("");let r=e.split(`
|
|
7
7
|
`),i=n.location.line-1;if(i>=0&&i<r.length){let o=Math.max(0,i-1),E=Math.min(r.length-1,i+1);for(let c=o;c<=E;c++){let a=(c+1).toString().padStart(4," "),R=c===i?">":" ";if(t.push(` ${R} ${a} | ${r[c]}`),c===i&&n.location.column>0){let u=" ".repeat(10+n.location.column-1);t.push(` ${u}^`)}}}}if(n.suggestion)t.push(""),t.push(` Suggestion: ${n.suggestion}`);return t.join(`
|
|
8
|
-
`)}function
|
|
8
|
+
`)}function Ao(n){if(n.length===0)return"No errors";let e=new Map;for(let s of n){let r=s.code||"UNKNOWN";e.set(r,(e.get(r)||0)+1)}let t=[`${n.length} error(s) found:`];for(let[s,r]of e.entries())t.push(` - ${s}: ${r}`);return t.join(`
|
|
9
9
|
`)}
|
|
10
|
-
export{Se,T,
|
|
10
|
+
export{Se,T,An,fi,di,Dn,Pn,pi,Co,vo,So,$o,Eo,ko,To,Qe,Et,Ao};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{In}from"./chunk-nnayqrp5.js";var g=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"]);function f(e,o={strings:!0}){let c="",n=0;while(n<e.length){let t=e.slice(n,n+2);if(t==="//"){let s=e.indexOf(`
|
|
3
3
|
`,n),a=s===-1?e.length:s;c+=" ".repeat(a-n),n=a;continue}if(t==="/*"){let s=e.indexOf("*/",n+2),a=s===-1?e.length:s+2;for(let r=n;r<a;r++)c+=e[r]===`
|
|
4
4
|
`?`
|
|
5
5
|
`:" ";n=a;continue}let i=e[n];if(o.strings&&(i==='"'||i==="'"||i==="`")){let s=i;c+=" ",n++;while(n<e.length){if(e[n]==="\\"){c+=" ",n+=2;continue}if(e[n]===s){c+=" ",n++;break}c+=e[n]===`
|
|
6
6
|
`?`
|
|
7
|
-
`:" ",n++}continue}c+=i,n++}return c}function m(e){let o=new Set,c=[/\b(?:export\s+)?(?:declare\s+)?(?:abstract\s+)?(?:type|interface|class|enum|namespace|module)\s+([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?(?:declare\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?declare\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g];for(let n of c)for(let t of e.matchAll(n))o.add(t[1]);return o}function d(e){let o=new Set;for(let c of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let n=c[1],t=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(n);if(t)o.add(t[1]);let i=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let a of i.split(",")){let r=a.trim();if(/^[A-Za-z_$][\w$]*$/.test(r))o.add(r)}let s=/\{([\s\S]*?)\}/.exec(n);if(s)for(let a of s[1].split(",")){let r=a.trim().replace(/^type\s+/,"");if(!r)continue;let l=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(r);o.add(l?l[1]:r.split(/\s+/)[0])}}for(let c of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))o.add(c[1]);return o}function p(e){let o=new Set,c=(t)=>{for(let i of t.split(",")){let s=i.trim().split(/\s+|=/)[0]?.trim();if(s&&/^[A-Za-z_$][\w$]*$/.test(s))o.add(s)}},n=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let t of e.matchAll(n))c(t[1]);for(let t of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))c(t[1]);for(let t of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))o.add(t[1]);for(let t of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))o.add(t[1]);return o}function h(e){let o=new Map,c=(t)=>{let i=1;for(let s=0;s<t&&s<e.length;s++)if(e.charCodeAt(s)===10)i++;return i},n=(t,i,s)=>{for(let a of t.matchAll(/\b([A-Z][\w$]*)\b/g)){let r=a[1];if(o.has(r))continue;let l=t.slice(a.index+r.length);if(/^\s*\??:/.test(l))continue;o.set(r,{line:c(i),context:s.trim().slice(0,120)})}};for(let t of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))n(t[1],t.index+t[0].indexOf("="),t[0]);for(let t of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))n(t[1],t.index,t[0]);for(let t of e.matchAll(/:\s*([^;,){}\n=]+)/g))n(t[1],t.index,t[0]);for(let t of e.matchAll(/<([^<>()]*)>/g))n(t[1],t.index,t[0]);return o}function
|
|
8
|
-
export{
|
|
7
|
+
`:" ",n++}continue}c+=i,n++}return c}function m(e){let o=new Set,c=[/\b(?:export\s+)?(?:declare\s+)?(?:abstract\s+)?(?:type|interface|class|enum|namespace|module)\s+([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?(?:declare\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?declare\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g];for(let n of c)for(let t of e.matchAll(n))o.add(t[1]);return o}function d(e){let o=new Set;for(let c of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let n=c[1],t=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(n);if(t)o.add(t[1]);let i=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let a of i.split(",")){let r=a.trim();if(/^[A-Za-z_$][\w$]*$/.test(r))o.add(r)}let s=/\{([\s\S]*?)\}/.exec(n);if(s)for(let a of s[1].split(",")){let r=a.trim().replace(/^type\s+/,"");if(!r)continue;let l=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(r);o.add(l?l[1]:r.split(/\s+/)[0])}}for(let c of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))o.add(c[1]);return o}function p(e){let o=new Set,c=(t)=>{for(let i of t.split(",")){let s=i.trim().split(/\s+|=/)[0]?.trim();if(s&&/^[A-Za-z_$][\w$]*$/.test(s))o.add(s)}},n=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let t of e.matchAll(n))c(t[1]);for(let t of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))c(t[1]);for(let t of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))o.add(t[1]);for(let t of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))o.add(t[1]);return o}function h(e){let o=new Map,c=(t)=>{let i=1;for(let s=0;s<t&&s<e.length;s++)if(e.charCodeAt(s)===10)i++;return i},n=(t,i,s)=>{for(let a of t.matchAll(/\b([A-Z][\w$]*)\b/g)){let r=a[1];if(o.has(r))continue;let l=t.slice(a.index+r.length);if(/^\s*\??:/.test(l))continue;o.set(r,{line:c(i),context:s.trim().slice(0,120)})}};for(let t of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))n(t[1],t.index+t[0].indexOf("="),t[0]);for(let t of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))n(t[1],t.index,t[0]);for(let t of e.matchAll(/:\s*([^;,){}\n=]+)/g))n(t[1],t.index,t[0]);for(let t of e.matchAll(/<([^<>()]*)>/g))n(t[1],t.index,t[0]);return o}function On(e){let o=f(e),c=f(e,{strings:!1}),n=new Set([...m(o),...d(c),...p(o),...In,...g]),t=[];for(let[i,s]of h(o)){if(n.has(i))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${i}\\b`).test(o))continue;t.push({name:i,line:s.line,context:s.context})}return t.sort((i,s)=>i.line-s.line||i.name.localeCompare(s.name))}
|
|
8
|
+
export{On};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r}from"./chunk-
|
|
2
|
+
import{r}from"./chunk-bys9tn88.js";import{existsSync as j,mkdirSync as N,readFileSync as z,writeFileSync as G}from"fs";import{dirname as K,relative as L,resolve as _}from"path";async function bs(t,e,n){let u=new Map,f=[],x=new Set,D=0,w=0,S=0,C=[];for(let i of t){let o=e.get(i);if(!o)continue;C.push({file:i,decls:r(o,i,n.keepComments)})}for(let{file:i,decls:o}of C){D+=o.length;for(let s of o)if(s.kind==="import"){w++;let c=s.source||"";if(c.startsWith("."))continue;if(!u.has(c))u.set(c,{source:c,specifiers:new Map,isTypeOnly:s.isTypeOnly||!1,isSideEffect:s.isSideEffect||!1});let l=u.get(c);if(s.specifiers)for(let h of s.specifiers){let W=h.alias||h.name;if(!l.specifiers.has(W))l.specifiers.set(W,{name:h.name,alias:h.alias,isType:h.isType||!1})}if(!s.isTypeOnly)l.isTypeOnly=!1}else if(s.isExported||s.kind==="export"){if(S++,s.kind==="export"&&s.source&&(s.source.startsWith(".")||s.source.startsWith("/")))continue;if(s.name&&x.has(s.name))continue;if(s.name)x.add(s.name);f.push({declaration:s,file:i})}}let a=[];a.push("/**"),a.push(" * Bundled TypeScript declarations"),a.push(` * Generated from ${t.length} source files`),a.push(" */"),a.push("");let T=n.importOrder||["bun"],y=Array.from(u.values()),p=Array(y.length);for(let i=0;i<y.length;i++){let o=y[i].source,s=T.length;for(let c=0;c<T.length;c++)if(o.startsWith(T[c])){s=c;break}p[i]=s}let g=y.map((i,o)=>o);g.sort((i,o)=>{let s=p[i],c=p[o];if(s!==c)return s-c;return y[i].source.localeCompare(y[o].source)});let b=g.map((i)=>y[i]);for(let i of b)if(i.isSideEffect)a.push(`import '${i.source}';`);else if(i.specifiers.size>0){let s=Array.from(i.specifiers.values()).map((l)=>{let h=l.isType?"type ":"";return l.alias?`${h}${l.name} as ${l.alias}`:`${h}${l.name}`}),c=i.isTypeOnly?"type ":"";a.push(`import ${c}{ ${s.join(", ")} } from '${i.source}';`)}if(b.length>0)a.push("");let m=new Map;for(let{declaration:i,file:o}of f){if(!m.has(o))m.set(o,[]);m.get(o).push(i)}for(let[i,o]of m){let s=L(n.cwd,i);a.push(`// From: ${s}`);for(let c of o){if(n.keepComments&&c.leadingComments)for(let l of c.leadingComments)a.push(l);a.push(F(c))}a.push("")}let d=a.join(`
|
|
3
3
|
`);return{content:d,files:t,declarationCount:D,importCount:w,exportCount:S,size:Buffer.byteLength(d,"utf8"),warnings:[]}}function F(t){if(t.text){let n=t.text.trim();if(t.isExported&&!n.startsWith("export"))n=`export ${n}`;if(!n.endsWith(";")&&!n.endsWith("}"))n+=";";return n}let e=[];if(t.isExported)e.push("export");if(t.isDefault)e.push("default");switch(t.kind){case"function":if(e.push("declare function"),e.push(t.name),t.generics)e.push(t.generics);if(e.push(`(${V(t.parameters)})`),t.returnType)e.push(`: ${t.returnType}`);break;case"variable":if(e.push("declare const"),e.push(t.name),t.typeAnnotation)e.push(`: ${t.typeAnnotation}`);break;case"interface":if(e.push("interface"),e.push(t.name),t.generics)e.push(t.generics);if(t.extends)e.push(`extends ${t.extends}`);if(e.push("{"),t.members)for(let n of t.members)e.push(` ${n.name}${n.typeAnnotation?`: ${n.typeAnnotation}`:""};`);e.push("}");break;case"type":if(e.push("type"),e.push(t.name),t.generics)e.push(t.generics);e.push("="),e.push(t.typeAnnotation||"unknown");break;case"class":if(e.push("declare class"),e.push(t.name),t.generics)e.push(t.generics);if(t.extends)e.push(`extends ${t.extends}`);if(t.implements&&t.implements.length>0)e.push(`implements ${t.implements.join(", ")}`);if(e.push("{"),t.members)for(let n of t.members)e.push(` ${F(n)}`);e.push("}");break;case"enum":if(e.push("declare enum"),e.push(t.name),e.push("{"),t.members){let n=t.members.map((u)=>u.value!==void 0?`${u.name} = ${u.value}`:u.name);e.push(` ${n.join(`,
|
|
4
|
-
`)}`)}e.push("}");break;default:return t.text||""}return e.join(" ")}function V(t){if(!t||t.length===0)return"";return t.map((e)=>{let n="";if(e.rest)n+="...";if(n+=e.name,e.optional)n+="?";if(e.type)n+=`: ${e.type}`;if(e.defaultValue)n+=` = ${e.defaultValue}`;return n}).join(", ")}async function
|
|
4
|
+
`)}`)}e.push("}");break;default:return t.text||""}return e.join(" ")}function V(t){if(!t||t.length===0)return"";return t.map((e)=>{let n="";if(e.rest)n+="...";if(n+=e.name,e.optional)n+="?";if(e.type)n+=`: ${e.type}`;if(e.defaultValue)n+=` = ${e.defaultValue}`;return n}).join(", ")}async function nn(t,e={}){let n=[],u=new Map,f=[],x=[],D=new Set,w=0,S=0,C=0;for(let p of t){if(!j(p)){n.push(`File not found: ${p}`);continue}let g=z(p,"utf-8");x.push(p);let b=g.split(`
|
|
5
5
|
`),m=[],d=0,i=!1;for(let o of b){let s=o.trim();if(!s&&!i)continue;if(s.startsWith("import ")){S++;let l=s.match(/import\s+(type\s+)?(?:\{([^}]+)\}|(\w+)|\*\s+as\s+(\w+))\s+from\s+['"]([^'"]+)['"]/);if(l){let[,h,W,q,H,A]=l;if(e.externals?.some((P)=>A.startsWith(P))){f.push(s);continue}if(A.startsWith("."))continue;if(!u.has(A))u.set(A,{source:A,specifiers:new Map,isTypeOnly:!!h,isSideEffect:!1});let E=u.get(A);if(W){let P=W.split(",").map((k)=>k.trim());for(let k of P){let[I,v]=k.split(/\s+as\s+/).map((M)=>M.trim()),R=I.startsWith("type "),O=R?I.replace("type ",""):I;E.specifiers.set(v||O,{name:O,alias:v!==O?v:void 0,isType:R})}}if(!h)E.isTypeOnly=!1}continue}if(/^(export\s+)?(declare\s+)?(interface|type|class|function|const|let|var|enum|namespace|module)\s/.test(s)){if(i=!0,m=[o],d=(o.match(/\{/g)||[]).length-(o.match(/\}/g)||[]).length,d===0&&(s.endsWith(";")||!s.includes("{"))){let l=B(s);if(!D.has(l)||!e.mergeDuplicates){if(D.add(l),f.push(o),w++,s.startsWith("export"))C++}i=!1,m=[]}}else if(i){if(m.push(o),d+=(o.match(/\{/g)||[]).length-(o.match(/\}/g)||[]).length,d<=0){let l=m.join(`
|
|
6
6
|
`),h=B(m[0]);if(!D.has(h)||!e.mergeDuplicates){if(D.add(h),f.push(l),w++,m[0].trim().startsWith("export"))C++}i=!1,m=[]}}else if(s.startsWith("export ")&&!s.includes("declare"))f.push(o),C++}}let a=[];if(e.banner)a.push(e.banner),a.push("");if(e.includeReferences&&e.references){for(let p of e.references)a.push(`/// <reference types="${p}" />`);a.push("")}let T=Array.from(u.values()).sort((p,g)=>p.source.localeCompare(g.source));for(let p of T)if(p.specifiers.size>0){let b=Array.from(p.specifiers.values()).map((d)=>{let i=d.isType?"type ":"";return d.alias?`${i}${d.name} as ${d.alias}`:`${i}${d.name}`}),m=p.isTypeOnly?"type ":"";a.push(`import ${m}{ ${b.join(", ")} } from '${p.source}';`)}if(T.length>0)a.push("");if(e.ambient&&e.moduleName){a.push(`declare module '${e.moduleName}' {`);for(let p of f){let g=p.split(`
|
|
7
7
|
`).map((b)=>` ${b.replace(/^(\s*)(export\s+)?declare\s+/,"$1$2")}`).join(`
|
|
8
8
|
`);a.push(g)}a.push("}")}else{if(e.sortDeclarations)f.sort((p,g)=>{let b=B(p),m=B(g);return b.localeCompare(m)});for(let p of f)a.push(p)}if(e.footer)a.push(""),a.push(e.footer);let y=a.join(`
|
|
9
|
-
`);return{content:y,files:x,declarationCount:w,importCount:S,exportCount:C,size:Buffer.byteLength(y,"utf-8"),warnings:n}}function B(t){let e=t.match(/(interface|type|class|function|const|let|var|enum|namespace|module)\s+(\w+)/);return e?`${e[1]}:${e[2]}`:t.trim()}async function
|
|
10
|
-
export{
|
|
9
|
+
`);return{content:y,files:x,declarationCount:w,importCount:S,exportCount:C,size:Buffer.byteLength(y,"utf-8"),warnings:n}}function B(t){let e=t.match(/(interface|type|class|function|const|let|var|enum|namespace|module)\s+(\w+)/);return e?`${e[1]}:${e[2]}`:t.trim()}async function Ar(t,e,n={}){let u=await nn(t,n),f=K(e);if(!j(f))N(f,{recursive:!0});return G(e,u.content),u}function ws(t={}){return{bundle:(e)=>nn(e,t),bundleAndWrite:(e,n)=>Ar(e,n,{...t,output:n})}}async function xs(t,e=process.cwd()){let n=Array.isArray(t)?t:[t],u=[];for(let f of n){if(f.includes("*"))continue;let x=_(e,f);if(j(x))u.push(x)}return u}
|
|
10
|
+
export{bs,nn,Ar,ws,xs};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{st}from"./chunk-
|
|
2
|
+
import{st}from"./chunk-6b6rt0yh.js";import{D}from"./chunk-rc1zpm7f.js";import{On}from"./chunk-v22xpr7j.js";import{ke}from"./chunk-hgg4aqvf.js";import{ce}from"./chunk-x6ddycvm.js";import y from"process";import{readdir as v}from"fs/promises";import{join as C,resolve as b}from"path";function tt(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}function Oo(n,r){throw Error(r||`Unexpected value: ${n}`)}async function Y(n,r,o="lf"){let t=r.replace(/\r\n/g,`
|
|
3
3
|
`);if(!t.endsWith(`
|
|
4
4
|
`))t+=`
|
|
5
5
|
`;if(o==="crlf")t=t.replace(/\n/g,`\r
|
|
6
|
-
`);if(await st(n,t)!==Buffer.byteLength(t,"utf8"))throw Error(`Incomplete declaration write: ${n}`)}async function
|
|
6
|
+
`);if(await st(n,t)!==Buffer.byteLength(t,"utf8"))throw Error(`Incomplete declaration write: ${n}`)}async function bi(n){let r=n??D.root,o=await v(r,{withFileTypes:!0});return(await Promise.all(o.map((i)=>{let c=C(r,i.name);return i.isDirectory()?bi(c):c}))).flat(1/0).filter((i)=>{if(typeof i!=="string")return!1;return/\.(?:ts|tsx|mts|cts)$/.test(i)&&!/\.d\.(?:ts|mts|cts)$/.test(i)})}async function re(n){try{let r=n?.cwd||y.cwd();return(await ce(b(r,n?.tsconfigPath||"tsconfig.json"),{allowCircular:!0}))?.isolatedDeclarations??!1}catch{return!1}}function Tt(n,r){let o={isValid:!0,errors:[]};for(let t of ke(n))o.errors.push({line:t.line,column:t.column,message:t.message,code:t.code});for(let t of On(n))o.errors.push({line:t.line,column:1,message:`'${t.name}' is used but never declared or imported here, so it resolves to an error type for anything consuming this file. It is most likely an ambient global in the source project \u2014 import it explicitly. Referenced by: ${t.context}`,code:"dangling-type-reference"});return o.isValid=o.errors.length===0,o}function At(n,r,o){if(n===r)return"";let t=n.split(`
|
|
7
7
|
`),i=r.split(`
|
|
8
8
|
`),c=new Map,a=new Map;for(let e=0;e<t.length;e++)c.set(t[e],(c.get(t[e])??0)+1);for(let e=0;e<i.length;e++)a.set(i[e],(a.get(i[e])??0)+1);let g=[],u=[];for(let[e,s]of c){let m=s-(a.get(e)??0);for(let l=0;l<m;l++)g.push(e)}for(let[e,s]of a){let m=s-(c.get(e)??0);for(let l=0;l<m;l++)u.push(e)}if(g.length===0&&u.length===0)return"";let p=[`--- ${o}`,`+++ ${o}`];for(let e=0;e<g.length;e++)p.push(`- ${g[e]}`);for(let e=0;e<u.length;e++)p.push(`+ ${u[e]}`);return p.join(`
|
|
9
9
|
`)}function Dt(n,r,o,t){let i=n.split(`
|
|
@@ -11,4 +11,4 @@ import{st}from"./chunk-02yqpwv0.js";import{D}from"./chunk-m7jndt3v.js";import{Mn
|
|
|
11
11
|
`).length;for(let s=0;s<i.length;s++){if(i[s].trim()===""){c.push("");continue}g=0;let l=Math.min(s,e-1),f=[],d=0-g,h=0,w=l-u,x=0-p;f.push(a(d)+a(h)+a(w)+a(x)),g=0,u=l,p=0,c.push(f.join(","))}return{version:3,file:r,sourceRoot:"",sources:[o],sourcesContent:[t],mappings:c.join(";")}}function Pt(n,r){return`${n}
|
|
12
12
|
${tt()}${r}
|
|
13
13
|
`}
|
|
14
|
-
export{tt,
|
|
14
|
+
export{tt,Oo,Y,bi,re,Tt,At,Dt,Pt};
|