@dtsx/dtsx 0.11.42 → 0.11.44
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/README.md +6 -0
- package/dist/bin/cli.js +9 -9
- package/dist/{chunk-s0sretav.js → chunk-0cynxv6w.js} +2 -2
- package/dist/{chunk-gc7y4wav.js → chunk-1hz6j7bq.js} +21 -21
- package/dist/{chunk-ywv56grs.js → chunk-2d3nbfth.js} +2 -2
- package/dist/{chunk-6vz1grv8.js → chunk-2y5b6hdw.js} +6 -6
- package/dist/{chunk-t76sqybd.js → chunk-3eb0gc0y.js} +1 -1
- package/dist/{chunk-vae5wxar.js → chunk-3rwbf45t.js} +2 -2
- package/dist/{chunk-veh8ks5v.js → chunk-3shq1bjr.js} +2 -2
- package/dist/{chunk-t8cgznk6.js → chunk-3v0yh5dk.js} +2 -2
- package/dist/{chunk-7g0hjhqy.js → chunk-4ece5g8t.js} +2 -2
- package/dist/{chunk-khyg6w62.js → chunk-4hkf7dda.js} +4 -4
- package/dist/chunk-59jw51gg.js +8 -0
- package/dist/{chunk-dh3y4pf7.js → chunk-5aqwt0a0.js} +4 -4
- package/dist/{chunk-8fg11pr7.js → chunk-65d3dga1.js} +3 -3
- package/dist/{chunk-asqkc0bw.js → chunk-6mryvpxj.js} +5 -5
- package/dist/{chunk-3r9dptyy.js → chunk-6pr23q72.js} +2 -2
- package/dist/{chunk-k9695p66.js → chunk-7ez7gynw.js} +2 -2
- package/dist/{chunk-eatp44nf.js → chunk-7krb9b1s.js} +2 -2
- package/dist/{chunk-gt5k2mff.js → chunk-7x9tawkf.js} +2 -2
- package/dist/{chunk-btwfkzt5.js → chunk-86xvq8km.js} +3 -3
- package/dist/{chunk-cywe5sgm.js → chunk-8v43ne8p.js} +3 -3
- package/dist/chunk-90f37xen.js +3 -0
- package/dist/{chunk-qqjbaqm6.js → chunk-932kxt70.js} +4 -4
- package/dist/{chunk-vjtcxr3q.js → chunk-976r899s.js} +4 -4
- package/dist/{chunk-06jp6gah.js → chunk-9etacmfx.js} +3 -3
- package/dist/{chunk-btc6zbyj.js → chunk-9hjd6p38.js} +2 -2
- package/dist/{chunk-twrcd0q6.js → chunk-9qv34ymq.js} +2 -2
- package/dist/{chunk-537hj5pj.js → chunk-an5ra7tr.js} +4 -4
- package/dist/{chunk-x3arymvk.js → chunk-anvhqbw8.js} +2 -2
- package/dist/{chunk-prst4szw.js → chunk-btmc3e8d.js} +2 -2
- package/dist/{chunk-r27pfg4r.js → chunk-c8s4d7qk.js} +6 -6
- package/dist/{chunk-q4gxj6qk.js → chunk-cgaw8fsn.js} +3 -3
- package/dist/{chunk-cyfnxk8d.js → chunk-cjhmmqxd.js} +2 -2
- package/dist/{chunk-m0tacjrk.js → chunk-cynfv4dt.js} +3 -3
- package/dist/{chunk-fv3x086v.js → chunk-d0aqaj02.js} +2 -2
- package/dist/{chunk-jf8mxazb.js → chunk-d68r83t9.js} +2 -2
- package/dist/{chunk-g4dpvmfy.js → chunk-der2ssgq.js} +2 -2
- package/dist/{chunk-73qsp464.js → chunk-dzdwc2fh.js} +2 -2
- package/dist/{chunk-w3zqfm8a.js → chunk-ehgnwdn9.js} +2 -2
- package/dist/{chunk-ej7jt519.js → chunk-eptz3q7r.js} +4 -4
- package/dist/{chunk-13tjnp25.js → chunk-erymqkk3.js} +6 -6
- package/dist/{chunk-kv3x5jrs.js → chunk-g19c3m7s.js} +2 -2
- package/dist/{chunk-qzb5pswc.js → chunk-g4rmn34j.js} +2 -2
- package/dist/{chunk-xzw0p4nq.js → chunk-gma09qy6.js} +2 -2
- package/dist/{chunk-1vc3eend.js → chunk-h1xwd278.js} +2 -2
- package/dist/{chunk-gv9brtta.js → chunk-hnckev96.js} +4 -4
- package/dist/{chunk-298wqs3n.js → chunk-hwgxwgsh.js} +2 -2
- package/dist/chunk-hyszyzq2.js +3 -0
- package/dist/{chunk-q76b61w9.js → chunk-jbxb317g.js} +6 -6
- package/dist/{chunk-3s37g6bh.js → chunk-ka22zwye.js} +8 -8
- package/dist/chunk-m2kzh519.js +3 -0
- package/dist/{chunk-hqph3vnd.js → chunk-m3y5knzq.js} +5 -5
- package/dist/{chunk-3jtwkmfx.js → chunk-madfh88z.js} +2 -2
- package/dist/{chunk-zbyvnsny.js → chunk-mfp35a3b.js} +9 -9
- package/dist/{chunk-01zsk2q8.js → chunk-mhyqvwcg.js} +3 -3
- package/dist/{chunk-g0dxj89b.js → chunk-mhz6xe61.js} +4 -4
- package/dist/{chunk-2ngfncfx.js → chunk-mjzee617.js} +11 -11
- package/dist/{chunk-54d8mt4c.js → chunk-nek63555.js} +2 -2
- package/dist/{chunk-550teag8.js → chunk-njqzhkzy.js} +10 -10
- package/dist/{chunk-j0p7bwj6.js → chunk-ns44qxdd.js} +4 -4
- package/dist/chunk-nxk4h5hy.js +3 -0
- package/dist/{chunk-9gp0e3kn.js → chunk-ptbd3dac.js} +2 -2
- package/dist/{chunk-zf96k060.js → chunk-q45jkpya.js} +2 -2
- package/dist/{chunk-x4qkjqda.js → chunk-q4ebd4qe.js} +2 -2
- package/dist/{chunk-f2yhf6gj.js → chunk-qevb6d6j.js} +2 -2
- package/dist/{chunk-bre2x1bd.js → chunk-rka9z03a.js} +4 -4
- package/dist/{chunk-8wk7nw3c.js → chunk-s7k223zx.js} +2 -2
- package/dist/{chunk-7bt7x8sy.js → chunk-sqnhxtbk.js} +3 -3
- package/dist/{chunk-a3apthex.js → chunk-th9tcxga.js} +2 -2
- package/dist/{chunk-8kj9pkw5.js → chunk-v3n9zzhm.js} +2 -2
- package/dist/{chunk-aq7y0s2v.js → chunk-vgyjw95e.js} +4 -4
- package/dist/{chunk-85d82vn3.js → chunk-vv8e8pa3.js} +2 -2
- package/dist/{chunk-jvqczw2k.js → chunk-vxghzchm.js} +3 -3
- package/dist/{chunk-00m9cbar.js → chunk-vz4fc70e.js} +3 -3
- package/dist/{chunk-60wrxcjt.js → chunk-waan03ga.js} +3 -3
- package/dist/chunk-x1j88x37.js +38 -0
- package/dist/{chunk-a2dn9j88.js → chunk-xa9vcbjj.js} +2 -2
- package/dist/chunk-xb2nr89a.js +3 -0
- package/dist/{chunk-bkbsg2bv.js → chunk-xgf6djk3.js} +2 -2
- package/dist/chunk-ykrdzatr.js +31 -0
- package/dist/{chunk-kdnqedyb.js → chunk-yqvn592m.js} +2 -2
- package/dist/{chunk-7387m006.js → chunk-zp93zcn5.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.d.ts +2 -1
- package/dist/src/index.js +1 -1
- package/dist/src/inferred-imports.js +1 -1
- package/dist/src/json-config.js +1 -1
- package/dist/src/lexical.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.d.ts +24 -2
- 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.d.ts +4 -3
- package/dist/src/process-source.js +1 -1
- package/dist/src/processor/cache.js +1 -1
- package/dist/src/processor/comments.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/syntax-validator.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/tsconfig.js +1 -1
- package/dist/src/type-mappings.js +1 -1
- package/dist/src/types.d.ts +1 -0
- package/dist/src/utils.js +1 -1
- 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 +1 -1
- package/dist/chunk-3qx4ys4v.js +0 -38
- package/dist/chunk-4q78f5pg.js +0 -3
- package/dist/chunk-5ezj0r3g.js +0 -3
- package/dist/chunk-7khy25x0.js +0 -3
- package/dist/chunk-msr5zymd.js +0 -31
- package/dist/chunk-pd30356m.js +0 -8
- package/dist/chunk-q4fhsthj.js +0 -3
- package/dist/chunk-zy5jxjmg.js +0 -3
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{An}from"./chunk-ptbd3dac.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 Tn(e){let o=f(e),c=f(e,{strings:!1}),n=new Set([...m(o),...d(c),...p(o),...An,...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{Tn};
|
|
@@ -3,5 +3,5 @@ function f(r,e=!0){if(!e||!r||r.length===0)return"";if(r.length===1){let t=r[0];
|
|
|
3
3
|
`;return`${t.trim()}
|
|
4
4
|
`}let n="";for(let t=0;t<r.length;t++){if(t>0)n+=`
|
|
5
5
|
`;n+=r[t].trim()}return`${n}
|
|
6
|
-
`}function
|
|
7
|
-
export{f,
|
|
6
|
+
`}function de(r){return r.replaceAll("*/","*\\/")}
|
|
7
|
+
export{f,de};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
function c(t){return t>=65&&t<=90||t>=97&&t<=122||t===95||t===36||t>127}function i(t){return c(t)||t>=48&&t<=57}function L(t,_){let n=_;for(;;){while(n>=0&&(t.charCodeAt(n)===32||t.charCodeAt(n)===9||t.charCodeAt(n)===10||t.charCodeAt(n)===13))n--;if(n<0)return-1;if(t.charCodeAt(n)===47&&n>0&&t.charCodeAt(n-1)===42){let C=t.lastIndexOf("/*",n-2);if(C===-1)return-1;n=C-1;continue}let r=t.lastIndexOf(`
|
|
3
3
|
`,n)+1,o=E(t,r,n);if(o!==-1){n=o-1;continue}return n}}function E(t,_,n){let r=0;for(let o=_;o<=n;o++){let C=t.charCodeAt(o);if(r){if(C===92){o++;continue}if(C===r)r=0;continue}if(C===39||C===34||C===96){r=C;continue}if(C===47&&o+1<=n&&t.charCodeAt(o+1)===47)return o}return-1}function u(t){return t===61||t===40||t===91||t===33||t===38||t===124||t===63||t===58||t===44||t===59||t===123||t===125||t===94||t===126||t===43||t===45||t===42||t===37||t===60||t===62}function R(t){return t==="return"||t==="typeof"||t==="void"||t==="delete"||t==="throw"||t==="new"||t==="in"||t==="of"||t==="case"||t==="instanceof"||t==="yield"||t==="await"||t==="else"||t==="do"}function b(t,_){let n=[],r=[],o=0,C=!1,l="",s="",S=!0,e=0,f=(H,A=!1)=>{s=l,l=H,S=A};while(e<=_){let H=t.charCodeAt(e);if(C){if(H===92){e+=2;continue}if(H===96)C=!1,f("literal");else if(H===36&&t.charCodeAt(e+1)===123)r.push(o++),C=!1,f("{",!0),e++;e++;continue}if(H===32||H===9||H===10||H===13){e++;continue}if(H===47&&t.charCodeAt(e+1)===47){let A=t.indexOf(`
|
|
4
|
-
`,e+2);e=A===-1?t.length:A+1;continue}if(H===47&&t.charCodeAt(e+1)===42){let A=t.indexOf("*/",e+2);e=A===-1?t.length:A+2;continue}if(H===39||H===34){let A=H;e++;while(e<t.length){let a=t.charCodeAt(e++);if(a===92)e++;else if(a===A)break}f("literal");continue}if(H===96){C=!0,e++;continue}if(c(H)||H===35&&c(t.charCodeAt(e+1))){let A=e++;while(i(t.charCodeAt(e)))e++;let a=t.slice(A,e);f(a,l!=="."&&R(a));continue}if(H===40){let A=s!=="."&&(l==="if"||l==="while"||l==="for"||l==="with"||l==="switch"||l==="catch"||l==="await"&&s==="for");n.push(A),f("(",!0)}else if(H===41){let A=n.pop()??!1;if(e===_)return A;f(")",A)}else if(H===47&&S){e=
|
|
5
|
-
export{c,i,
|
|
4
|
+
`,e+2);e=A===-1?t.length:A+1;continue}if(H===47&&t.charCodeAt(e+1)===42){let A=t.indexOf("*/",e+2);e=A===-1?t.length:A+2;continue}if(H===39||H===34){let A=H;e++;while(e<t.length){let a=t.charCodeAt(e++);if(a===92)e++;else if(a===A)break}f("literal");continue}if(H===96){C=!0,e++;continue}if(c(H)||H===35&&c(t.charCodeAt(e+1))){let A=e++;while(i(t.charCodeAt(e)))e++;let a=t.slice(A,e);f(a,l!=="."&&R(a));continue}if(H===40){let A=s!=="."&&(l==="if"||l==="while"||l==="for"||l==="with"||l==="switch"||l==="catch"||l==="await"&&s==="for");n.push(A),f("(",!0)}else if(H===41){let A=n.pop()??!1;if(e===_)return A;f(")",A)}else if(H===47&&S){e=me(t,e),f("literal");continue}else{if(H===123)o++;else if(H===125){if(o--,r.at(-1)===o)r.pop(),C=!0}f(t[e],H===47||u(H))}e++}return!1}function _e(t,_){let n=L(t,_-1);if(n<0)return!0;let r=t.charCodeAt(n);if(r===41)return b(t,n);if(u(r))return!0;if(i(r)){let o=n;while(o>=0&&i(t.charCodeAt(o)))o--;let C=t.charCodeAt(L(t,o));if(C===46||C===35)return!1;return R(t.slice(o+1,n+1))}return!1}function me(t,_){let n=_,r=t.length;n++;let o=!1;while(n<r){let C=t.charCodeAt(n);if(C===92){n+=2;continue}if(o){if(C===93)o=!1;n++;continue}if(C===91){o=!0,n++;continue}if(C===47){n++;break}if(C===10||C===13)break;n++}while(n<r&&i(t.charCodeAt(n)))n++;return n}
|
|
5
|
+
export{c,i,_e,me};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function
|
|
2
|
+
function ft(e,r={}){let{entryPoints:n,keepExported:s=!0,keep:t=[],remove:l=[],shakableKinds:c=["type","interface"],debug:m=!1}=r,p=m?console.log.bind(console,"[tree-shake]"):()=>{},x=new Map;for(let a of e)x.set(a.name,a);let i=dt(e);p("Dependency graph:",Object.fromEntries(Array.from(i.entries()).map(([a,d])=>[a,Array.from(d)])));let o=new Set;if(n&&n.length>0){for(let a of n)if(x.has(a))o.add(a)}else{let a=new Set(c);for(let d of e){if(s&&d.isExported){o.add(d.name);continue}if(k(d.name,t)){o.add(d.name);continue}if(!a.has(d.kind))o.add(d.name)}}if(n&&n.length>0&&t.length>0){for(let a of e)if(k(a.name,t))o.add(a.name)}p("Entry points:",Array.from(o));let f=T(o,i);p("Reachable:",Array.from(f));let u=new Set,g=[];for(let a of e){let d=a.name;if(f.has(d)){u.add(d);continue}if(k(d,l)){g.push(d);continue}if(!c.includes(a.kind)){u.add(d);continue}g.push(d)}p("Keeping:",Array.from(u)),p("Removing:",g);let b=e.filter((a)=>u.has(a.name)),y={totalBefore:e.length,totalAfter:b.length,removedCount:g.length,reductionPercent:e.length>0?Math.round(g.length/e.length*100):0};return{declarations:b,removed:g,dependencyGraph:i,stats:y}}function dt(e){let r=new Map,n=new Set;for(let s=0;s<e.length;s++)n.add(e[s].name);for(let s of e){let t=new Set,l=pt(s);for(let c of l)if(n.has(c)&&c!==s.name)t.add(c);r.set(s.name,t)}return r}function pt(e){let r=new Set;if(e.typeAnnotation)h(e.typeAnnotation,r);if(e.extends)h(e.extends,r);if(e.text)R(e.text,r);if(e.members)for(let n of e.members){let s=pt(n);for(let t of s)r.add(t)}if(e.parameters){for(let n of e.parameters)if(n.type)h(n.type,r)}if(e.returnType)h(e.returnType,r);return r}var E=new Set(["string","number","boolean","object","any","unknown","never","void","null","undefined","symbol","bigint","true","false","Array","Object","String","Number","Boolean","Function","Symbol","Promise","Map","Set","WeakMap","WeakSet","Record","Partial","Required","Readonly","Pick","Omit","Exclude","Extract","NonNullable","Parameters","ReturnType","InstanceType","ConstructorParameters","ThisParameterType","OmitThisParameter","ThisType","Uppercase","Lowercase","Capitalize","Uncapitalize","Awaited","keyof","typeof","infer","extends","readonly","const","new"]),S=/\b([A-Z]\w*)\b/g,D=/\btypeof\s+([$A-Z_a-z][$\w]*)/g;function h(e,r){S.lastIndex=0;let n;while((n=S.exec(e))!==null){let s=n[1];if(!E.has(s))r.add(s)}D.lastIndex=0;while((n=D.exec(e))!==null)r.add(n[1])}function R(e,r){h(e,r)}function T(e,r){let n=new Set,s=Array.from(e);while(s.length>0){let t=s.pop();if(n.has(t))continue;n.add(t);let l=r.get(t);if(l){for(let c of l)if(!n.has(c))s.push(c)}}return n}function k(e,r){for(let n of r)if(typeof n==="string"){if(n.includes("*")){if(new RegExp(`^${n.replace(/\*/g,".*").replace(/\?/g,".")}$`).test(e))return!0}else if(e===n)return!0}else if(n.test(e))return!0;return!1}function ur(e,r={}){let n=e.split(`
|
|
3
3
|
`),s=[],t=null;for(let i=0;i<n.length;i++){let o=n[i],f=o.trim();if(!t&&(f===""||f.startsWith("//")))continue;if(!t){let u=f.match(/^(export\s+)?(declare\s+)?(interface|type|enum|class|function|const|let|var)\s+(\w+)/);if(u){let[,g,,b,y]=u;if(t={name:y,kind:b,isExported:!!g,start:i,lines:[o],braceCount:0},t.braceCount+=(o.match(/\{/g)||[]).length,t.braceCount-=(o.match(/\}/g)||[]).length,t.braceCount===0&&(f.endsWith(";")||!f.includes("{")))s.push({name:t.name,kind:t.kind,isExported:t.isExported,start:t.start,end:i,text:t.lines.join(`
|
|
4
4
|
`)}),t=null;continue}}if(t){if(t.lines.push(o),t.braceCount+=(o.match(/\{/g)||[]).length,t.braceCount-=(o.match(/\}/g)||[]).length,t.braceCount<=0&&(f.endsWith("}")||f.endsWith(";")))s.push({name:t.name,kind:t.kind,isExported:t.isExported,start:t.start,end:i,text:t.lines.join(`
|
|
5
|
-
`)}),t=null}}if(s.length===0)return{content:e,removed:[]};let l=s.map((i)=>({name:i.name,kind:i.kind,isExported:i.isExported,text:i.text})),c=
|
|
5
|
+
`)}),t=null}}if(s.length===0)return{content:e,removed:[]};let l=s.map((i)=>({name:i.name,kind:i.kind,isExported:i.isExported,text:i.text})),c=ft(l,r),m=new Set(c.declarations.map((i)=>i.name)),p=new Set;for(let i of s)if(!m.has(i.name))for(let o=i.start;o<=i.end;o++)p.add(o);return{content:n.filter((i,o)=>!p.has(o)).join(`
|
|
6
6
|
`).replace(/\n{3,}/g,`
|
|
7
7
|
|
|
8
|
-
`),removed:c.removed}}function
|
|
9
|
-
export{
|
|
8
|
+
`),removed:c.removed}}function fr(e,r={}){return ft(e,{...r,debug:!1}).removed}function dr(e,r){let n=dt(r),s=n.get(e)||new Set,t=T(new Set([e]),n);t.delete(e);let l=[];for(let[c,m]of n)if(c!==e&&m.has(e))l.push(c);return{directDependencies:Array.from(s),transitiveDependencies:Array.from(t),dependents:l}}function Yi(e={}){return{shake:(r)=>ft(r,e),shakeContent:(r)=>ur(r,e),findUnused:(r)=>fr(r,e),analyzeDependencies:(r,n)=>dr(r,n),buildGraph:dt,extractRefs:pt}}
|
|
9
|
+
export{ft,dt,pt,ur,fr,dr,Yi};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{spawn as m}from"child_process";import{readFile as i,stat as n,writeFile as p}from"fs/promises";var g=typeof globalThis.Bun<"u",
|
|
3
|
-
export{g,
|
|
2
|
+
import{spawn as m}from"child_process";import{readFile as i,stat as n,writeFile as p}from"fs/promises";var g=typeof globalThis.Bun<"u",sa=!g&&typeof process<"u"&&!!process.versions?.node,oa=g?"bun":"node";class s{name;_size=-1;constructor(e){this.name=e}async exists(){try{return await n(this.name),!0}catch{return!1}}async text(){return i(this.name,"utf-8")}async arrayBuffer(){let e=await i(this.name);return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}get size(){if(this._size===-1)return-1;return this._size}}class a{pid;stdout;stderr;stdin;exited;process;constructor(e){this.process=e,this.pid=e.pid??0,this.stdout=e.stdout,this.stderr=e.stderr,this.stdin=e.stdin,this.exited=new Promise((r)=>{e.on("exit",(t)=>{r(t??0)}),e.on("error",()=>{r(1)})})}kill(e){this.process.kill(e)}ref(){this.process.ref()}unref(){this.process.unref()}}function re(e){if(g)return globalThis.Bun.file(e);return new s(e)}async function et(e,r){if(g)return globalThis.Bun.write(e,r);let t=typeof r==="string"?r:r instanceof ArrayBuffer?Buffer.from(r):r;return await p(e,t),typeof r==="string"?Buffer.byteLength(r):r.byteLength}function At(e,r={}){if(g)return globalThis.Bun.spawn(e,r);let t=Array.isArray(e)?e:[e],[o,...d]=t,l={cwd:r.cwd,env:r.env,stdio:[r.stdin??"pipe",r.stdout??"pipe",r.stderr??"pipe"]},f=m(o,d,l);return new a(f)}async function u(e){if(g)return globalThis.Bun.file(e).text();return i(e,"utf-8")}async function aa(e){if(g)return globalThis.Bun.file(e).exists();try{return await n(e),!0}catch{return!1}}async function ca(e,r){await et(e,r)}function la(){if(g)return{name:"bun",version:globalThis.Bun.version,isBun:!0,isNode:!1};return{name:"node",version:process.versions.node,isBun:!1,isNode:!0}}
|
|
3
|
+
export{g,sa,oa,re,et,At,u,aa,ca,la};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function
|
|
2
|
+
function qi(m,b={}){let{mergeInterfaces:c=!0,mergeNamespaces:e=!0,mergeTypes:n=!1,mergeEnums:l=!0,deduplicateIdentical:g=!0,conflictStrategy:d="last",preserveAllComments:h=!0}=b,u=[],r=0,f=new Map,o=[];for(let i of m){let a=`${i.kind}:${i.name}`,s=f.get(a);if(!s)s=[],f.set(a,s),o.push(a);s.push(i)}let t=[];for(let i of o){let a=f.get(i),s=a[0];if(a.length===1){t.push(s);continue}if(!(s.kind==="interface"&&c||s.kind==="module"&&e||s.kind==="type"&&n||s.kind==="enum"&&l)){t.push(...a);continue}let p=a;if(g)p=y(a);if(p.length===1){t.push(p[0]);continue}let x;switch(s.kind){case"interface":x=k(p,d,h);break;case"module":x=w(p,d,h);break;case"enum":x=M(p,d,h);break;case"type":x=A(p,d,h);break;default:x=p[0]}t.push(x),r+=p.length-1,u.push({name:s.name,kind:s.kind,sourceCount:p.length,memberCount:x.members?.length||0})}return{declarations:t,mergedCount:r,merges:u}}function y(m){let b=new Map;for(let c of m){let e=D(c.text);if(!b.has(e))b.set(e,c);else{let n=b.get(e);if((c.leadingComments?.length||0)>(n.leadingComments?.length||0))b.set(e,c)}}return Array.from(b.values())}function D(m){return m.replace(/\s+/g," ").replace(/;\s*/g,";").trim()}function k(m,b,c){let e=m[0],n=new Map,l=[],g=c?new Set:null;for(let a of m){if(c&&a.leadingComments&&g){for(let s of a.leadingComments)if(!g.has(s))g.add(s),l.push(s)}if(a.members)for(let s of a.members)if(!n.get(s.name))n.set(s.name,s);else switch(b){case"first":break;case"last":n.set(s.name,s);break;case"error":throw Error(`Conflicting member '${s.name}' in interface '${e.name}'`)}}let d=Array.from(n.values()),h=d.map((a)=>` ${a.text}`).join(`
|
|
3
3
|
`),u=e.generics||"",r=e.extends||"",f=new Set;for(let a of m)if(a.extends){let s=a.extends.split(",");for(let C of s){let p=C.trim();if(p)f.add(p)}}if(f.size>0)r=`extends ${Array.from(f).join(", ")}`;let o=e.isExported?"export ":"",t=e.modifiers?.includes("declare")?"declare ":"",i=`${o}${t}interface ${e.name}${u} ${r} {
|
|
4
4
|
${h}
|
|
5
5
|
}`;return{...e,members:d,leadingComments:l.length>0?l:e.leadingComments,text:i.replace(/\s+\{/," {").replace(/\{\s*\n\s*\n/,`{
|
|
@@ -9,10 +9,10 @@ ${h}
|
|
|
9
9
|
}`;return{...e,members:d,leadingComments:l.length>0?l:e.leadingComments,text:f}}function M(m,b,c){let e=m[0],n=new Map,l=[],g=c?new Set:null;for(let t of m){if(c&&t.leadingComments&&g){for(let i of t.leadingComments)if(!g.has(i))g.add(i),l.push(i)}if(t.members)for(let i of t.members)if(!n.get(i.name))n.set(i.name,i);else switch(b){case"first":break;case"last":n.set(i.name,i);break;case"error":throw Error(`Conflicting member '${i.name}' in enum '${e.name}'`)}}let d=Array.from(n.values()),h=d.map((t)=>` ${t.name}${t.value!==void 0?` = ${t.value}`:""}`).join(`,
|
|
10
10
|
`),u=e.isExported?"export ":"",r=e.modifiers?.includes("declare")?"declare ":"",f=e.modifiers?.includes("const")?"const ":"",o=`${u}${r}${f}enum ${e.name} {
|
|
11
11
|
${h}
|
|
12
|
-
}`;return{...e,members:d,leadingComments:l.length>0?l:e.leadingComments,text:o}}function A(m,b,c){let e=m[0],n=[],l=c?new Set:null,g=[],d=new Set;for(let o of m){if(c&&o.leadingComments&&l){for(let t of o.leadingComments)if(!l.has(t))l.add(t),n.push(t)}if(o.typeAnnotation&&!d.has(o.typeAnnotation))d.add(o.typeAnnotation),g.push(o.typeAnnotation)}if(g.length<=1)return{...e,leadingComments:n.length>0?n:e.leadingComments};let h=g.join(" | "),u=e.isExported?"export ":"",r=e.generics||"",f=`${u}type ${e.name}${r} = ${h}`;return{...e,typeAnnotation:h,leadingComments:n.length>0?n:e.leadingComments,text:f}}function
|
|
12
|
+
}`;return{...e,members:d,leadingComments:l.length>0?l:e.leadingComments,text:o}}function A(m,b,c){let e=m[0],n=[],l=c?new Set:null,g=[],d=new Set;for(let o of m){if(c&&o.leadingComments&&l){for(let t of o.leadingComments)if(!l.has(t))l.add(t),n.push(t)}if(o.typeAnnotation&&!d.has(o.typeAnnotation))d.add(o.typeAnnotation),g.push(o.typeAnnotation)}if(g.length<=1)return{...e,leadingComments:n.length>0?n:e.leadingComments};let h=g.join(" | "),u=e.isExported?"export ":"",r=e.generics||"",f=`${u}type ${e.name}${r} = ${h}`;return{...e,typeAnnotation:h,leadingComments:n.length>0?n:e.leadingComments,text:f}}function Ji(m,b={}){let c=m.split(`
|
|
13
13
|
`),e=new Map,n=null,l=0;for(let u=0;u<c.length;u++){let r=c[u],f=r.match(/^(export\s+)?(declare\s+)?interface\s+(\w+)/);if(f&&!n){n={name:f[3],start:u,lines:[r]},l=(r.match(/\{/g)||[]).length-(r.match(/\}/g)||[]).length;continue}if(n){if(n.lines.push(r),l+=(r.match(/\{/g)||[]).length-(r.match(/\}/g)||[]).length,l<=0){let o=e.get(n.name)||[];o.push({start:n.start,end:u,content:n.lines}),e.set(n.name,o),n=null,l=0}}}let g=Array.from(e.entries()).filter(([,u])=>u.length>1);if(g.length===0)return m;let d=[...c],h=new Set;for(let[u,r]of g){if(r.length<=1)continue;let[f,...o]=r,t=[],i=new Set;for(let C of r)for(let p of C.content){let x=p.trim();if(x.startsWith("interface")||x.startsWith("export")||x==="{"||x==="}")continue;if(x&&!i.has(x))i.add(x),t.push(p)}for(let C of o)for(let p=C.start;p<=C.end;p++)h.add(p);let a=f.content[0],s=[a.endsWith("{")?a:`${a} {`,...t,"}"];for(let C=f.start;C<=f.end;C++)h.add(C);d[f.start]=s.join(`
|
|
14
14
|
`)}return d.filter((u,r)=>!h.has(r)||d[r].includes("interface")).join(`
|
|
15
15
|
`).replace(/\n{3,}/g,`
|
|
16
16
|
|
|
17
17
|
`)}
|
|
18
|
-
export{
|
|
18
|
+
export{qi,Ji};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
class
|
|
3
|
-
`)}async writeResults(){if(!this.config.outputFile)return;let e=this.getResults(),t=JSON.stringify(e,null,2);try{let s=await import("fs/promises");await s.writeFile(this.config.outputFile,t,"utf-8")}catch{await Bun.write(this.config.outputFile,t)}}}function y(){if(typeof process<"u"&&process.memoryUsage){let e=process.memoryUsage();return{timestamp:Date.now(),heapUsed:e.heapUsed,heapTotal:e.heapTotal,external:e.external,arrayBuffers:e.arrayBuffers||0,rss:e.rss}}return{timestamp:Date.now(),heapUsed:0,heapTotal:0,external:0,arrayBuffers:0,rss:0}}function d(){if(typeof process<"u"&&process.cpuUsage){let e=process.cpuUsage();return{user:e.user,system:e.system}}return{user:0,system:0}}function n(e){if(e===0)return"0 B";let t=["B","KB","MB","GB"],s=1024,r=Math.floor(Math.log(e)/Math.log(s));return`${Number.parseFloat((e/s**r).toFixed(2))} ${t[r]}`}function
|
|
4
|
-
export{
|
|
2
|
+
class Ut{config;memorySamples=[];cpuSamples=[];ioOperations=[];startTime=0;memoryInterval=null;cpuInterval=null;lastCpuUsage=null;isRunning=!1;constructor(e={}){this.config={memory:e.memory??!1,memoryLimit:e.memoryLimit??1024,cpu:e.cpu??!1,samplingInterval:e.samplingInterval??100,io:e.io??!1,trackOperations:e.trackOperations??["read","write"],outputFile:e.outputFile??""}}start(){if(this.isRunning)return;if(this.isRunning=!0,this.startTime=Date.now(),this.memorySamples=[],this.cpuSamples=[],this.ioOperations=[],this.lastCpuUsage=null,this.config.memory)this.sampleMemory(),this.memoryInterval=setInterval(()=>this.sampleMemory(),this.config.samplingInterval);if(this.config.cpu)this.sampleCpu(),this.cpuInterval=setInterval(()=>this.sampleCpu(),this.config.samplingInterval)}stop(){if(!this.isRunning)return;if(this.isRunning=!1,this.memoryInterval)clearInterval(this.memoryInterval),this.memoryInterval=null;if(this.cpuInterval)clearInterval(this.cpuInterval),this.cpuInterval=null}sampleMemory(){let e=y();this.memorySamples.push(e)}sampleCpu(){let e=d();if(this.lastCpuUsage){let t={timestamp:Date.now(),user:e.user-this.lastCpuUsage.user,system:e.system-this.lastCpuUsage.system,total:e.user-this.lastCpuUsage.user+(e.system-this.lastCpuUsage.system)};this.cpuSamples.push(t)}this.lastCpuUsage=e}recordIo(e,t,s,r){if(!this.config.io)return;if(!this.config.trackOperations.includes(e))return;this.ioOperations.push({timestamp:Date.now(),operation:e,path:t,size:s,durationMs:r})}getResults(){let e=Date.now(),t=[],s=this.memorySamples[0]||y(),r=0;for(let a of this.memorySamples){if(r+=a.heapUsed,a.heapUsed>s.heapUsed)s=a;let g=a.heapUsed/1048576;if(g>this.config.memoryLimit)t.push(`Memory limit exceeded at ${new Date(a.timestamp).toISOString()}: ${g.toFixed(2)}MB > ${this.config.memoryLimit}MB`)}let i=this.memorySamples.length>0?r/this.memorySamples.length:0,o=0,m=0;for(let a of this.cpuSamples)o+=a.user,m+=a.system;let u=0,l=0,p=0,h=0,c=0,f=0;for(let a of this.ioOperations)if(a.operation==="read")u++,p+=a.size,c+=a.durationMs;else l++,h+=a.size,f+=a.durationMs;return{startTime:this.startTime,endTime:e,durationMs:e-this.startTime,memory:{samples:this.memorySamples,peak:s,average:{timestamp:0,heapUsed:i,heapTotal:0,external:0,arrayBuffers:0,rss:0},warnings:t},cpu:{samples:this.cpuSamples,totalUser:o,totalSystem:m},io:{operations:this.ioOperations,totalReads:u,totalWrites:l,totalReadBytes:p,totalWriteBytes:h,totalReadMs:c,totalWriteMs:f}}}formatResults(){let e=this.getResults(),t=["=== Profiling Results ===",""];if(t.push(`Duration: ${e.durationMs}ms`),t.push(""),this.config.memory){if(t.push("Memory:"),t.push(` Samples: ${e.memory.samples.length}`),t.push(` Peak heap: ${n(e.memory.peak.heapUsed)}`),t.push(` Average heap: ${n(e.memory.average.heapUsed)}`),e.memory.warnings.length>0){t.push(" Warnings:");for(let s of e.memory.warnings)t.push(` - ${s}`)}t.push("")}if(this.config.cpu)t.push("CPU:"),t.push(` Samples: ${e.cpu.samples.length}`),t.push(` Total user time: ${(e.cpu.totalUser/1000).toFixed(2)}ms`),t.push(` Total system time: ${(e.cpu.totalSystem/1000).toFixed(2)}ms`),t.push("");if(this.config.io)t.push("I/O:"),t.push(` Total reads: ${e.io.totalReads}`),t.push(` Total writes: ${e.io.totalWrites}`),t.push(` Total read: ${n(e.io.totalReadBytes)} in ${e.io.totalReadMs.toFixed(2)}ms`),t.push(` Total write: ${n(e.io.totalWriteBytes)} in ${e.io.totalWriteMs.toFixed(2)}ms`),t.push("");return t.join(`
|
|
3
|
+
`)}async writeResults(){if(!this.config.outputFile)return;let e=this.getResults(),t=JSON.stringify(e,null,2);try{let s=await import("fs/promises");await s.writeFile(this.config.outputFile,t,"utf-8")}catch{await Bun.write(this.config.outputFile,t)}}}function y(){if(typeof process<"u"&&process.memoryUsage){let e=process.memoryUsage();return{timestamp:Date.now(),heapUsed:e.heapUsed,heapTotal:e.heapTotal,external:e.external,arrayBuffers:e.arrayBuffers||0,rss:e.rss}}return{timestamp:Date.now(),heapUsed:0,heapTotal:0,external:0,arrayBuffers:0,rss:0}}function d(){if(typeof process<"u"&&process.cpuUsage){let e=process.cpuUsage();return{user:e.user,system:e.system}}return{user:0,system:0}}function n(e){if(e===0)return"0 B";let t=["B","KB","MB","GB"],s=1024,r=Math.floor(Math.log(e)/Math.log(s));return`${Number.parseFloat((e/s**r).toFixed(2))} ${t[r]}`}function yr(e){return new Ut(e)}async function ts(e,t){let s=yr({memory:!0,cpu:!0,...t});s.start();try{return{result:await e(),profile:s.getResults()}}finally{s.stop()}}function ns(e){return{async read(t,s){let r=Date.now();try{let i=await s(),o=typeof i==="string"?i.length:0;return e.recordIo("read",t,o,Date.now()-r),i}catch(i){throw e.recordIo("read",t,0,Date.now()-r),i}},async write(t,s,r){let i=Date.now();try{await s(),e.recordIo("write",t,r,Date.now()-i)}catch(o){throw e.recordIo("write",t,0,Date.now()-i),o}}}}class zt{marks=new Map;durations=new Map;mark(e){this.marks.set(e,performance.now())}measure(e,t){let s=this.marks.get(t);if(s===void 0)throw Error(`Mark "${t}" not found`);let r=performance.now()-s,i=this.durations.get(e)||[];return i.push(r),this.durations.set(e,i),r}getDurations(e){return this.durations.get(e)||[]}getAverage(e){let t=this.getDurations(e);if(t.length===0)return 0;return t.reduce((s,r)=>s+r,0)/t.length}getSummary(){let e=new Map;for(let[t,s]of this.durations)e.set(t,{count:s.length,total:s.reduce((r,i)=>r+i,0),average:s.reduce((r,i)=>r+i,0)/s.length,min:Math.min(...s),max:Math.max(...s)});return e}clear(){this.marks.clear(),this.durations.clear()}}function rs(){return new zt}
|
|
4
|
+
export{Ut,yr,ts,ns,zt,rs};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{e}from"./chunk-btc6zbyj.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 L}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&&T(r[0])&&"id"in r[0]&&r[0].id===3&&T(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(T(r)&&T(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(T(t)&&"arr"in t&&Array.isArray(t.arr)&&T(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&T(r[0])&&T(t[0])){let i=[...r];for(let s of t)if(T(s)&&"name"in s){if(!i.find((a)=>T(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(T(s)&&"path"in s){if(!i.find((a)=>T(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(!T(r)||!T(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(T(s)&&T(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&&T(s[0])&&T(n[i][0])){let o=[...s];for(let a of n[i])if(T(a)&&"name"in a){if(!o.find((c)=>T(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(T(a)&&"path"in a){if(!o.find((c)=>T(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(T(t)&&T(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 T(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 A(){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(A())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(A())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(!A()&&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?S.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} ${S.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&&!A()){let f=an[t],u=this.options.showTags!==!1&&this.name?S.gray(this.formatTag(this.name)):"",g;switch(t){case"debug":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:S.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:S.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-9hjd6p38.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 L}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&&T(r[0])&&"id"in r[0]&&r[0].id===3&&T(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(T(r)&&T(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(T(t)&&"arr"in t&&Array.isArray(t.arr)&&T(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&T(r[0])&&T(t[0])){let i=[...r];for(let s of t)if(T(s)&&"name"in s){if(!i.find((a)=>T(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(T(s)&&"path"in s){if(!i.find((a)=>T(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(!T(r)||!T(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(T(s)&&T(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&&T(s[0])&&T(n[i][0])){let o=[...s];for(let a of n[i])if(T(a)&&"name"in a){if(!o.find((c)=>T(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(T(a)&&"path"in a){if(!o.find((c)=>T(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(T(t)&&T(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 T(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 A(){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(A())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(A())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(!A()&&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?S.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} ${S.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&&!A()){let f=an[t],u=this.options.showTags!==!1&&this.name?S.gray(this.formatTag(this.name)):"",g;switch(t){case"debug":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:S.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:S.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:S.gray(` ${h}`),level:t,showTimestamp:!1}))}break}}else if(!A()){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&&!A()){let n=this.options.showTags!==!1&&this.name?S.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:S.blue("\u25D0"),tag:n,message:`${S.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(k){if($n(k)||!c)return null;throw k}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 F=Y(m,o);h.push(F);let z=f?$e(i,c,g):c,_=await this.fileLoader.tryLoadFromPaths([F],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: ${F}`);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((k)=>Object.hasOwn(m,k)&&(u||Boolean(m[k])));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 B={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{...B,...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 Zo(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:{...B,cwd:r}}),cwd:r}})(),ct.set(r,n);try{return await n}catch(i){throw ct.delete(r),i}}function Qo(){ct.clear()}function ea(t){return{...B,...t}}function ta(t){return async()=>{let r=await t();return{...B,...r}}}var E=B;
|
|
62
|
-
export{B,
|
|
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(k){if($n(k)||!c)return null;throw k}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 F=Y(m,o);h.push(F);let z=f?$e(i,c,g):c,_=await this.fileLoader.tryLoadFromPaths([F],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: ${F}`);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((k)=>Object.hasOwn(m,k)&&(u||Boolean(m[k])));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 B={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{...B,...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 ta(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:{...B,cwd:r}}),cwd:r}})(),ct.set(r,n);try{return await n}catch(i){throw ct.delete(r),i}}function na(){ct.clear()}function ra(t){return{...B,...t}}function ia(t){return async()=>{let r=await t();return{...B,...r}}}var E=B;
|
|
62
|
+
export{B,ta,na,ra,ia,E};
|