@dtsx/dtsx 0.11.46 → 0.11.48

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.
Files changed (124) hide show
  1. package/dist/bin/cli.js +1 -1
  2. package/dist/{chunk-2h5p8n7w.js → chunk-02yqpwv0.js} +2 -2
  3. package/dist/{chunk-0gwj2fct.js → chunk-1dnqddk9.js} +1 -1
  4. package/dist/chunk-29m9mhwt.js +3 -0
  5. package/dist/{chunk-0nw1w523.js → chunk-475bjqea.js} +4 -4
  6. package/dist/{chunk-6m8f0y7w.js → chunk-4e02xmrg.js} +1 -1
  7. package/dist/{chunk-ga769zw5.js → chunk-4kv50gfv.js} +1 -1
  8. package/dist/{chunk-c7dw612y.js → chunk-564pr6v4.js} +1 -1
  9. package/dist/{chunk-2wxgt73q.js → chunk-689tfwjh.js} +1 -1
  10. package/dist/{chunk-nmjxxcvg.js → chunk-8dyz1cte.js} +8 -8
  11. package/dist/{chunk-ry1c863d.js → chunk-8hwmssy9.js} +1 -1
  12. package/dist/{chunk-rkpwmkrm.js → chunk-adhnnbe1.js} +1 -1
  13. package/dist/{chunk-kdqckf54.js → chunk-agq858s0.js} +1 -1
  14. package/dist/{chunk-trvp818c.js → chunk-atzh1g6f.js} +1 -1
  15. package/dist/{chunk-pjqd38w1.js → chunk-bxjswrak.js} +1 -1
  16. package/dist/{chunk-xg8yhpe6.js → chunk-c87yyjv7.js} +2 -2
  17. package/dist/{chunk-hcf0hd85.js → chunk-cgrta603.js} +1 -1
  18. package/dist/{chunk-em9pz9s0.js → chunk-cgz4sy6k.js} +1 -1
  19. package/dist/chunk-d0dbet9n.js +7 -0
  20. package/dist/{chunk-z0aa0gd8.js → chunk-d27xpsa4.js} +1 -1
  21. package/dist/{chunk-ehpz5rg3.js → chunk-ex02f2vm.js} +15 -15
  22. package/dist/{chunk-ac95p5v4.js → chunk-fkngq7na.js} +3 -3
  23. package/dist/{chunk-j32xn94r.js → chunk-fn2xxavw.js} +1 -1
  24. package/dist/{chunk-yaej6q2v.js → chunk-g4eb5tgt.js} +1 -1
  25. package/dist/{chunk-gsvb5wey.js → chunk-h2007n8k.js} +1 -1
  26. package/dist/{chunk-6bmr0e81.js → chunk-h5esm323.js} +2 -2
  27. package/dist/{chunk-zaka2jk1.js → chunk-h6ngkqg7.js} +1 -1
  28. package/dist/{chunk-t89jepjk.js → chunk-hnw7mwcw.js} +1 -1
  29. package/dist/chunk-hzjesnf1.js +38 -0
  30. package/dist/{chunk-dpd2b7dd.js → chunk-hzybfasv.js} +1 -1
  31. package/dist/{chunk-2xp48sa2.js → chunk-jjdjk59m.js} +1 -1
  32. package/dist/{chunk-yapmefw7.js → chunk-kdz4gxdq.js} +18 -18
  33. package/dist/{chunk-t7jvkq9j.js → chunk-mjaf2je8.js} +1 -1
  34. package/dist/{chunk-0af0hsfc.js → chunk-mm1cfz16.js} +4 -4
  35. package/dist/{chunk-swmftav9.js → chunk-nf10pph8.js} +1 -1
  36. package/dist/{chunk-h7tsf2qg.js → chunk-nqdc6n5d.js} +21 -21
  37. package/dist/chunk-p458sykz.js +3 -0
  38. package/dist/{chunk-1xgcs6aq.js → chunk-pkdrq4sh.js} +1 -1
  39. package/dist/{chunk-kp6qv2fb.js → chunk-qpahzkm0.js} +1 -1
  40. package/dist/{chunk-k472ve44.js → chunk-r2h572w9.js} +1 -1
  41. package/dist/{chunk-nxqap7nx.js → chunk-rkdyetby.js} +1 -1
  42. package/dist/{chunk-rdb7j1d6.js → chunk-s6bjmr93.js} +2 -2
  43. package/dist/{chunk-k75z3nef.js → chunk-vhna4qch.js} +2 -2
  44. package/dist/{chunk-986k5306.js → chunk-vk5r6pgx.js} +2 -2
  45. package/dist/{chunk-hbe5sg17.js → chunk-vwn5fx4f.js} +1 -1
  46. package/dist/chunk-w5m9qv5k.js +10 -0
  47. package/dist/{chunk-v4z6808c.js → chunk-wrvgt39b.js} +1 -1
  48. package/dist/{chunk-thzkm86y.js → chunk-x5bspdyq.js} +1 -1
  49. package/dist/chunk-xs0ke3f2.js +27 -0
  50. package/dist/{chunk-dw84pjmf.js → chunk-y3vhsctr.js} +1 -1
  51. package/dist/{chunk-y1xq2hm4.js → chunk-zerajrvv.js} +1 -1
  52. package/dist/{chunk-4mrq1jdn.js → chunk-zesjexqf.js} +1 -1
  53. package/dist/{chunk-wrjrwren.js → chunk-znsgvx9t.js} +1 -1
  54. package/dist/src/augmentation-graph.js +1 -1
  55. package/dist/src/binding-patterns.js +1 -1
  56. package/dist/src/bundle-linker.js +1 -1
  57. package/dist/src/bundler.js +1 -1
  58. package/dist/src/cache.js +1 -1
  59. package/dist/src/call-signatures.js +1 -1
  60. package/dist/src/circular.js +1 -1
  61. package/dist/src/compat.js +1 -1
  62. package/dist/src/computed-keys.js +1 -1
  63. package/dist/src/config.js +1 -1
  64. package/dist/src/declaration-project.js +1 -1
  65. package/dist/src/declaration-publication.js +1 -1
  66. package/dist/src/declaration-references.js +1 -1
  67. package/dist/src/diff.js +1 -1
  68. package/dist/src/docs.js +1 -1
  69. package/dist/src/enum-declarations.js +1 -1
  70. package/dist/src/errors.js +1 -1
  71. package/dist/src/extractor/extract.js +1 -1
  72. package/dist/src/extractor/scanner.js +1 -1
  73. package/dist/src/extractor.js +1 -1
  74. package/dist/src/function-properties.js +1 -1
  75. package/dist/src/generator.js +1 -1
  76. package/dist/src/index.js +1 -1
  77. package/dist/src/inferred-imports.js +1 -1
  78. package/dist/src/initializer-type-spans.js +1 -1
  79. package/dist/src/lexical.js +1 -1
  80. package/dist/src/lsp.js +1 -1
  81. package/dist/src/module-graph.js +1 -1
  82. package/dist/src/module-references.js +1 -1
  83. package/dist/src/native-checker.js +1 -1
  84. package/dist/src/native-extractor.js +1 -1
  85. package/dist/src/native-generation.js +1 -1
  86. package/dist/src/native-project.js +1 -1
  87. package/dist/src/numeric-literals.js +1 -1
  88. package/dist/src/optimizer.js +1 -1
  89. package/dist/src/parallel-processor.js +1 -1
  90. package/dist/src/parameters.js +1 -1
  91. package/dist/src/parser.js +1 -1
  92. package/dist/src/plugins/bun.js +1 -1
  93. package/dist/src/plugins/esbuild.js +1 -1
  94. package/dist/src/plugins/index.js +1 -1
  95. package/dist/src/plugins/tsdown.js +1 -1
  96. package/dist/src/plugins/tsup.js +1 -1
  97. package/dist/src/plugins/vite.js +1 -1
  98. package/dist/src/plugins/webpack.js +1 -1
  99. package/dist/src/process-source.js +1 -1
  100. package/dist/src/processor/declarations.js +1 -1
  101. package/dist/src/processor/import-usage.js +1 -1
  102. package/dist/src/processor/imports.js +1 -1
  103. package/dist/src/processor/index.js +1 -1
  104. package/dist/src/processor/type-inference.js +1 -1
  105. package/dist/src/processor.js +1 -1
  106. package/dist/src/return-type-scope.js +1 -1
  107. package/dist/src/security.js +1 -1
  108. package/dist/src/utils.js +1 -1
  109. package/dist/src/value-inference.js +1 -1
  110. package/dist/src/worker-thread.js +1 -1
  111. package/dist/src/workspace.js +1 -1
  112. package/native/darwin-arm64/libzig-dtsx.dylib +0 -0
  113. package/native/darwin-x64/libzig-dtsx.dylib +0 -0
  114. package/native/freebsd-x64/libzig-dtsx.so +0 -0
  115. package/native/linux-arm64/libzig-dtsx.so +0 -0
  116. package/native/linux-x64/libzig-dtsx.so +0 -0
  117. package/native/windows-x64/zig-dtsx.dll +0 -0
  118. package/package.json +1 -1
  119. package/dist/chunk-8ab8793q.js +0 -27
  120. package/dist/chunk-jtq24yb8.js +0 -3
  121. package/dist/chunk-kcbbz8t7.js +0 -37
  122. package/dist/chunk-t03y036d.js +0 -3
  123. package/dist/chunk-tsbthwf0.js +0 -7
  124. package/dist/chunk-vdhzc40m.js +0 -10
@@ -7,16 +7,16 @@ import{e}from"./chunk-qmg1535a.js";import Qt from"process";import{existsSync as
7
7
  `),a=Math.max(...o.map((u)=>u.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,c=`\u2514${"\u2500".repeat(a)}\u2518`,f=o.map((u)=>{let g=" ".repeat(a-u.length-2);return`\u2502 ${u}${g} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:x.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(l)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(c),showTimestamp:!1}))}else if(!k())console.error(`${i} ${this.environment}.INFO: [BOX] ${t}`);let s=`${i} ${this.environment}.INFO: [BOX] ${t}
8
8
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}async prompt(t){if(k())return Promise.resolve(!0);return new Promise((r)=>{console.error(`${x.cyan("?")} ${t} (y/n) `);let n=(i)=>{let s=i.toString().trim().toLowerCase();N.stdin.removeListener("data",n);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),r(s==="y"||s==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...r){if(!this.enabled)return;let n=t;if(r&&r.length>0){let a=/%([sdijfo%])/g,l=0;if(n=t.replace(a,(c,f)=>{if(f==="%")return"%";if(l>=r.length)return c;let u=r[l++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),l<r.length)n+=` ${r.slice(l).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!k()){let a=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",l=x.blue("\u25D0");console.error(`${l} ${a} ${x.cyan(n)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
9
9
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(o)}progress(t,r=""){if(!this.enabled||!this.fancy||k()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:t,current:0,message:r,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(a,l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,a)),l!==void 0)this.activeProgressBar.message=l;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(a)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=this.activeProgressBar.total,a!==void 0)this.activeProgressBar.message=a;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(a,l="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(l,a),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,r=!1){if(!this.enabled||!this.fancy||k()||!N.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),i=Math.round(t.barLength*n/100),s=t.barLength-i,o=x.green("\u2501".repeat(i)),a=x.gray("\u2501".repeat(s)),l=`[${o}${a}]`,c=`${n}%`.padStart(4),f=t.message?` ${t.message}`:"",u=r||n===100?x.green("\u2713"):x.blue("\u25B6"),g=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",m=`\r${u}${g} ${l} ${c}${f}`,h=N.stdout.columns||80,y=" ".repeat(Math.max(0,h-m.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${m}${y}`,N.stdout.write(t.lastRenderedLine),r)N.stdout.write(`
10
- `)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||k()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(r)t.message=r;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let r=await ke(this.config.logDirectory),n=[];for(let i of r){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let o=fe(this.config.logDirectory,i);if(t.before)try{if((await le(o)).mtime>=t.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}n.push(o)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let i of n)try{await Ae(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(r){console.error("Error during log clearing process:",r)}}}function _e(t,r){if(Array.isArray(r)&&Array.isArray(t)&&r.length===2&&t.length===2&&E(r[0])&&"id"in r[0]&&r[0].id===3&&E(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(E(r)&&E(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(E(t)&&"arr"in t&&Array.isArray(t.arr)&&E(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&E(r[0])&&E(t[0])){let i=[...r];for(let s of t)if(E(s)&&"name"in s){if(!i.find((a)=>E(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(E(s)&&"path"in s){if(!i.find((a)=>E(a)&&("path"in a)&&a.path===s.path))i.push(s)}else if(!i.some((o)=>Xe(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(!E(r)||!E(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(E(s)&&E(n[i]))n[i]=_e(n[i],s);else if(Array.isArray(s)&&Array.isArray(n[i]))if(s.length>0&&n[i].length>0&&E(s[0])&&E(n[i][0])){let o=[...s];for(let a of n[i])if(E(a)&&"name"in a){if(!o.find((c)=>E(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(E(a)&&"path"in a){if(!o.find((c)=>E(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>Xe(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 Gt(t,r,n="replace"){if(r===null||r===void 0)return t;if(Array.isArray(r))return n==="replace"?r:_e(t,r);if(Array.isArray(t))return n==="replace"?r:_e(t,r);if(!E(r)||!E(t))return r;let i={...t};for(let s of Object.keys(r)){if(!Object.prototype.hasOwnProperty.call(r,s))continue;let o=r[s],a=i[s];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(a))if(n==="replace")i[s]=o;else i[s]=_e(a,o);else if(E(o)&&E(a))i[s]=Gt(a,o,n);else i[s]=o}return i}function Xe(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(!Xe(t[n],r[n]))return!1;return!0}if(E(t)&&E(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(!Xe(t[s],r[s]))return!1}return!0}return!1}function E(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Le(t,r,n="replace"){if(!Jr(t))return null;try{let i=await import(t),s=i.default||i;if(typeof s!=="object"||s===null||Array.isArray(s))return null;try{return Gt(r,s,n)}catch{return null}}catch{return null}}function Ri(t,r,n=!1){if(!t)return r;let i=t.toUpperCase().replace(/-/g,"_"),s={...r};function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=(d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase(),h=`${i}_${g.map(m).join("_")}`,y=`${i}_${g.map((d)=>d.toUpperCase()).join("_")}`;if(n)L.info(`Checking environment variable ${h} for config ${t}.${g.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=o(u,g);else{let d=Ee.env[h]||Ee.env[y];if(d!==void 0){if(n)L.info(`Using environment variable ${d?h:y} for config ${t}.${g.join(".")}`);if(typeof u==="number")c[f]=Number(d);else if(typeof u==="boolean")c[f]=d.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(d);if(Array.isArray(p))c[f]=p;else c[f]=d.split(",").map((T)=>T.trim())}catch{c[f]=d.split(",").map((p)=>p.trim())}else c[f]=d}}}return c}return o(s)}async function Pi({name:t="",alias:r,cwd:n,configDir:i,defaultConfig:s,verbose:o=!1,checkEnv:a=!0,arrayStrategy:l="replace"}){let c=a&&typeof s==="object"&&s!==null&&!Array.isArray(s)?Ri(t,s,o):s,f=n||Ee.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)L.info(`Loading configuration for "${t}"${r?` (alias: "${r}")`:""} from ${f}`);let g=[t,`.${t}`].filter(Boolean),m=[`${t}.config`,`.${t}.config`].filter(Boolean),h=r?[r,`.${r}`]:[],y=r?[`${r}.config`,`.${r}.config`]:[],d=Array.from(new Set([f,B(f,"config"),B(f,".config"),i?B(f,i):void 0].filter(Boolean)));for(let p of d){if(o)L.info(`Searching for configuration in: ${p}`);let F=[B(f,"config"),B(f,".config")].concat(i?[B(f,i)]:[]).includes(p)?[...g,...m,...h,...y]:[...m,...g,...y,...h];for(let z of F)for(let _ of u){let U=B(p,`${z}${_}`),er=await Le(U,c,l);if(er!==null){if(o)L.success(`Configuration loaded from: ${U}`);return er}}}if(t){let p=B(lt(),".config",t),T=["config",`${t}.config`];if(r)T.push(`${r}.config`);if(o)L.info(`Checking user config directory: ${p}`);for(let F of T)for(let z of u){let _=B(p,`${F}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user config directory: ${_}`);return U}}}if(t){let p=B(lt(),".config"),T=[`.${t}.config`];if(r)T.push(`.${r}.config`);if(o)L.info(`Checking user config directory for dotfile configs: ${p}`);for(let F of T)for(let z of u){let _=B(p,`${F}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user config directory dotfile: ${_}`);return U}}}if(t){let p=lt(),T=[`.${t}.config`,`.${t}`];if(r)T.push(`.${r}.config`),T.push(`.${r}`);if(o)L.info(`Checking user home directory for dotfile configs: ${p}`);for(let F of T)for(let z of u){let _=B(p,`${F}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user home directory: ${_}`);return U}}}try{let p=B(f,"package.json");if(Jr(p)){let T=await import(p),F=T[t];if(!F&&r){if(F=T[r],F&&o)L.success(`Using alias "${r}" configuration from package.json`)}if(F&&typeof F==="object"&&!Array.isArray(F))try{if(o)L.success(`Configuration loaded from package.json: ${F===T[t]?t:r}`);return Gt(c,F,l)}catch(z){if(o)L.warn("Failed to merge package.json config:",z)}}}catch(p){if(o)L.warn("Failed to load package.json:",p)}if(o)L.info(`No configuration found for "${t}"${r?` or alias "${r}"`:""}, using default configuration with environment variables`);return c}function Di(t,r={}){let n=Ge.cwd();while(n.includes("storage"))n=or(n,"..");let i=or(n,t||"");if(r?.relative)return Bn(Ge.cwd(),i);return i}async function Ni(){try{let t=await Pi({name:"clarity",alias:"logging",defaultConfig:We,cwd:Ge.cwd()});return{...We,...t||{}}}catch{return We}}function O(){if(Q.env.NODE_ENV==="test"||Q.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Mi(){if(Q.env.NODE_ENV==="test"||Q.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Q<"u"){let t=Q.type;if(t==="renderer"||t==="worker")return!1;return!!(Q.versions&&(Q.versions.node||Q.versions.bun))}return!1}class Zr{async format(t){let r=await Mi(),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:me.pid,hostname:r(),environment:me.env.NODE_ENV||"development",platform:me.platform,version:me.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:me.env.NODE_ENV||me.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Qe{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,r={}){this.name=t,this.config={...Nt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new Zr,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??C.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()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let r={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return r[t]>=r[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...ze,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...ze};return{...ze,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:Nt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,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}shouldWriteToFile(){return!O()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await Xn(this.config.logDirectory,yr.F_OK|yr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Qn(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:H.from(t);try{if(!Fe(this.currentLogFile))await pt(this.currentLogFile,"",{mode:420});if(s=pr(this.currentLogFile,"a",420),Zn(s,c,{flag:"a"}),dr(s),s!==void 0)dt(s),s=void 0;if((await ge(this.currentLogFile)).size===0){if(await pt(this.currentLogFile,c,{flag:"w",mode:420}),(await ge(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{dt(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 he(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 he(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return he(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(O())return;if(!this.shouldWriteToFile())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 mt(16).toString("hex")}generateKey(){return mt(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=mt(16),i=qn("aes-256-gcm",r,n),s=H.isBuffer(t)?t:H.from(t,"utf8"),o=i.update(s),a=i.final(),l=o.length+a.length,c=i.getAuthTag(),f=H.allocUnsafe(16+l+16);return n.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:n}}async compressData(t){return new Promise((r,n)=>{let i=vr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(H.from(H.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(O())return;if(!this.shouldWriteToFile())return;let t=await ge(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 Oe(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 ge(n).catch(()=>null))try{if(await wr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Re(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 pt(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 ge(n).catch(()=>null))await wr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await Oe(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await Re(he(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=mr(t),i=Hn(r),s=vr();await ri(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);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}}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()})),Fe(this.currentLogFile))try{let t=pr(this.currentLogFile,"r+");dr(t),dt(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(!O()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await Oe(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await Re(he(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.shouldStyleConsole()?w.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||O())return!1;let t=typeof C.env.NO_COLOR<"u",r=C.env.FORCE_COLOR==="0";if(t||r)return!1;return!!(typeof C.stderr<"u"&&C.stderr.isTTY||typeof C.stdout<"u"&&C.stdout.isTTY)}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=C.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} ${w.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}formatMarkdown(t){if(!t)return t;let r=t;return r=r.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,i,s)=>{let o=w.underline(w.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),r=r.replace(/`([^`]+)`/g,(n,i)=>w.bgGray(i)),r=r.replace(/\*\*([^*]+)\*\*/g,(n,i)=>w.bold(i)),r=r.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,i)=>w.italic(i)),r=r.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,i)=>w.italic(i)),r=r.replace(/~([^~]+)~/g,(n,i)=>w.strikethrough(i)),r}supportsHyperlinks(){if(O())return!1;let t=C.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let r=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(r)&&r>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let r=t;if(r.startsWith("file://"))r=r.replace(/^file:\/\//,"");if(r.startsWith("~")){let n=C.env.HOME||"";if(n)r=r.replace(/^~(?=$|\/)/,n)}if(ei(r)||r.startsWith("./")||r.startsWith("../"))r=ti(r);else return null;return Fe(r)?r:null}catch{return null}}buildOutputTexts(t){let r=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:r,fileText:n}}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);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":cn[t],m=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",h;switch(t){case"debug":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:w.gray(c),level:t}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:w.green(c),level:t}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.error(h),l){let y=l.split(`
11
- `);for(let d of y)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:w.gray(` ${d}`),level:t,showTimestamp:!1}))}break}}else if(!O()){if(console.error(`${o} ${this.environment}.${t.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(t))return;let u=`${o} ${this.environment}.${t.toUpperCase()}: ${f}
10
+ `)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||k()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(r)t.message=r;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let r=await ke(this.config.logDirectory),n=[];for(let i of r){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let o=fe(this.config.logDirectory,i);if(t.before)try{if((await le(o)).mtime>=t.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}n.push(o)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let i of n)try{await Ae(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(r){console.error("Error during log clearing process:",r)}}}function _e(t,r){if(Array.isArray(r)&&Array.isArray(t)&&r.length===2&&t.length===2&&E(r[0])&&"id"in r[0]&&r[0].id===3&&E(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(E(r)&&E(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(E(t)&&"arr"in t&&Array.isArray(t.arr)&&E(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&E(r[0])&&E(t[0])){let i=[...r];for(let s of t)if(E(s)&&"name"in s){if(!i.find((a)=>E(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(E(s)&&"path"in s){if(!i.find((a)=>E(a)&&("path"in a)&&a.path===s.path))i.push(s)}else if(!i.some((o)=>Xe(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(!E(r)||!E(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(E(s)&&E(n[i]))n[i]=_e(n[i],s);else if(Array.isArray(s)&&Array.isArray(n[i]))if(s.length>0&&n[i].length>0&&E(s[0])&&E(n[i][0])){let o=[...s];for(let a of n[i])if(E(a)&&"name"in a){if(!o.find((c)=>E(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(E(a)&&"path"in a){if(!o.find((c)=>E(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>Xe(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 Gt(t,r,n="replace"){if(r===null||r===void 0)return t;if(Array.isArray(r))return n==="replace"?r:_e(t,r);if(Array.isArray(t))return n==="replace"?r:_e(t,r);if(!E(r)||!E(t))return r;let i={...t};for(let s of Object.keys(r)){if(!Object.prototype.hasOwnProperty.call(r,s))continue;let o=r[s],a=i[s];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(a))if(n==="replace")i[s]=o;else i[s]=_e(a,o);else if(E(o)&&E(a))i[s]=Gt(a,o,n);else i[s]=o}return i}function Xe(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(!Xe(t[n],r[n]))return!1;return!0}if(E(t)&&E(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(!Xe(t[s],r[s]))return!1}return!0}return!1}function E(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Le(t,r,n="replace"){if(!Jr(t))return null;try{let i=await import(t),s=i.default||i;if(typeof s!=="object"||s===null||Array.isArray(s))return null;try{return Gt(r,s,n)}catch{return null}}catch{return null}}function Ri(t,r,n=!1){if(!t)return r;let i=t.toUpperCase().replace(/-/g,"_"),s={...r};function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=(d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase(),h=`${i}_${g.map(m).join("_")}`,y=`${i}_${g.map((d)=>d.toUpperCase()).join("_")}`;if(n)L.info(`Checking environment variable ${h} for config ${t}.${g.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=o(u,g);else{let d=Ee.env[h]||Ee.env[y];if(d!==void 0){if(n)L.info(`Using environment variable ${d?h:y} for config ${t}.${g.join(".")}`);if(typeof u==="number")c[f]=Number(d);else if(typeof u==="boolean")c[f]=d.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(d);if(Array.isArray(p))c[f]=p;else c[f]=d.split(",").map((T)=>T.trim())}catch{c[f]=d.split(",").map((p)=>p.trim())}else c[f]=d}}}return c}return o(s)}async function Pi({name:t="",alias:r,cwd:n,configDir:i,defaultConfig:s,verbose:o=!1,checkEnv:a=!0,arrayStrategy:l="replace"}){let c=a&&typeof s==="object"&&s!==null&&!Array.isArray(s)?Ri(t,s,o):s,f=n||Ee.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)L.info(`Loading configuration for "${t}"${r?` (alias: "${r}")`:""} from ${f}`);let g=[t,`.${t}`].filter(Boolean),m=[`${t}.config`,`.${t}.config`].filter(Boolean),h=r?[r,`.${r}`]:[],y=r?[`${r}.config`,`.${r}.config`]:[],d=Array.from(new Set([f,B(f,"config"),B(f,".config"),i?B(f,i):void 0].filter(Boolean)));for(let p of d){if(o)L.info(`Searching for configuration in: ${p}`);let A=[B(f,"config"),B(f,".config")].concat(i?[B(f,i)]:[]).includes(p)?[...g,...m,...h,...y]:[...m,...g,...y,...h];for(let z of A)for(let _ of u){let U=B(p,`${z}${_}`),er=await Le(U,c,l);if(er!==null){if(o)L.success(`Configuration loaded from: ${U}`);return er}}}if(t){let p=B(lt(),".config",t),T=["config",`${t}.config`];if(r)T.push(`${r}.config`);if(o)L.info(`Checking user config directory: ${p}`);for(let A of T)for(let z of u){let _=B(p,`${A}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user config directory: ${_}`);return U}}}if(t){let p=B(lt(),".config"),T=[`.${t}.config`];if(r)T.push(`.${r}.config`);if(o)L.info(`Checking user config directory for dotfile configs: ${p}`);for(let A of T)for(let z of u){let _=B(p,`${A}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user config directory dotfile: ${_}`);return U}}}if(t){let p=lt(),T=[`.${t}.config`,`.${t}`];if(r)T.push(`.${r}.config`),T.push(`.${r}`);if(o)L.info(`Checking user home directory for dotfile configs: ${p}`);for(let A of T)for(let z of u){let _=B(p,`${A}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user home directory: ${_}`);return U}}}try{let p=B(f,"package.json");if(Jr(p)){let T=await import(p),A=T[t];if(!A&&r){if(A=T[r],A&&o)L.success(`Using alias "${r}" configuration from package.json`)}if(A&&typeof A==="object"&&!Array.isArray(A))try{if(o)L.success(`Configuration loaded from package.json: ${A===T[t]?t:r}`);return Gt(c,A,l)}catch(z){if(o)L.warn("Failed to merge package.json config:",z)}}}catch(p){if(o)L.warn("Failed to load package.json:",p)}if(o)L.info(`No configuration found for "${t}"${r?` or alias "${r}"`:""}, using default configuration with environment variables`);return c}function Di(t,r={}){let n=Ge.cwd();while(n.includes("storage"))n=or(n,"..");let i=or(n,t||"");if(r?.relative)return Bn(Ge.cwd(),i);return i}async function Ni(){try{let t=await Pi({name:"clarity",alias:"logging",defaultConfig:We,cwd:Ge.cwd()});return{...We,...t||{}}}catch{return We}}function F(){if(Q.env.NODE_ENV==="test"||Q.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Mi(){if(Q.env.NODE_ENV==="test"||Q.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Q<"u"){let t=Q.type;if(t==="renderer"||t==="worker")return!1;return!!(Q.versions&&(Q.versions.node||Q.versions.bun))}return!1}class Zr{async format(t){let r=await Mi(),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:me.pid,hostname:r(),environment:me.env.NODE_ENV||"development",platform:me.platform,version:me.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:me.env.NODE_ENV||me.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Qe{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,r={}){this.name=t,this.config={...Nt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new Zr,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??C.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()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let r={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return r[t]>=r[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...ze,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...ze};return{...ze,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:Nt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,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}shouldWriteToFile(){return!F()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await Xn(this.config.logDirectory,yr.F_OK|yr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Qn(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:H.from(t);try{if(!Fe(this.currentLogFile))await pt(this.currentLogFile,"",{mode:420});if(s=pr(this.currentLogFile,"a",420),Zn(s,c,{flag:"a"}),dr(s),s!==void 0)dt(s),s=void 0;if((await ge(this.currentLogFile)).size===0){if(await pt(this.currentLogFile,c,{flag:"w",mode:420}),(await ge(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{dt(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 he(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 he(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return he(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(F())return;if(!this.shouldWriteToFile())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 mt(16).toString("hex")}generateKey(){return mt(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=mt(16),i=qn("aes-256-gcm",r,n),s=H.isBuffer(t)?t:H.from(t,"utf8"),o=i.update(s),a=i.final(),l=o.length+a.length,c=i.getAuthTag(),f=H.allocUnsafe(16+l+16);return n.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:n}}async compressData(t){return new Promise((r,n)=>{let i=vr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(H.from(H.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(F())return;if(!this.shouldWriteToFile())return;let t=await ge(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 Oe(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 ge(n).catch(()=>null))try{if(await wr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Re(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 pt(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 ge(n).catch(()=>null))await wr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await Oe(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await Re(he(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=mr(t),i=Hn(r),s=vr();await ri(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);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}}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()})),Fe(this.currentLogFile))try{let t=pr(this.currentLogFile,"r+");dr(t),dt(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(!F()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await Oe(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await Re(he(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.shouldStyleConsole()?w.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F())return!1;let t=typeof C.env.NO_COLOR<"u",r=C.env.FORCE_COLOR==="0";if(t||r)return!1;return!!(typeof C.stderr<"u"&&C.stderr.isTTY||typeof C.stdout<"u"&&C.stdout.isTTY)}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=C.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} ${w.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}formatMarkdown(t){if(!t)return t;let r=t;return r=r.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,i,s)=>{let o=w.underline(w.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),r=r.replace(/`([^`]+)`/g,(n,i)=>w.bgGray(i)),r=r.replace(/\*\*([^*]+)\*\*/g,(n,i)=>w.bold(i)),r=r.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,i)=>w.italic(i)),r=r.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,i)=>w.italic(i)),r=r.replace(/~([^~]+)~/g,(n,i)=>w.strikethrough(i)),r}supportsHyperlinks(){if(F())return!1;let t=C.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let r=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(r)&&r>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let r=t;if(r.startsWith("file://"))r=r.replace(/^file:\/\//,"");if(r.startsWith("~")){let n=C.env.HOME||"";if(n)r=r.replace(/^~(?=$|\/)/,n)}if(ei(r)||r.startsWith("./")||r.startsWith("../"))r=ti(r);else return null;return Fe(r)?r:null}catch{return null}}buildOutputTexts(t){let r=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:r,fileText:n}}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);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":cn[t],m=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",h;switch(t){case"debug":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:w.gray(c),level:t}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:w.green(c),level:t}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.error(h),l){let y=l.split(`
11
+ `);for(let d of y)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:w.gray(` ${d}`),level:t,showTimestamp:!1}))}break}}else if(!F()){if(console.error(`${o} ${this.environment}.${t.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(t))return;let u=`${o} ${this.environment}.${t.toUpperCase()}: ${f}
12
12
  `;if(l)u+=`${l}
13
- `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,r=""){let n={update:(l,c)=>{},finish:(l)=>{},interrupt:(l,c)=>{}};if(!this.enabled)return n;let i=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:r||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!O()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!O()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,c="info")=>{if(!O()&&C.stdout.isTTY)C.stdout.write(`
14
- `);if(this[c==="warning"?"warn":c](l),this.activeProgressBar&&this.shouldStyleConsole()&&!O()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let r=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":w.blue("\u25D0"),tag:n,message:`${w.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+=`
15
- `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":w.green("\u2713"),tag:u,message:`${o}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!O())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug(t,...r){await this.log("debug",t,...r)}async info(t,...r){await this.log("info",t,...r)}async success(t,...r){await this.log("success",t,...r)}async warn(t,...r){await this.log("warning",t,...r)}async error(t,...r){await this.log("error",t,...r)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:r}=t;return!!r}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let r=`${this.name}:${t}`,n=new Qe(r,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(O())throw Error("createReadStream is not supported in browser environments");if(!Fe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return mr(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let r=this.config.rotation;if(!r.encrypt||typeof r.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let i=H.isBuffer(t)?t:H.from(t,"base64"),s=i.subarray(0,16),o=i.subarray(i.length-16),a=i.subarray(16,i.length-16),l=Yn("aes-256-gcm",n,s);l.setAuthTag(o);let c=l.update(a),f=l.final(),u=c.length+f.length,g=H.allocUnsafe(u);return c.copy(g,0),f.copy(g,c.length),g.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return O()}isServerMode(){return!O()}setTestEncryptionKey(t,r){this.currentKeyId=t,this.keys.set(t,r)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let r=new Date,n=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),{consoleText:s,fileText:o}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let l=s.split(`
16
- `),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,g=l.map((m)=>this.formatConsoleMessage({timestamp:n,message:w.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:w.cyan(f),showTimestamp:!1})),g.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:n,message:w.cyan(u),showTimestamp:!1}))}else if(!O())console.error(`${i} ${this.environment}.INFO: [BOX] ${o}`);let a=`${i} ${this.environment}.INFO: [BOX] ${o}
17
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(t){if(O())return Promise.resolve(!0);return new Promise((r)=>{console.error(`${w.cyan("?")} ${t} (y/n) `);let n=(i)=>{let s=i.toString().trim().toLowerCase();C.stdin.removeListener("data",n);try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!1)}catch{}C.stdin.pause(),console.error(""),r(s==="y"||s==="yes")};try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!0)}catch{}C.stdin.resume(),C.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...r){if(!this.enabled)return;let n=t;if(r&&r.length>0){let c=/%([sdijfo%])/g,f=0;if(n=t.replace(c,(u,g)=>{if(g==="%")return"%";if(f>=r.length)return u;let m=r[f++];switch(g){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return u}}),f<r.length)n+=` ${r.slice(f).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:i,fileText:s}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",f=this.options.showIcons===!1?"":`${w.blue("\u25D0")} `;console.error(`${f}${c} ${w.cyan(i)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
13
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,r=""){let n={update:(l,c)=>{},finish:(l)=>{},interrupt:(l,c)=>{}};if(!this.enabled)return n;let i=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:r||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!F()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!F()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,c="info")=>{if(!F()&&C.stdout.isTTY)C.stdout.write(`
14
+ `);if(this[c==="warning"?"warn":c](l),this.activeProgressBar&&this.shouldStyleConsole()&&!F()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let r=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":w.blue("\u25D0"),tag:n,message:`${w.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+=`
15
+ `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":w.green("\u2713"),tag:u,message:`${o}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!F())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug(t,...r){await this.log("debug",t,...r)}async info(t,...r){await this.log("info",t,...r)}async success(t,...r){await this.log("success",t,...r)}async warn(t,...r){await this.log("warning",t,...r)}async error(t,...r){await this.log("error",t,...r)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:r}=t;return!!r}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let r=`${this.name}:${t}`,n=new Qe(r,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(F())throw Error("createReadStream is not supported in browser environments");if(!Fe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return mr(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let r=this.config.rotation;if(!r.encrypt||typeof r.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let i=H.isBuffer(t)?t:H.from(t,"base64"),s=i.subarray(0,16),o=i.subarray(i.length-16),a=i.subarray(16,i.length-16),l=Yn("aes-256-gcm",n,s);l.setAuthTag(o);let c=l.update(a),f=l.final(),u=c.length+f.length,g=H.allocUnsafe(u);return c.copy(g,0),f.copy(g,c.length),g.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F()}isServerMode(){return!F()}setTestEncryptionKey(t,r){this.currentKeyId=t,this.keys.set(t,r)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let r=new Date,n=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),{consoleText:s,fileText:o}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let l=s.split(`
16
+ `),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,g=l.map((m)=>this.formatConsoleMessage({timestamp:n,message:w.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:w.cyan(f),showTimestamp:!1})),g.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:n,message:w.cyan(u),showTimestamp:!1}))}else if(!F())console.error(`${i} ${this.environment}.INFO: [BOX] ${o}`);let a=`${i} ${this.environment}.INFO: [BOX] ${o}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(t){if(F())return Promise.resolve(!0);return new Promise((r)=>{console.error(`${w.cyan("?")} ${t} (y/n) `);let n=(i)=>{let s=i.toString().trim().toLowerCase();C.stdin.removeListener("data",n);try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!1)}catch{}C.stdin.pause(),console.error(""),r(s==="y"||s==="yes")};try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!0)}catch{}C.stdin.resume(),C.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...r){if(!this.enabled)return;let n=t;if(r&&r.length>0){let c=/%([sdijfo%])/g,f=0;if(n=t.replace(c,(u,g)=>{if(g==="%")return"%";if(f>=r.length)return u;let m=r[f++];switch(g){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return u}}),f<r.length)n+=` ${r.slice(f).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:i,fileText:s}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",f=this.options.showIcons===!1?"":`${w.blue("\u25D0")} `;console.error(`${f}${c} ${w.cyan(i)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
18
18
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(t,r=!1){if(!this.enabled||!this.shouldStyleConsole()||!C.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),i=Math.round(t.barLength*n/100),s=t.barLength-i,o=w.green("\u2501".repeat(i)),a=w.gray("\u2501".repeat(s)),l=`[${o}${a}]`,c=`${n}%`.padStart(4),f=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":r||n===100?w.green("\u2713"):w.blue("\u25B6"),g=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",m=`\r${u}${g} ${l} ${c}${f}`,h=C.stdout.columns||80,y=" ".repeat(Math.max(0,h-m.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${m}${y}`,C.stdout.write(t.lastRenderedLine),r)C.stdout.write(`
19
- `)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||O()||!C.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(r)t.message=r;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(O()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let r=await Oe(this.config.logDirectory),n=[];for(let i of r){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let o=he(this.config.logDirectory,i);if(t.before)try{if((await ge(o)).mtime>=t.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}n.push(o)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let i of n)try{await Re(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(r){console.error("Error during log clearing process:",r)}}}async function Xr(t,r={}){let{maxRetries:n=3,retryDelay:i=1000,isRetryable:s=()=>!0,fallback:o}=r,a=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(c){if(a=c instanceof Error?c:Error(String(c)),l===n||!s(a))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(o!==void 0)return o;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function Qr(t){return t instanceof K}function ji(t){return t instanceof et}function Li(t){if(Qr(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>t.message.toLowerCase().includes(n.toLowerCase()))}class st{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,r)=>r==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let r=t.toLowerCase();return["true","1","yes"].includes(r)}},{name:"number",canParse:(t,r)=>r==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let r=Number(t);if(Number.isNaN(r))throw TypeError(`Cannot parse "${t}" as number`);return r}},{name:"array",canParse:(t,r)=>r==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return t.split(",").map((r)=>r.trim())}},{name:"json",canParse:(t,r)=>r==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(r){throw Error(`Cannot parse "${t}" as JSON: ${r}`)}}}]}async applyEnvironmentVariables(t,r,n={}){let{prefix:i,useCamelCase:s=!0,useBackwardCompatibility:o=!0,customParsers:a={},verbose:l=!1,trackPerformance:c=!0}=n,f=async()=>{if(!t)return{config:r,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(t),g={...r};return this.processObject(g,[],u,{useCamelCase:s,useBackwardCompatibility:o,customParsers:a,verbose:l,configName:t}),{config:g,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Te.track("applyEnvironmentVariables",f,{configName:t});return f()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,r){if(!r)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${n}_${l.join("_")}`,f=i.useBackwardCompatibility?`${n}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,a,n,i);else{let u=Pe.env[c]||(f?Pe.env[f]:void 0);if(u!==void 0){if(i.verbose){let g=Pe.env[c]?c:f}try{t[s]=this.parseEnvironmentValue(u,typeof o,c,i.customParsers,i.configName)}catch(g){if(g instanceof tt)throw g;throw ie.envVar(c,u,typeof o,i.configName)}}}}}parseEnvironmentValue(t,r,n,i,s){for(let[o,a]of Object.entries(i))try{return a(t)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(t,r))try{return o.parse(t)}catch{throw ie.envVar(n,t,`${r} (via ${o.name} parser)`,s)}return t}getEnvironmentVariables(t){let r={},n=t.toUpperCase();for(let[i,s]of Object.entries(Pe.env))if(i.startsWith(n)&&s!==void 0)r[i]=s;return r}validateEnvironmentVariable(t,r,n){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))i.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,r,n,{})}catch(s){i.push(`Cannot parse value "${r}" as ${n}: ${s}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(t,r,n={}){let{prefix:i,format:s="text"}=n,o=i||this.generateEnvPrefix(t),a=[];switch(this.extractEnvVarInfo(r,[],o,a),s){case"markdown":return this.formatAsMarkdown(a,t);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,t)}}extractEnvVarInfo(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=`${n}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,a,n,i);else i.push({key:l,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${a.join(".")}`,example:this.generateExample(o)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,r){let n=`Environment Variables for ${r}:
19
+ `)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||F()||!C.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(r)t.message=r;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(F()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let r=await Oe(this.config.logDirectory),n=[];for(let i of r){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let o=he(this.config.logDirectory,i);if(t.before)try{if((await ge(o)).mtime>=t.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}n.push(o)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let i of n)try{await Re(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(r){console.error("Error during log clearing process:",r)}}}async function Xr(t,r={}){let{maxRetries:n=3,retryDelay:i=1000,isRetryable:s=()=>!0,fallback:o}=r,a=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(c){if(a=c instanceof Error?c:Error(String(c)),l===n||!s(a))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(o!==void 0)return o;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function Qr(t){return t instanceof K}function ji(t){return t instanceof et}function Li(t){if(Qr(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>t.message.toLowerCase().includes(n.toLowerCase()))}class st{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,r)=>r==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let r=t.toLowerCase();return["true","1","yes"].includes(r)}},{name:"number",canParse:(t,r)=>r==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let r=Number(t);if(Number.isNaN(r))throw TypeError(`Cannot parse "${t}" as number`);return r}},{name:"array",canParse:(t,r)=>r==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return t.split(",").map((r)=>r.trim())}},{name:"json",canParse:(t,r)=>r==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(r){throw Error(`Cannot parse "${t}" as JSON: ${r}`)}}}]}async applyEnvironmentVariables(t,r,n={}){let{prefix:i,useCamelCase:s=!0,useBackwardCompatibility:o=!0,customParsers:a={},verbose:l=!1,trackPerformance:c=!0}=n,f=async()=>{if(!t)return{config:r,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(t),g={...r};return this.processObject(g,[],u,{useCamelCase:s,useBackwardCompatibility:o,customParsers:a,verbose:l,configName:t}),{config:g,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Te.track("applyEnvironmentVariables",f,{configName:t});return f()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,r){if(!r)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${n}_${l.join("_")}`,f=i.useBackwardCompatibility?`${n}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,a,n,i);else{let u=Pe.env[c]||(f?Pe.env[f]:void 0);if(u!==void 0){if(i.verbose){let g=Pe.env[c]?c:f}try{t[s]=this.parseEnvironmentValue(u,typeof o,c,i.customParsers,i.configName)}catch(g){if(g instanceof tt)throw g;throw ie.envVar(c,u,typeof o,i.configName)}}}}}parseEnvironmentValue(t,r,n,i,s){for(let[o,a]of Object.entries(i))try{return a(t)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(t,r))try{return o.parse(t)}catch{throw ie.envVar(n,t,`${r} (via ${o.name} parser)`,s)}return t}getEnvironmentVariables(t){let r={},n=t.toUpperCase();for(let[i,s]of Object.entries(Pe.env))if(i.startsWith(n)&&s!==void 0)r[i]=s;return r}validateEnvironmentVariable(t,r,n){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))i.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,r,n,{})}catch(s){i.push(`Cannot parse value "${r}" as ${n}: ${s}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(t,r,n={}){let{prefix:i,format:s="text"}=n,o=i||this.generateEnvPrefix(t),a=[];switch(this.extractEnvVarInfo(r,[],o,a),s){case"markdown":return this.formatAsMarkdown(a,t);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,t)}}extractEnvVarInfo(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=`${n}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,a,n,i);else i.push({key:l,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${a.join(".")}`,example:this.generateExample(o)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,r){let n=`Environment Variables for ${r}:
20
20
 
21
21
  `;for(let i of t)n+=`${i.key}
22
22
  `,n+=` Type: ${i.type}
@@ -37,16 +37,16 @@ ${s.map((f)=>{let u=$r(r,f.file).replace(/\\/g,"/");return` '${f.base}': typeof
37
37
  export type ConfigByName = ${l}
38
38
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
39
  export type ConfigOf = Config
40
- `}return{name:"bunfig-plugin",setup(s){s.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),s.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var sn,ve,Te,on,Yi,Hi,Fr,Ke,Dt,M,x,Zi,Or,Xi,Rr,Qi,es,bt,ts,Pr,Dr,Et,rs,ns,is,ss,Ve,an,os,L,as,cs,Nr,We,Nt,R,w,ls,Mr,fs,jr,us,gs,xt,hs,Lr,Br,ms,St,ds,ps,ys,ws,vs,ze,cn,$s,Cs="0.15.6",K,et,xe,Mt,jt,tt,Lt,Bt,Se,It,_t,ie,ln,fn,G,te,un,gn,bs=bi(async()=>{sn=import.meta.require,ve=new Wt,Te=new zt,on={createKey:Ei,isEquivalent:xi,estimateMemoryUsage:Si},Yi=qe(Rt.cwd(),"config"),Hi=qe(Rt.cwd(),"src/generated"),Fr=Je.env.CLARITY_LOG_DIR||In(Ai(),"logs"),Ke={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Fr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Dt=await Fi(),M={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},x=M,Zi=M.red,Or=M.green,Xi=M.yellow,Rr=M.blue,Qi=M.magenta,es=M.cyan,bt=M.white,ts=M.gray,Pr=M.bgRed,Dr=M.bgYellow,Et=M.bold,rs=M.dim,ns=M.italic,is=M.underline,ss=M.reset,Ve={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},an={debug:"\uD83D\uDD0D",info:Rr("\u2139"),success:Or("\u2713"),warning:Dr(bt(Et(" WARN "))),error:Pr(bt(Et(" ERROR ")))},os=new Ze("stacks"),L=new Ze("bunfig",{showTags:!0}),as=B(Ee.cwd(),"config"),cs=B(Ee.cwd(),"src/generated"),Nr=Ge.env.CLARITY_LOG_DIR||Ln(Di(),"logs"),We={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Nr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Nt=await Ni(),R={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},w=R,ls=R.red,Mr=R.green,fs=R.yellow,jr=R.blue,us=R.magenta,gs=R.cyan,xt=R.white,hs=R.gray,Lr=R.bgRed,Br=R.bgYellow,ms=R.bgGray,St=R.bold,ds=R.dim,ps=R.italic,ys=R.underline,ws=R.strikethrough,vs=R.reset,ze={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cn={debug:"\uD83D\uDD0D",info:jr("\u2139"),success:Mr("\u2713"),warning:Br(xt(St(" WARN "))),error:Lr(xt(St(" ERROR ")))},$s=new Qe("stacks"),K=class extends Error{timestamp;context;constructor(r,n={}){super(r);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let r=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,i])=>`${n}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${r}`}},et=class extends K{code="CONFIG_NOT_FOUND";constructor(r,n,i){let s=i?` or alias "${i}"`:"";super(`Configuration "${r}"${s} not found`,{configName:r,alias:i,searchPaths:n,searchPathCount:n.length})}},xe=class extends K{code="CONFIG_LOAD_ERROR";constructor(r,n,i){super(`Failed to load configuration from "${r}": ${n.message}`,{configPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Mt=class extends K{code="CONFIG_VALIDATION_ERROR";constructor(r,n,i){super(`Configuration validation failed for "${r}"`,{configPath:r,configName:i,validationErrors:n,errorCount:n.length})}},jt=class extends K{code="CONFIG_MERGE_ERROR";constructor(r,n,i,s){super(`Failed to merge configuration from "${r}" with "${n}": ${i.message}`,{sourcePath:r,targetPath:n,configName:s,originalError:i.name,originalMessage:i.message});this.cause=i}},tt=class extends K{code="ENV_VAR_ERROR";constructor(r,n,i,s){super(`Failed to parse environment variable "${r}" with value "${n}" as ${i}`,{envKey:r,envValue:n,expectedType:i,configName:s})}},Lt=class extends K{code="FILE_SYSTEM_ERROR";constructor(r,n,i){super(`File system ${r} failed for "${n}": ${i.message}`,{operation:r,path:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Bt=class extends K{code="TYPE_GENERATION_ERROR";constructor(r,n,i){super(`Failed to generate types from "${r}" to "${n}": ${i.message}`,{configDir:r,outputPath:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Se=class extends K{code="SCHEMA_VALIDATION_ERROR";constructor(r,n,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:r,configName:i,validationErrors:n,errorCount:n.length})}},It=class extends K{code="BROWSER_CONFIG_ERROR";constructor(r,n,i,s){super(`Failed to fetch configuration from "${r}": ${n} ${i}`,{endpoint:r,status:n,statusText:i,configName:s})}},_t=class extends K{code="PLUGIN_ERROR";constructor(r,n,i){super(`Plugin "${r}" failed during ${n}: ${i.message}`,{pluginName:r,operation:n,originalError:i.name,originalMessage:i.message});this.cause=i}},ie={configNotFound(t,r,n){return new et(t,r,n)},configLoad(t,r,n){return new xe(t,r,n)},configValidation(t,r,n){return new Mt(t,r,n)},configMerge(t,r,n,i){return new jt(t,r,n,i)},envVar(t,r,n,i){return new tt(t,r,n,i)},fileSystem(t,r,n){return new Lt(t,r,n)},typeGeneration(t,r,n){return new Bt(t,r,n)},schemaValidation(t,r,n){return new Se(t,r,n)},browserConfig(t,r,n,i){return new It(t,r,n,i)},plugin(t,r,n){return new _t(t,r,n)}},ln={replace:"replace",concat:"concat",smart:"smart"},fn=/^https?:\/\//,G=new Qe("bunfig",{showTags:!0}),te=new Yt,un=I(oe.cwd(),"config"),gn=I(oe.cwd(),"src/generated")});function Es(t,r={}){let n=Ye.cwd();while(n.includes("storage"))n=Cr(n,"..");let i=Cr(n,t||"");if(r?.relative)return ci(Ye.cwd(),i);return i}var xs=Ye.env.CLARITY_LOG_DIR||ai(Es(),"logs"),hn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},rt={...hn},Ca=(async()=>{try{let{loadConfig:t}=await bs().then(()=>Yr),r=await t({name:"clarity",alias:"logging",defaultConfig:hn,cwd:Ye.cwd()});if(r)Object.assign(rt,r)}catch{}return rt})();function P(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ss(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ee<"u"){let t=ee.type;if(t==="renderer"||t==="worker")return!1;return!!(ee.versions&&(ee.versions.node||ee.versions.bun))}return!1}class mn{async format(t){let r=await Ss(),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:ye.pid,hostname:r(),environment:ye.env.NODE_ENV||"development",platform:ye.platform,version:ye.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ye.env.NODE_ENV||ye.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var D={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},v=D,{red:ba,green:Ts,yellow:Ea,blue:ks,magenta:xa,cyan:Sa,white:Ir,gray:Ta,bgRed:As,bgYellow:Fs,bgGray:ka,bold:_r,dim:Aa,italic:Fa,underline:Oa,strikethrough:Ra,reset:Pa}=D,Tt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Os={debug:"\uD83D\uDD0D",info:ks("\u2139"),success:Ts("\u2713"),warning:Fs(Ir(_r(" WARN "))),error:As(Ir(_r(" ERROR ")))};class at{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,r={}){this.name=t,this.config={...rt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new mn,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??b.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,level:this.options.level??"info"},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()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let r={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return r[t]>=r[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Tt,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Tt};return{...Tt,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:rt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,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}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await hi(this.config.logDirectory,Sr.F_OK|Sr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await mi(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:Z.from(t);try{if(!Ne(this.currentLogFile))await Ct(this.currentLogFile,"",{mode:420});if(s=xr(this.currentLogFile,"a",420),gi(s,c,{flag:"a"}),Er(s),s!==void 0)$t(s),s=void 0;if((await de(this.currentLogFile)).size===0){if(await Ct(this.currentLogFile,c,{flag:"w",mode:420}),(await de(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{$t(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 pe(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 pe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return pe(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())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 vt(16).toString("hex")}generateKey(){return vt(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=vt(16),i=li("aes-256-gcm",r,n),s=Z.isBuffer(t)?t:Z.from(t,"utf8"),o=i.update(s),a=i.final(),l=o.length+a.length,c=i.getAuthTag(),f=Z.allocUnsafe(16+l+16);return n.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:n}}async compressData(t){return new Promise((r,n)=>{let i=kr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(Z.from(Z.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(P())return;if(!this.shouldWriteToFile())return;let t=await de(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 Me(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 de(n).catch(()=>null))try{if(await Tr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await je(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 Ct(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 de(n).catch(()=>null))await Tr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await Me(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await je(pe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=br(t),i=ui(r),s=kr();await yi(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);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}}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()})),Ne(this.currentLogFile))try{let t=xr(this.currentLogFile,"r+");Er(t),$t(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(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await Me(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await je(pe(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.shouldStyleConsole()?v.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof b.env.NO_COLOR<"u",r=b.env.FORCE_COLOR==="0";if(t||r)return!1;return!!(typeof b.stderr<"u"&&b.stderr.isTTY||typeof b.stdout<"u"&&b.stdout.isTTY)}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=b.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} ${v.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}formatMarkdown(t){if(!t)return t;let r=t;return r=r.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,i,s)=>{let o=v.underline(v.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),r=r.replace(/`([^`]+)`/g,(n,i)=>v.bgGray(i)),r=r.replace(/\*\*([^*]+)\*\*/g,(n,i)=>v.bold(i)),r=r.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,i)=>v.italic(i)),r=r.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,i)=>v.italic(i)),r=r.replace(/~([^~]+)~/g,(n,i)=>v.strikethrough(i)),r}supportsHyperlinks(){if(P())return!1;let t=b.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let r=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(r)&&r>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let r=t;if(r.startsWith("file://"))r=r.replace(/^file:\/\//,"");if(r.startsWith("~")){let n=b.env.HOME||"";if(n)r=r.replace(/^~(?=$|\/)/,n)}if(di(r)||r.startsWith("./")||r.startsWith("../"))r=pi(r);else return null;return Ne(r)?r:null}catch{return null}}buildOutputTexts(t){let r=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:r,fileText:n}}async log(t,r,...n){if(!this.shouldLog(t))return;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);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":Os[t],m=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",h;switch(t){case"debug":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.gray(c),level:t}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.green(c),level:t}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.error(h),l){let y=l.split(`
41
- `);for(let d of y)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:v.gray(` ${d}`),level:t,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${o} ${this.environment}.${t.toUpperCase()}: ${a}`),l)console.error(l)}let u=`${o} ${this.environment}.${t.toUpperCase()}: ${f}
40
+ `}return{name:"bunfig-plugin",setup(s){s.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),s.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var sn,ve,Te,on,Yi,Hi,Fr,Ke,Dt,M,x,Zi,Or,Xi,Rr,Qi,es,bt,ts,Pr,Dr,Et,rs,ns,is,ss,Ve,an,os,L,as,cs,Nr,We,Nt,O,w,ls,Mr,fs,jr,us,gs,xt,hs,Lr,Br,ms,St,ds,ps,ys,ws,vs,ze,cn,$s,Cs="0.15.6",K,et,xe,Mt,jt,tt,Lt,Bt,Se,It,_t,ie,ln,fn,G,te,un,gn,bs=bi(async()=>{sn=import.meta.require,ve=new Wt,Te=new zt,on={createKey:Ei,isEquivalent:xi,estimateMemoryUsage:Si},Yi=qe(Rt.cwd(),"config"),Hi=qe(Rt.cwd(),"src/generated"),Fr=Je.env.CLARITY_LOG_DIR||In(Ai(),"logs"),Ke={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Fr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Dt=await Fi(),M={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},x=M,Zi=M.red,Or=M.green,Xi=M.yellow,Rr=M.blue,Qi=M.magenta,es=M.cyan,bt=M.white,ts=M.gray,Pr=M.bgRed,Dr=M.bgYellow,Et=M.bold,rs=M.dim,ns=M.italic,is=M.underline,ss=M.reset,Ve={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},an={debug:"\uD83D\uDD0D",info:Rr("\u2139"),success:Or("\u2713"),warning:Dr(bt(Et(" WARN "))),error:Pr(bt(Et(" ERROR ")))},os=new Ze("stacks"),L=new Ze("bunfig",{showTags:!0}),as=B(Ee.cwd(),"config"),cs=B(Ee.cwd(),"src/generated"),Nr=Ge.env.CLARITY_LOG_DIR||Ln(Di(),"logs"),We={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Nr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Nt=await Ni(),O={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},w=O,ls=O.red,Mr=O.green,fs=O.yellow,jr=O.blue,us=O.magenta,gs=O.cyan,xt=O.white,hs=O.gray,Lr=O.bgRed,Br=O.bgYellow,ms=O.bgGray,St=O.bold,ds=O.dim,ps=O.italic,ys=O.underline,ws=O.strikethrough,vs=O.reset,ze={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cn={debug:"\uD83D\uDD0D",info:jr("\u2139"),success:Mr("\u2713"),warning:Br(xt(St(" WARN "))),error:Lr(xt(St(" ERROR ")))},$s=new Qe("stacks"),K=class extends Error{timestamp;context;constructor(r,n={}){super(r);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let r=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,i])=>`${n}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${r}`}},et=class extends K{code="CONFIG_NOT_FOUND";constructor(r,n,i){let s=i?` or alias "${i}"`:"";super(`Configuration "${r}"${s} not found`,{configName:r,alias:i,searchPaths:n,searchPathCount:n.length})}},xe=class extends K{code="CONFIG_LOAD_ERROR";constructor(r,n,i){super(`Failed to load configuration from "${r}": ${n.message}`,{configPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Mt=class extends K{code="CONFIG_VALIDATION_ERROR";constructor(r,n,i){super(`Configuration validation failed for "${r}"`,{configPath:r,configName:i,validationErrors:n,errorCount:n.length})}},jt=class extends K{code="CONFIG_MERGE_ERROR";constructor(r,n,i,s){super(`Failed to merge configuration from "${r}" with "${n}": ${i.message}`,{sourcePath:r,targetPath:n,configName:s,originalError:i.name,originalMessage:i.message});this.cause=i}},tt=class extends K{code="ENV_VAR_ERROR";constructor(r,n,i,s){super(`Failed to parse environment variable "${r}" with value "${n}" as ${i}`,{envKey:r,envValue:n,expectedType:i,configName:s})}},Lt=class extends K{code="FILE_SYSTEM_ERROR";constructor(r,n,i){super(`File system ${r} failed for "${n}": ${i.message}`,{operation:r,path:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Bt=class extends K{code="TYPE_GENERATION_ERROR";constructor(r,n,i){super(`Failed to generate types from "${r}" to "${n}": ${i.message}`,{configDir:r,outputPath:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Se=class extends K{code="SCHEMA_VALIDATION_ERROR";constructor(r,n,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:r,configName:i,validationErrors:n,errorCount:n.length})}},It=class extends K{code="BROWSER_CONFIG_ERROR";constructor(r,n,i,s){super(`Failed to fetch configuration from "${r}": ${n} ${i}`,{endpoint:r,status:n,statusText:i,configName:s})}},_t=class extends K{code="PLUGIN_ERROR";constructor(r,n,i){super(`Plugin "${r}" failed during ${n}: ${i.message}`,{pluginName:r,operation:n,originalError:i.name,originalMessage:i.message});this.cause=i}},ie={configNotFound(t,r,n){return new et(t,r,n)},configLoad(t,r,n){return new xe(t,r,n)},configValidation(t,r,n){return new Mt(t,r,n)},configMerge(t,r,n,i){return new jt(t,r,n,i)},envVar(t,r,n,i){return new tt(t,r,n,i)},fileSystem(t,r,n){return new Lt(t,r,n)},typeGeneration(t,r,n){return new Bt(t,r,n)},schemaValidation(t,r,n){return new Se(t,r,n)},browserConfig(t,r,n,i){return new It(t,r,n,i)},plugin(t,r,n){return new _t(t,r,n)}},ln={replace:"replace",concat:"concat",smart:"smart"},fn=/^https?:\/\//,G=new Qe("bunfig",{showTags:!0}),te=new Yt,un=I(oe.cwd(),"config"),gn=I(oe.cwd(),"src/generated")});function Es(t,r={}){let n=Ye.cwd();while(n.includes("storage"))n=Cr(n,"..");let i=Cr(n,t||"");if(r?.relative)return ci(Ye.cwd(),i);return i}var xs=Ye.env.CLARITY_LOG_DIR||ai(Es(),"logs"),hn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},rt={...hn},Ca=(async()=>{try{let{loadConfig:t}=await bs().then(()=>Yr),r=await t({name:"clarity",alias:"logging",defaultConfig:hn,cwd:Ye.cwd()});if(r)Object.assign(rt,r)}catch{}return rt})();function R(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ss(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ee<"u"){let t=ee.type;if(t==="renderer"||t==="worker")return!1;return!!(ee.versions&&(ee.versions.node||ee.versions.bun))}return!1}class mn{async format(t){let r=await Ss(),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:ye.pid,hostname:r(),environment:ye.env.NODE_ENV||"development",platform:ye.platform,version:ye.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ye.env.NODE_ENV||ye.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var D={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},v=D,{red:ba,green:Ts,yellow:Ea,blue:ks,magenta:xa,cyan:Sa,white:Ir,gray:Ta,bgRed:As,bgYellow:Fs,bgGray:ka,bold:_r,dim:Aa,italic:Fa,underline:Oa,strikethrough:Ra,reset:Pa}=D,Tt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Os={debug:"\uD83D\uDD0D",info:ks("\u2139"),success:Ts("\u2713"),warning:Fs(Ir(_r(" WARN "))),error:As(Ir(_r(" ERROR ")))};class at{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,r={}){this.name=t,this.config={...rt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new mn,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??b.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,level:this.options.level??"info"},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()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let r={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return r[t]>=r[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Tt,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Tt};return{...Tt,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:rt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,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}shouldWriteToFile(){return!R()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await hi(this.config.logDirectory,Sr.F_OK|Sr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await mi(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:Z.from(t);try{if(!Ne(this.currentLogFile))await Ct(this.currentLogFile,"",{mode:420});if(s=xr(this.currentLogFile,"a",420),gi(s,c,{flag:"a"}),Er(s),s!==void 0)$t(s),s=void 0;if((await de(this.currentLogFile)).size===0){if(await Ct(this.currentLogFile,c,{flag:"w",mode:420}),(await de(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{$t(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 pe(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 pe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return pe(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(R())return;if(!this.shouldWriteToFile())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 vt(16).toString("hex")}generateKey(){return vt(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=vt(16),i=li("aes-256-gcm",r,n),s=Z.isBuffer(t)?t:Z.from(t,"utf8"),o=i.update(s),a=i.final(),l=o.length+a.length,c=i.getAuthTag(),f=Z.allocUnsafe(16+l+16);return n.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:n}}async compressData(t){return new Promise((r,n)=>{let i=kr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(Z.from(Z.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(R())return;if(!this.shouldWriteToFile())return;let t=await de(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 Me(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 de(n).catch(()=>null))try{if(await Tr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await je(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 Ct(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 de(n).catch(()=>null))await Tr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await Me(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await je(pe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=br(t),i=ui(r),s=kr();await yi(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);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}}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()})),Ne(this.currentLogFile))try{let t=xr(this.currentLogFile,"r+");Er(t),$t(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(!R()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await Me(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await je(pe(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.shouldStyleConsole()?v.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||R())return!1;let t=typeof b.env.NO_COLOR<"u",r=b.env.FORCE_COLOR==="0";if(t||r)return!1;return!!(typeof b.stderr<"u"&&b.stderr.isTTY||typeof b.stdout<"u"&&b.stdout.isTTY)}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=b.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} ${v.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}formatMarkdown(t){if(!t)return t;let r=t;return r=r.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,i,s)=>{let o=v.underline(v.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),r=r.replace(/`([^`]+)`/g,(n,i)=>v.bgGray(i)),r=r.replace(/\*\*([^*]+)\*\*/g,(n,i)=>v.bold(i)),r=r.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,i)=>v.italic(i)),r=r.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,i)=>v.italic(i)),r=r.replace(/~([^~]+)~/g,(n,i)=>v.strikethrough(i)),r}supportsHyperlinks(){if(R())return!1;let t=b.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let r=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(r)&&r>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let r=t;if(r.startsWith("file://"))r=r.replace(/^file:\/\//,"");if(r.startsWith("~")){let n=b.env.HOME||"";if(n)r=r.replace(/^~(?=$|\/)/,n)}if(di(r)||r.startsWith("./")||r.startsWith("../"))r=pi(r);else return null;return Ne(r)?r:null}catch{return null}}buildOutputTexts(t){let r=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:r,fileText:n}}async log(t,r,...n){if(!this.shouldLog(t))return;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);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":Os[t],m=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",h;switch(t){case"debug":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.gray(c),level:t}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.green(c),level:t}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.error(h),l){let y=l.split(`
41
+ `);for(let d of y)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:v.gray(` ${d}`),level:t,showTimestamp:!1}))}break}}else if(!R()){if(console.error(`${o} ${this.environment}.${t.toUpperCase()}: ${a}`),l)console.error(l)}let u=`${o} ${this.environment}.${t.toUpperCase()}: ${f}
42
42
  `;if(l)u+=`${l}
43
- `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,r=""){let n={update:(l,c)=>{},finish:(l)=>{},interrupt:(l,c)=>{}};if(!this.enabled)return n;let i=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:r||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!P()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,c="info")=>{if(!P()&&b.stdout.isTTY)b.stdout.write(`
44
- `);if(this[c==="warning"?"warn":c](l),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let r=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":v.blue("\u25D0"),tag:n,message:`${v.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+=`
45
- `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":v.green("\u2713"),tag:u,message:`${o}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!P())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug(t,...r){await this.log("debug",t,...r)}async info(t,...r){await this.log("info",t,...r)}async success(t,...r){await this.log("success",t,...r)}async warn(t,...r){await this.log("warning",t,...r)}async error(t,...r){await this.log("error",t,...r)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:r}=t;return!!r}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let r=`${this.name}:${t}`,n=new at(r,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!Ne(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return br(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let r=this.config.rotation;if(!r.encrypt||typeof r.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let i=Z.isBuffer(t)?t:Z.from(t,"base64"),s=i.subarray(0,16),o=i.subarray(i.length-16),a=i.subarray(16,i.length-16),l=fi("aes-256-gcm",n,s);l.setAuthTag(o);let c=l.update(a),f=l.final(),u=c.length+f.length,g=Z.allocUnsafe(u);return c.copy(g,0),f.copy(g,c.length),g.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P()}isServerMode(){return!P()}setTestEncryptionKey(t,r){this.currentKeyId=t,this.keys.set(t,r)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let r=new Date,n=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),{consoleText:s,fileText:o}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let l=s.split(`
46
- `),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,g=l.map((m)=>this.formatConsoleMessage({timestamp:n,message:v.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:v.cyan(f),showTimestamp:!1})),g.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:n,message:v.cyan(u),showTimestamp:!1}))}else if(!P())console.error(`${i} ${this.environment}.INFO: [BOX] ${o}`);let a=`${i} ${this.environment}.INFO: [BOX] ${o}
47
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((r)=>{console.error(`${v.cyan("?")} ${t} (y/n) `);let n=(i)=>{let s=i.toString().trim().toLowerCase();b.stdin.removeListener("data",n);try{if(typeof b.stdin.setRawMode==="function")b.stdin.setRawMode(!1)}catch{}b.stdin.pause(),console.error(""),r(s==="y"||s==="yes")};try{if(typeof b.stdin.setRawMode==="function")b.stdin.setRawMode(!0)}catch{}b.stdin.resume(),b.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...r){if(!this.enabled)return;let n=t;if(r&&r.length>0){let c=/%([sdijfo%])/g,f=0;if(n=t.replace(c,(u,g)=>{if(g==="%")return"%";if(f>=r.length)return u;let m=r[f++];switch(g){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return u}}),f<r.length)n+=` ${r.slice(f).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:i,fileText:s}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",f=this.options.showIcons===!1?"":`${v.blue("\u25D0")} `;console.error(`${f}${c} ${v.cyan(i)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
43
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,r=""){let n={update:(l,c)=>{},finish:(l)=>{},interrupt:(l,c)=>{}};if(!this.enabled)return n;let i=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:r||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!R()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!R()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,c="info")=>{if(!R()&&b.stdout.isTTY)b.stdout.write(`
44
+ `);if(this[c==="warning"?"warn":c](l),this.activeProgressBar&&this.shouldStyleConsole()&&!R()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let r=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":v.blue("\u25D0"),tag:n,message:`${v.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+=`
45
+ `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":v.green("\u2713"),tag:u,message:`${o}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!R())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug(t,...r){await this.log("debug",t,...r)}async info(t,...r){await this.log("info",t,...r)}async success(t,...r){await this.log("success",t,...r)}async warn(t,...r){await this.log("warning",t,...r)}async error(t,...r){await this.log("error",t,...r)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:r}=t;return!!r}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let r=`${this.name}:${t}`,n=new at(r,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(R())throw Error("createReadStream is not supported in browser environments");if(!Ne(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return br(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let r=this.config.rotation;if(!r.encrypt||typeof r.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let i=Z.isBuffer(t)?t:Z.from(t,"base64"),s=i.subarray(0,16),o=i.subarray(i.length-16),a=i.subarray(16,i.length-16),l=fi("aes-256-gcm",n,s);l.setAuthTag(o);let c=l.update(a),f=l.final(),u=c.length+f.length,g=Z.allocUnsafe(u);return c.copy(g,0),f.copy(g,c.length),g.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return R()}isServerMode(){return!R()}setTestEncryptionKey(t,r){this.currentKeyId=t,this.keys.set(t,r)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let r=new Date,n=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),{consoleText:s,fileText:o}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let l=s.split(`
46
+ `),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,g=l.map((m)=>this.formatConsoleMessage({timestamp:n,message:v.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:v.cyan(f),showTimestamp:!1})),g.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:n,message:v.cyan(u),showTimestamp:!1}))}else if(!R())console.error(`${i} ${this.environment}.INFO: [BOX] ${o}`);let a=`${i} ${this.environment}.INFO: [BOX] ${o}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(t){if(R())return Promise.resolve(!0);return new Promise((r)=>{console.error(`${v.cyan("?")} ${t} (y/n) `);let n=(i)=>{let s=i.toString().trim().toLowerCase();b.stdin.removeListener("data",n);try{if(typeof b.stdin.setRawMode==="function")b.stdin.setRawMode(!1)}catch{}b.stdin.pause(),console.error(""),r(s==="y"||s==="yes")};try{if(typeof b.stdin.setRawMode==="function")b.stdin.setRawMode(!0)}catch{}b.stdin.resume(),b.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...r){if(!this.enabled)return;let n=t;if(r&&r.length>0){let c=/%([sdijfo%])/g,f=0;if(n=t.replace(c,(u,g)=>{if(g==="%")return"%";if(f>=r.length)return u;let m=r[f++];switch(g){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return u}}),f<r.length)n+=` ${r.slice(f).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:i,fileText:s}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",f=this.options.showIcons===!1?"":`${v.blue("\u25D0")} `;console.error(`${f}${c} ${v.cyan(i)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
48
48
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(t,r=!1){if(!this.enabled||!this.shouldStyleConsole()||!b.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),i=Math.round(t.barLength*n/100),s=t.barLength-i,o=v.green("\u2501".repeat(i)),a=v.gray("\u2501".repeat(s)),l=`[${o}${a}]`,c=`${n}%`.padStart(4),f=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":r||n===100?v.green("\u2713"):v.blue("\u25B6"),g=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",m=`\r${u}${g} ${l} ${c}${f}`,h=b.stdout.columns||80,y=" ".repeat(Math.max(0,h-m.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${m}${y}`,b.stdout.write(t.lastRenderedLine),r)b.stdout.write(`
49
- `)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||P()||!b.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(r)t.message=r;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let r=await Me(this.config.logDirectory),n=[];for(let i of r){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let o=pe(this.config.logDirectory,i);if(t.before)try{if((await de(o)).mtime>=t.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}n.push(o)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let i of n)try{await je(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(r){console.error("Error during log clearing process:",r)}}}var Da=new at("stacks");class J extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class we extends J{name="ConfigNotFoundError";code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],s="";if(i.length===1)s=` or alias "${i[0]}"`;else if(i.length>1)s=` or aliases ${i.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${t}"${s} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}}class se extends J{name="ConfigLoadError";code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ht extends J{name="ConfigValidationError";code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}}class dn extends J{name="ConfigMergeError";code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class Zt extends J{name="EnvVarError";code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}}class pn extends J{name="FileSystemError";code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class yn extends J{name="TypeGenerationError";code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class nt extends J{name="SchemaValidationError";code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}}class wn extends J{name="BrowserConfigError";code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}}class vn extends J{name="PluginError";code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}}var ne={configNotFound(t,r,n){return new we(t,r,n)},configLoad(t,r,n){return new se(t,r,n)},configValidation(t,r,n){return new Ht(t,r,n)},configMerge(t,r,n,i){return new dn(t,r,n,i)},envVar(t,r,n,i){return new Zt(t,r,n,i)},fileSystem(t,r,n){return new pn(t,r,n)},typeGeneration(t,r,n){return new yn(t,r,n)},schemaValidation(t,r,n){return new nt(t,r,n)},browserConfig(t,r,n,i){return new wn(t,r,n,i)},plugin(t,r,n){return new vn(t,r,n)}};async function Rs(t,r={}){let{maxRetries:n=3,retryDelay:i=1000,isRetryable:s=()=>!0,fallback:o}=r,a=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(c){if(a=c instanceof Error?c:Error(String(c)),l===n||!s(a))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(o!==void 0)return o;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}class Xt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,r)=>r==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let r=t.toLowerCase();return["true","1","yes"].includes(r)}},{name:"number",canParse:(t,r)=>r==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let r=Number(t);if(Number.isNaN(r))throw TypeError(`Cannot parse "${t}" as number`);return r}},{name:"array",canParse:(t,r)=>r==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return t.split(",").map((r)=>r.trim())}},{name:"json",canParse:(t,r)=>r==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(r){throw Error(`Cannot parse "${t}" as JSON: ${r}`)}}}]}async applyEnvironmentVariables(t,r,n={}){let{prefix:i,useCamelCase:s=!0,useBackwardCompatibility:o=!0,customParsers:a={},verbose:l=!1,trackPerformance:c=!0}=n,f=async()=>{if(!t)return{config:r,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(t),g={...r};return this.processObject(g,[],u,{useCamelCase:s,useBackwardCompatibility:o,customParsers:a,verbose:l,configName:t}),{config:g,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Vt.track("applyEnvironmentVariables",f,{configName:t});return f()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,r){if(!r)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${n}_${l.join("_")}`,f=i.useBackwardCompatibility?`${n}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,a,n,i);else{let u=Be.env[c]||(f?Be.env[f]:void 0);if(u!==void 0){if(i.verbose){let g=Be.env[c]?c:f}try{t[s]=this.parseEnvironmentValue(u,typeof o,c,i.customParsers,i.configName)}catch(g){if(g instanceof Zt)throw g;throw ne.envVar(c,u,typeof o,i.configName)}}}}}parseEnvironmentValue(t,r,n,i,s){for(let[o,a]of Object.entries(i))try{return a(t)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(t,r))try{return o.parse(t)}catch{throw ne.envVar(n,t,`${r} (via ${o.name} parser)`,s)}return t}getEnvironmentVariables(t){let r={},n=t.toUpperCase();for(let[i,s]of Object.entries(Be.env))if(i.startsWith(n)&&s!==void 0)r[i]=s;return r}validateEnvironmentVariable(t,r,n){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))i.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,r,n,{})}catch(s){i.push(`Cannot parse value "${r}" as ${n}: ${s}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(t,r,n={}){let{prefix:i,format:s="text"}=n,o=i||this.generateEnvPrefix(t),a=[];switch(this.extractEnvVarInfo(r,[],o,a),s){case"markdown":return this.formatAsMarkdown(a,t);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,t)}}extractEnvVarInfo(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=`${n}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,a,n,i);else i.push({key:l,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${a.join(".")}`,example:this.generateExample(o)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,r){let n=`Environment Variables for ${r}:
49
+ `)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||R()||!b.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(r)t.message=r;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(R()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let r=await Me(this.config.logDirectory),n=[];for(let i of r){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let o=pe(this.config.logDirectory,i);if(t.before)try{if((await de(o)).mtime>=t.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}n.push(o)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let i of n)try{await je(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(r){console.error("Error during log clearing process:",r)}}}var Da=new at("stacks");class J extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class we extends J{name="ConfigNotFoundError";code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],s="";if(i.length===1)s=` or alias "${i[0]}"`;else if(i.length>1)s=` or aliases ${i.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${t}"${s} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}}class se extends J{name="ConfigLoadError";code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ht extends J{name="ConfigValidationError";code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}}class dn extends J{name="ConfigMergeError";code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class Zt extends J{name="EnvVarError";code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}}class pn extends J{name="FileSystemError";code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class yn extends J{name="TypeGenerationError";code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class nt extends J{name="SchemaValidationError";code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}}class wn extends J{name="BrowserConfigError";code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}}class vn extends J{name="PluginError";code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}}var ne={configNotFound(t,r,n){return new we(t,r,n)},configLoad(t,r,n){return new se(t,r,n)},configValidation(t,r,n){return new Ht(t,r,n)},configMerge(t,r,n,i){return new dn(t,r,n,i)},envVar(t,r,n,i){return new Zt(t,r,n,i)},fileSystem(t,r,n){return new pn(t,r,n)},typeGeneration(t,r,n){return new yn(t,r,n)},schemaValidation(t,r,n){return new nt(t,r,n)},browserConfig(t,r,n,i){return new wn(t,r,n,i)},plugin(t,r,n){return new vn(t,r,n)}};async function Rs(t,r={}){let{maxRetries:n=3,retryDelay:i=1000,isRetryable:s=()=>!0,fallback:o}=r,a=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(c){if(a=c instanceof Error?c:Error(String(c)),l===n||!s(a))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(o!==void 0)return o;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}class Xt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,r)=>r==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let r=t.toLowerCase();return["true","1","yes"].includes(r)}},{name:"number",canParse:(t,r)=>r==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let r=Number(t);if(Number.isNaN(r))throw TypeError(`Cannot parse "${t}" as number`);return r}},{name:"array",canParse:(t,r)=>r==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return t.split(",").map((r)=>r.trim())}},{name:"json",canParse:(t,r)=>r==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(r){throw Error(`Cannot parse "${t}" as JSON: ${r}`)}}}]}async applyEnvironmentVariables(t,r,n={}){let{prefix:i,useCamelCase:s=!0,useBackwardCompatibility:o=!0,customParsers:a={},verbose:l=!1,trackPerformance:c=!0}=n,f=async()=>{if(!t)return{config:r,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(t),g={...r};return this.processObject(g,[],u,{useCamelCase:s,useBackwardCompatibility:o,customParsers:a,verbose:l,configName:t}),{config:g,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Vt.track("applyEnvironmentVariables",f,{configName:t});return f()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,r){if(!r)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${n}_${l.join("_")}`,f=i.useBackwardCompatibility?`${n}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,a,n,i);else{let u=Be.env[c]||(f?Be.env[f]:void 0);if(u!==void 0){if(i.verbose){let g=Be.env[c]?c:f}try{t[s]=this.parseEnvironmentValue(u,typeof o,c,i.customParsers,i.configName)}catch(g){if(g instanceof Zt)throw g;throw ne.envVar(c,u,typeof o,i.configName)}}}}}parseEnvironmentValue(t,r,n,i,s){for(let[o,a]of Object.entries(i))try{return a(t)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(t,r))try{return o.parse(t)}catch{throw ne.envVar(n,t,`${r} (via ${o.name} parser)`,s)}return t}getEnvironmentVariables(t){let r={},n=t.toUpperCase();for(let[i,s]of Object.entries(Be.env))if(i.startsWith(n)&&s!==void 0)r[i]=s;return r}validateEnvironmentVariable(t,r,n){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))i.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,r,n,{})}catch(s){i.push(`Cannot parse value "${r}" as ${n}: ${s}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(t,r,n={}){let{prefix:i,format:s="text"}=n,o=i||this.generateEnvPrefix(t),a=[];switch(this.extractEnvVarInfo(r,[],o,a),s){case"markdown":return this.formatAsMarkdown(a,t);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,t)}}extractEnvVarInfo(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=`${n}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,a,n,i);else i.push({key:l,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${a.join(".")}`,example:this.generateExample(o)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,r){let n=`Environment Variables for ${r}:
50
50
 
51
51
  `;for(let i of t)n+=`${i.key}
52
52
  `,n+=` Type: ${i.type}
@@ -58,5 +58,5 @@ export type ConfigOf = Config
58
58
  `;n+=`| Variable | Type | Description | Example |
59
59
  `,n+=`|----------|------|-------------|----------|
60
60
  `;for(let i of t)n+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
61
- `;return n}}var Kr=Ns(import.meta.url),Ie=new Map,kt=new Set;function $n(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="ENOTDIR")}async function Cn(t){let r=Ds(t),n=Ie.get(r),i,s=new Promise((o)=>{i=o});Ie.set(r,s),await n;try{if(Ps(r),Kr.cache[r]?.loaded===!0||kt.has(r))delete Kr.cache[r];try{let o=await import(Ms(r).href);return kt.delete(r),o}catch(o){throw kt.add(r),o}}finally{if(i(),Ie.get(r)===s)Ie.delete(r)}}function Ls(t,r,n={}){return bn(t,r,n,new WeakMap)}function bn(t,r,n,i){let{arrayMergeMode:s="replace",skipNullish:o=!1,customMerger:a}=n;if(r===null||r===void 0)return o?t:r;if(a){let l=a(t,r);if(l!==void 0)return l}if(Array.isArray(r)||Array.isArray(t))return En(t,r,s,i);if(!W(r)||!W(t))return r;return Ks(t,r,n,i)}function En(t,r,n,i){if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(t)&&!Array.isArray(r))return r;if(Array.isArray(r)&&Array.isArray(t))switch(n){case"replace":return r;case"concat":return Bs(t,r);case"smart":return Is(t,r,i);default:return r}return r}function Bs(t,r){let n=[...r];for(let i of t)if(!n.some((s)=>Kt(s,i)))n.push(i);return n}function Is(t,r,n){if(r.length===0)return t;if(t.length===0)return r;if(W(r[0])&&W(t[0]))return _s(t,r,n);if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}function _s(t,r,n){let i=[...r];for(let s of t){if(!W(s)){i.push(s);continue}let o=["id","name","key","path","type"],a=!1;for(let l of o)if(l in s){if(i.find((f)=>W(f)&&(l in f)&&f[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function Ks(t,r,n,i){let s=r;if(W(s)&&i.has(s))return i.get(s);let o={...t};if(W(s))i.set(s,o);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],c=o[a];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[a]=l;continue}if(W(l)&&W(c))o[a]=bn(c,l,n,i);else if(Array.isArray(l)||Array.isArray(c))o[a]=En(c,l,n.arrayMergeMode||"smart",i);else o[a]=l}return o}function xn(t,r,n="replace"){return Ls(t,r,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Kt(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!Kt(t[n],r[n]))return!1;return!0}if(W(t)&&W(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!Kt(t[s],r[s]))return!1}return!0}return!1}function W(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Sn{extensions=Ur;async loadFromPath(t,r,n={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:o,trackPerformance:a=!0,verbose:l=!1,strictDiscovery:c=!1}=n;if(s){let u=Ue.getWithFileCheck("file",t);if(u){if(l)console.log(`Configuration loaded from cache: ${t}`);return u}}let f=async()=>{try{try{js(t)}catch(T){if($n(T)||!c)return null;throw T}let u=await Cn(t),g=Object.hasOwn(u,"default"),m=Object.keys(u).length>0,h=g?u.default:u;if(!g&&!m)throw new se(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new se(t,Error("Configuration must export a valid object"),"unknown");let p={config:xn(r,h,i),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(s)Ue.setWithFileCheck("file",p,t,o);return p}catch(u){throw u instanceof Error?ne.configLoad(t,u):ne.configLoad(t,Error(String(u)))}};if(a)return Vt.track("loadFromPath",f,{path:t});return f()}async tryLoadFromPaths(t,r,n={}){for(let i of t)try{let s=await this.loadFromPath(i,r,n);if(s)return s}catch(s){if(s instanceof se)throw s;if(n.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(t,r,n){return Rn({name:t,directory:r,alias:n})}generateNamePatterns(t,r){return Gr({name:t,alias:r})}checkFileAccess(t){return Rs(async()=>At(t),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,r,n){let i=[];if(!At(t))return i;if(r||n){let s=this.generateNamePatterns(r||"",n);for(let o of s)for(let a of this.extensions){let l=Vr(t,`${o}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),o=s(t);for(let a of o)if(this.looksLikeConfigFile(a)){let l=Vr(t,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(t))}async validateConfigFile(t){let r=[];try{if(!At(t))return r.push("Configuration file does not exist"),r;let n=await import(t),i=n.default||n;if(i===void 0)r.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)r.push("Configuration must be an object");else if(Array.isArray(i))r.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),o=s(t,"utf8");JSON.parse(o)}catch(s){r.push(`Invalid JSON syntax: ${s}`)}}catch(n){r.push(`Failed to load configuration file: ${n}`)}return r}async getFileModificationTime(t){try{let{statSync:r}=await import("fs");return r(t).mtime}catch{return null}}async preloadConfigurations(t,r={}){let n=new Map;return await Promise.allSettled(t.map(async(i)=>{try{let s=await this.loadFromPath(i,{},r);if(s)n.set(i,s.config)}catch(s){if(r.verbose)console.warn(`Failed to preload ${i}:`,s)}})),n}}var Ws=/^https?:\/\//;class Tn{async validateConfiguration(t,r,n={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:o=!0,customRules:a=[],trackPerformance:l=!0,verbose:c=!1}=n,f=async()=>{let u=[],g=[],m={stopOnFirstError:i,validateRequired:s,validateTypes:o,customRules:a,trackPerformance:l,verbose:c};try{if(typeof r==="string")return await this.validateWithSchemaFile(t,r,m);else if(Array.isArray(r))return this.validateWithRules(t,[...r,...a],m);else return this.validateWithJSONSchema(t,r,m)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:g}}};if(l)return await Vt.track("validateConfiguration",f);return f()}async validateWithSchemaFile(t,r,n){try{if(!Vs(r))throw new nt(r,[{path:"",message:"Schema file does not exist"}]);let i=await Cn(r),s=Object.hasOwn(i,"default")?i.default:i;if(Array.isArray(s))return this.validateWithRules(t,s,n);else{if(typeof s!=="object"||s===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(t,s,n)}}catch(i){throw new nt(r,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(t,r,n){let i=[],s=[];return this.validateObjectAgainstSchema(t,r,"",i,s,n),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(t,r,n,i,s,o){if(o.validateTypes&&r.type){let a=Array.isArray(t)?"array":typeof t,l=Array.isArray(r.type)?r.type:[r.type];if(!l.includes(a)){if(i.push({path:n,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),o.stopOnFirstError)return}}if(r.enum&&!r.enum.includes(t)){if(i.push({path:n,message:`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"}),o.stopOnFirstError)return}if(typeof t==="string"){if(r.minLength!==void 0&&t.length<r.minLength)i.push({path:n,message:`String length must be at least ${r.minLength}`,expected:`>= ${r.minLength}`,actual:t.length,rule:"minLength"});if(r.maxLength!==void 0&&t.length>r.maxLength)i.push({path:n,message:`String length must not exceed ${r.maxLength}`,expected:`<= ${r.maxLength}`,actual:t.length,rule:"maxLength"});if(r.pattern){if(!new RegExp(r.pattern).test(t))i.push({path:n,message:`String does not match pattern ${r.pattern}`,expected:r.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(r.minimum!==void 0&&t<r.minimum)i.push({path:n,message:`Value must be at least ${r.minimum}`,expected:`>= ${r.minimum}`,actual:t,rule:"minimum"});if(r.maximum!==void 0&&t>r.maximum)i.push({path:n,message:`Value must not exceed ${r.maximum}`,expected:`<= ${r.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&r.items)for(let a=0;a<t.length;a++){let l=n?`${n}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(t[a],r.items,l,i,s,o),o.stopOnFirstError&&i.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let a=t;if(o.validateRequired&&r.required){for(let l of r.required)if(!(l in a)){if(i.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(r.properties){for(let[l,c]of Object.entries(r.properties))if(l in a){let f=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],c,f,i,s,o),o.stopOnFirstError&&i.length>0)return}}if(r.additionalProperties===!1){let l=new Set(Object.keys(r.properties||{}));for(let c of Object.keys(a))if(!l.has(c))s.push({path:n?`${n}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,r,n){let i=[],s=[];for(let o of r)try{let a=this.getValueByPath(t,o.path),l=this.validateWithRule(a,o,o.path);if(i.push(...l),n.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:o.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(t,r,n){let i=[];if(r.required&&(t===void 0||t===null))return i.push({path:n,message:r.message||`Property '${n}' is required`,expected:"required",rule:"required"}),i;if(t===void 0||t===null)return i;if(r.type){let s=Array.isArray(t)?"array":typeof t;if(s!==r.type)i.push({path:n,message:r.message||`Expected type ${r.type}, got ${s}`,expected:r.type,actual:s,rule:"type"})}if(r.min!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s<r.min)i.push({path:n,message:r.message||`Value must be at least ${r.min}`,expected:`>= ${r.min}`,actual:s,rule:"min"})}if(r.max!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s>r.max)i.push({path:n,message:r.message||`Value must not exceed ${r.max}`,expected:`<= ${r.max}`,actual:s,rule:"max"})}if(r.pattern&&typeof t==="string"){if(!r.pattern.test(t))i.push({path:n,message:r.message||`Value does not match pattern ${r.pattern}`,expected:r.pattern.toString(),actual:t,rule:"pattern"})}if(r.enum&&!r.enum.includes(t))i.push({path:n,message:r.message||`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"});if(r.validator){let s=r.validator(t);if(s)i.push({path:n,message:r.message||s,rule:"custom"})}return i}getValueByPath(t,r){if(!r)return t;let n=r.split("."),i=t;for(let s of n)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(t){let r=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of n){let[,s,o,a]=i;r.push({path:s,required:!o,type:this.mapTypeScriptType(a)})}return r}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Ws},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var q=new at("bunfig",{showTags:!0});function zs(t){if(!t)return"";let r=Array.isArray(t)?t.filter(Boolean):[t];if(r.length===0)return"";if(r.length===1)return` or alias "${r[0]}"`;return` or aliases ${r.map((n)=>`"${n}"`).join(", ")}`}class kn{fileLoader=new Sn;envProcessor=new Xt;validator=new Tn;async loadConfig(t){let r=Date.now(),{cache:n,performance:i,schema:s,validate:o,...a}=t,l=a.errorPolicy==="throw"?{...n,enabled:!1}:n;try{if(l?.enabled){let f=this.checkCache(a.name||"",a);if(f)return f}let c;try{c=await this.loadConfigurationStrategies(a,!0,l)}catch(f){if(a.configFile||a.errorPolicy==="throw"&&!(f instanceof we))throw f;let u=a.__strictErrorHandling;if(f instanceof we){if(u&&a.errorPolicy!=="throw")throw f;c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(f instanceof se){let g=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),m=!g&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),h=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(u&&(h||g))throw f;if(m&&(!u||!h))c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(s||o)await this.validateConfiguration(c.config,s,o,a.name);if(l?.enabled&&c)this.cacheResult(a.name||"",c,l,a);if(i?.enabled){let f={operation:"loadConfig",duration:Date.now()-r,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(f);if(i.slowThreshold&&f.duration>i.slowThreshold)q.warn(`Slow configuration loading detected: ${f.duration}ms for ${a.name}`);c.metrics=f}return c}catch(c){if(c instanceof we)throw c;let f=Date.now()-r;throw q.error(`Configuration loading failed after ${f}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,r=!1,n){let{name:i="",alias:s,configFile:o,cwd:a,configDir:l,defaultConfig:c,checkEnv:f=!0,arrayStrategy:u="replace",verbose:g=!1}=t,m=a||it.cwd(),h=[];if(o){let 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((T)=>Object.hasOwn(m,T)&&(u||Boolean(m[T])));if(d===void 0)return null;let p=m[d];if(typeof p!=="object"||p===null||Array.isArray(p))throw Error(`Configuration field "${d}" must contain an object`);if(o)q.success(`Configuration loaded from package.json: ${d}`);return{config:xn(c,p,s),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(g){if($n(g))return null;if(u)throw ne.configLoad(f,g instanceof Error?g:Error(String(g)));if(o)q.warn("Failed to load package.json:",[g instanceof Error?g:Error(String(g))]);return null}}async applyEnvironmentVariables(t,r,n,i){if(!n||!t||typeof r!=="object"||r===null||Array.isArray(r))return{config:r,source:{type:"default",priority:10,timestamp:new Date}};return{config:$e(t,r,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,r,n,i,s){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,r,n,i){let s=[];if(n){let o=n(t);if(o)s.push(...o)}if(r){let o=await this.validator.validateConfiguration(t,r);if(!o.isValid)s.push(...o.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw ne.configValidation(i||"unknown",s,i)}checkCache(t,r){let n=this.generateCacheKey(t,r);return Ue.get(n)||null}cacheResult(t,r,n,i){let s=this.generateCacheKey(t,i);Ue.set(s,r,void 0,n.ttl)}generateCacheKey(t,r){let n=[t];if(r.alias){let i=Array.isArray(r.alias)?r.alias.join(","):r.alias;n.push(`alias:${i}`)}if(r.cwd)n.push(`cwd:${r.cwd}`);if(r.configFile)n.push(`configFile:${r.configFile}`);if(r.configDir)n.push(`configDir:${r.configDir}`);if("checkEnv"in r)n.push(`checkEnv:${r.checkEnv}`);return n.join("|")}getLocalDirectories(t,r){return Pn({cwd:t,configDir:r})}getAllSearchPaths(t,r,n,i){let s=[];return s.push(...this.getLocalSearchPaths(t,r,n,i)),s.push(...this.getHomeSearchPaths(t,r)),s.push(Y(n,"package.json")),s}getLocalSearchPaths(t,r,n,i){let s=this.getLocalDirectories(n,i),o=[];for(let a of s)o.push(...this.fileLoader.generateConfigPaths(t,a,r));return o}getHomeSearchPaths(t,r){if(!t)return[];let n=[Y(ae(),".config",t),Y(ae(),".config"),ae()],i=[];for(let s of n)i.push(...this.fileLoader.generateConfigPaths(t,s,r));return i}async loadConfigWithResult(t){return this.loadConfig(t)}}var Ft=new kn;async function An(t){let r="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let i;if(n)i=await Ft.loadConfig(t);else i=await Ft.loadConfig({...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??r}catch(i){if(t.configFile||t.errorPolicy==="throw")throw i;let s=i instanceof Error?i.message:String(i);if(!(i instanceof we||i instanceof se||i instanceof Ht||s.includes("config"))&&t.verbose)q.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=n?{...t,defaultConfig:r}:{...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Ft.applyEnvironmentVariables(a.name||"",r,!0,a.verbose||!1))?.config??r;return r}}function $e(t,r,n=!1){let i=new Xt,s=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=[`${s}_${g.join("_").toUpperCase()}`,`${s}_${g.map((d)=>d.toUpperCase()).join("")}`,`${s}_${g.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,y;for(let d of m)if(h=it.env[d],h!==void 0){y=d;break}if(h!==void 0&&y)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let d=Number(h);if(!Number.isNaN(d))c[f]=d}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((d)=>d.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,g)}return c}return o(r)}var Ka=Y(it.cwd(),"config"),Va=Y(it.cwd(),"src/generated");var j={cwd:Qt.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",moduleSpecifierMode:"preserve",verbose:!1,importOrder:["bun"],declarationMap:!1},Js=["dtsx.config.ts","dtsx.config.js","dtsx.config.mjs","dtsx.config.mts","dts.config.ts","dts.config.js"];async function qs(t=Qt.cwd()){for(let r of Js){let n=Fn(t,r);if(Us(n))try{let s=await import(Gs(n).href),o=s.default||s.config||s,a=typeof o==="function"?await o():o;return{...j,...a,cwd:t}}catch(i){let s=i instanceof Error?i.message:String(i);e.warn(`Failed to load config from ${r}: ${s}`)}}return null}var ct=new Map;async function oa(t){let r=Fn(t??Qt.cwd()),n=ct.get(r);if(!n)n=(async()=>{let i=await qs(r);if(i)return i;return{...await An({name:"dts",cwd:r,defaultConfig:{...j,cwd:r}}),cwd:r}})(),ct.set(r,n);try{return await n}catch(i){throw ct.delete(r),i}}function aa(){ct.clear()}function ca(t){return{...j,...t}}function la(t){return async()=>{let r=await t();return{...j,...r}}}var A=j;
62
- export{j,oa,aa,ca,la,A};
61
+ `;return n}}var Kr=Ns(import.meta.url),Ie=new Map,kt=new Set;function $n(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="ENOTDIR")}async function Cn(t){let r=Ds(t),n=Ie.get(r),i,s=new Promise((o)=>{i=o});Ie.set(r,s),await n;try{if(Ps(r),Kr.cache[r]?.loaded===!0||kt.has(r))delete Kr.cache[r];try{let o=await import(Ms(r).href);return kt.delete(r),o}catch(o){throw kt.add(r),o}}finally{if(i(),Ie.get(r)===s)Ie.delete(r)}}function Ls(t,r,n={}){return bn(t,r,n,new WeakMap)}function bn(t,r,n,i){let{arrayMergeMode:s="replace",skipNullish:o=!1,customMerger:a}=n;if(r===null||r===void 0)return o?t:r;if(a){let l=a(t,r);if(l!==void 0)return l}if(Array.isArray(r)||Array.isArray(t))return En(t,r,s,i);if(!W(r)||!W(t))return r;return Ks(t,r,n,i)}function En(t,r,n,i){if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(t)&&!Array.isArray(r))return r;if(Array.isArray(r)&&Array.isArray(t))switch(n){case"replace":return r;case"concat":return Bs(t,r);case"smart":return Is(t,r,i);default:return r}return r}function Bs(t,r){let n=[...r];for(let i of t)if(!n.some((s)=>Kt(s,i)))n.push(i);return n}function Is(t,r,n){if(r.length===0)return t;if(t.length===0)return r;if(W(r[0])&&W(t[0]))return _s(t,r,n);if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}function _s(t,r,n){let i=[...r];for(let s of t){if(!W(s)){i.push(s);continue}let o=["id","name","key","path","type"],a=!1;for(let l of o)if(l in s){if(i.find((f)=>W(f)&&(l in f)&&f[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function Ks(t,r,n,i){let s=r;if(W(s)&&i.has(s))return i.get(s);let o={...t};if(W(s))i.set(s,o);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],c=o[a];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[a]=l;continue}if(W(l)&&W(c))o[a]=bn(c,l,n,i);else if(Array.isArray(l)||Array.isArray(c))o[a]=En(c,l,n.arrayMergeMode||"smart",i);else o[a]=l}return o}function xn(t,r,n="replace"){return Ls(t,r,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Kt(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!Kt(t[n],r[n]))return!1;return!0}if(W(t)&&W(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!Kt(t[s],r[s]))return!1}return!0}return!1}function W(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Sn{extensions=Ur;async loadFromPath(t,r,n={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:o,trackPerformance:a=!0,verbose:l=!1,strictDiscovery:c=!1}=n;if(s){let u=Ue.getWithFileCheck("file",t);if(u){if(l)console.log(`Configuration loaded from cache: ${t}`);return u}}let f=async()=>{try{try{js(t)}catch(T){if($n(T)||!c)return null;throw T}let u=await Cn(t),g=Object.hasOwn(u,"default"),m=Object.keys(u).length>0,h=g?u.default:u;if(!g&&!m)throw new se(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new se(t,Error("Configuration must export a valid object"),"unknown");let p={config:xn(r,h,i),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(s)Ue.setWithFileCheck("file",p,t,o);return p}catch(u){throw u instanceof Error?ne.configLoad(t,u):ne.configLoad(t,Error(String(u)))}};if(a)return Vt.track("loadFromPath",f,{path:t});return f()}async tryLoadFromPaths(t,r,n={}){for(let i of t)try{let s=await this.loadFromPath(i,r,n);if(s)return s}catch(s){if(s instanceof se)throw s;if(n.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(t,r,n){return Rn({name:t,directory:r,alias:n})}generateNamePatterns(t,r){return Gr({name:t,alias:r})}checkFileAccess(t){return Rs(async()=>At(t),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,r,n){let i=[];if(!At(t))return i;if(r||n){let s=this.generateNamePatterns(r||"",n);for(let o of s)for(let a of this.extensions){let l=Vr(t,`${o}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),o=s(t);for(let a of o)if(this.looksLikeConfigFile(a)){let l=Vr(t,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(t))}async validateConfigFile(t){let r=[];try{if(!At(t))return r.push("Configuration file does not exist"),r;let n=await import(t),i=n.default||n;if(i===void 0)r.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)r.push("Configuration must be an object");else if(Array.isArray(i))r.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),o=s(t,"utf8");JSON.parse(o)}catch(s){r.push(`Invalid JSON syntax: ${s}`)}}catch(n){r.push(`Failed to load configuration file: ${n}`)}return r}async getFileModificationTime(t){try{let{statSync:r}=await import("fs");return r(t).mtime}catch{return null}}async preloadConfigurations(t,r={}){let n=new Map;return await Promise.allSettled(t.map(async(i)=>{try{let s=await this.loadFromPath(i,{},r);if(s)n.set(i,s.config)}catch(s){if(r.verbose)console.warn(`Failed to preload ${i}:`,s)}})),n}}var Ws=/^https?:\/\//;class Tn{async validateConfiguration(t,r,n={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:o=!0,customRules:a=[],trackPerformance:l=!0,verbose:c=!1}=n,f=async()=>{let u=[],g=[],m={stopOnFirstError:i,validateRequired:s,validateTypes:o,customRules:a,trackPerformance:l,verbose:c};try{if(typeof r==="string")return await this.validateWithSchemaFile(t,r,m);else if(Array.isArray(r))return this.validateWithRules(t,[...r,...a],m);else return this.validateWithJSONSchema(t,r,m)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:g}}};if(l)return await Vt.track("validateConfiguration",f);return f()}async validateWithSchemaFile(t,r,n){try{if(!Vs(r))throw new nt(r,[{path:"",message:"Schema file does not exist"}]);let i=await Cn(r),s=Object.hasOwn(i,"default")?i.default:i;if(Array.isArray(s))return this.validateWithRules(t,s,n);else{if(typeof s!=="object"||s===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(t,s,n)}}catch(i){throw new nt(r,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(t,r,n){let i=[],s=[];return this.validateObjectAgainstSchema(t,r,"",i,s,n),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(t,r,n,i,s,o){if(o.validateTypes&&r.type){let a=Array.isArray(t)?"array":typeof t,l=Array.isArray(r.type)?r.type:[r.type];if(!l.includes(a)){if(i.push({path:n,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),o.stopOnFirstError)return}}if(r.enum&&!r.enum.includes(t)){if(i.push({path:n,message:`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"}),o.stopOnFirstError)return}if(typeof t==="string"){if(r.minLength!==void 0&&t.length<r.minLength)i.push({path:n,message:`String length must be at least ${r.minLength}`,expected:`>= ${r.minLength}`,actual:t.length,rule:"minLength"});if(r.maxLength!==void 0&&t.length>r.maxLength)i.push({path:n,message:`String length must not exceed ${r.maxLength}`,expected:`<= ${r.maxLength}`,actual:t.length,rule:"maxLength"});if(r.pattern){if(!new RegExp(r.pattern).test(t))i.push({path:n,message:`String does not match pattern ${r.pattern}`,expected:r.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(r.minimum!==void 0&&t<r.minimum)i.push({path:n,message:`Value must be at least ${r.minimum}`,expected:`>= ${r.minimum}`,actual:t,rule:"minimum"});if(r.maximum!==void 0&&t>r.maximum)i.push({path:n,message:`Value must not exceed ${r.maximum}`,expected:`<= ${r.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&r.items)for(let a=0;a<t.length;a++){let l=n?`${n}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(t[a],r.items,l,i,s,o),o.stopOnFirstError&&i.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let a=t;if(o.validateRequired&&r.required){for(let l of r.required)if(!(l in a)){if(i.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(r.properties){for(let[l,c]of Object.entries(r.properties))if(l in a){let f=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],c,f,i,s,o),o.stopOnFirstError&&i.length>0)return}}if(r.additionalProperties===!1){let l=new Set(Object.keys(r.properties||{}));for(let c of Object.keys(a))if(!l.has(c))s.push({path:n?`${n}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,r,n){let i=[],s=[];for(let o of r)try{let a=this.getValueByPath(t,o.path),l=this.validateWithRule(a,o,o.path);if(i.push(...l),n.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:o.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(t,r,n){let i=[];if(r.required&&(t===void 0||t===null))return i.push({path:n,message:r.message||`Property '${n}' is required`,expected:"required",rule:"required"}),i;if(t===void 0||t===null)return i;if(r.type){let s=Array.isArray(t)?"array":typeof t;if(s!==r.type)i.push({path:n,message:r.message||`Expected type ${r.type}, got ${s}`,expected:r.type,actual:s,rule:"type"})}if(r.min!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s<r.min)i.push({path:n,message:r.message||`Value must be at least ${r.min}`,expected:`>= ${r.min}`,actual:s,rule:"min"})}if(r.max!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s>r.max)i.push({path:n,message:r.message||`Value must not exceed ${r.max}`,expected:`<= ${r.max}`,actual:s,rule:"max"})}if(r.pattern&&typeof t==="string"){if(!r.pattern.test(t))i.push({path:n,message:r.message||`Value does not match pattern ${r.pattern}`,expected:r.pattern.toString(),actual:t,rule:"pattern"})}if(r.enum&&!r.enum.includes(t))i.push({path:n,message:r.message||`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"});if(r.validator){let s=r.validator(t);if(s)i.push({path:n,message:r.message||s,rule:"custom"})}return i}getValueByPath(t,r){if(!r)return t;let n=r.split("."),i=t;for(let s of n)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(t){let r=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of n){let[,s,o,a]=i;r.push({path:s,required:!o,type:this.mapTypeScriptType(a)})}return r}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Ws},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var q=new at("bunfig",{showTags:!0});function zs(t){if(!t)return"";let r=Array.isArray(t)?t.filter(Boolean):[t];if(r.length===0)return"";if(r.length===1)return` or alias "${r[0]}"`;return` or aliases ${r.map((n)=>`"${n}"`).join(", ")}`}class kn{fileLoader=new Sn;envProcessor=new Xt;validator=new Tn;async loadConfig(t){let r=Date.now(),{cache:n,performance:i,schema:s,validate:o,...a}=t,l=a.errorPolicy==="throw"?{...n,enabled:!1}:n;try{if(l?.enabled){let f=this.checkCache(a.name||"",a);if(f)return f}let c;try{c=await this.loadConfigurationStrategies(a,!0,l)}catch(f){if(a.configFile||a.errorPolicy==="throw"&&!(f instanceof we))throw f;let u=a.__strictErrorHandling;if(f instanceof we){if(u&&a.errorPolicy!=="throw")throw f;c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(f instanceof se){let g=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),m=!g&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),h=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(u&&(h||g))throw f;if(m&&(!u||!h))c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(s||o)await this.validateConfiguration(c.config,s,o,a.name);if(l?.enabled&&c)this.cacheResult(a.name||"",c,l,a);if(i?.enabled){let f={operation:"loadConfig",duration:Date.now()-r,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(f);if(i.slowThreshold&&f.duration>i.slowThreshold)q.warn(`Slow configuration loading detected: ${f.duration}ms for ${a.name}`);c.metrics=f}return c}catch(c){if(c instanceof we)throw c;let f=Date.now()-r;throw q.error(`Configuration loading failed after ${f}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,r=!1,n){let{name:i="",alias:s,configFile:o,cwd:a,configDir:l,defaultConfig:c,checkEnv:f=!0,arrayStrategy:u="replace",verbose:g=!1}=t,m=a||it.cwd(),h=[];if(o){let A=Y(m,o);h.push(A);let z=f?$e(i,c,g):c,_=await this.fileLoader.tryLoadFromPaths([A],z,{arrayStrategy:u,verbose:g,cacheTtl:n?.ttl,useCache:n?.enabled!==!1&&(!n?.ttl||n.ttl>100),strictDiscovery:!0});if(!_)throw ne.configNotFound(i||o,h,s);if(g)q.success(`Configuration loaded from explicit path: ${A}`);return this.finalizeResult(_,h,f,i,g)}let y=await this.loadLocalConfiguration(i,s,m,l,c,u,g,f,n,t.errorPolicy==="throw");if(y)return h.push(...this.getLocalSearchPaths(i,s,m,l)),this.finalizeResult(y,h,f,i,g);let d=await this.loadHomeConfiguration(i,s,c,u,g,f,n,t.errorPolicy==="throw");if(d)return h.push(...this.getHomeSearchPaths(i,s)),this.finalizeResult(d,h,f,i,g);let p=await this.loadPackageJsonConfiguration(i,s,m,c,u,g,f,t.errorPolicy);if(p)return h.push(Y(m,"package.json")),this.finalizeResult(p,h,f,i,g);if(h.push(...this.getAllSearchPaths(i,s,m,l)),r)throw ne.configNotFound(i,h,s);return{...await this.applyEnvironmentVariables(i,c,f,g),warnings:[`No configuration file found for "${i}"${zs(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,r,n,i,s,o,a,l,c,f=!1){let u=l?$e(t,s,a):s,g=this.getLocalDirectories(n,i);for(let m of g){if(a)q.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(t,m,r),y=await this.fileLoader.tryLoadFromPaths(h,u,{arrayStrategy:o,verbose:a,cacheTtl:c?.ttl,useCache:c?.enabled!==!1&&(!c?.ttl||c.ttl>100),strictDiscovery:f});if(y){if(a)q.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,r,n,i,s,o,a,l=!1){if(!t)return null;let c=o?$e(t,n,s):n,f=[Y(ae(),".config",t),Y(ae(),".config"),ae()];for(let u of f){if(s)q.info(`Checking home directory: ${u}`);let g=this.fileLoader.generateConfigPaths(t,u,r),m=await this.fileLoader.tryLoadFromPaths(g,c,{arrayStrategy:i,verbose:s,cacheTtl:a?.ttl,useCache:a?.enabled!==!1&&(!a?.ttl||a.ttl>100),strictDiscovery:l});if(m){if(s)q.success(`Configuration loaded from home directory: ${m.source.path}`);return m}}return null}async loadPackageJsonConfiguration(t,r,n,i,s,o,a,l){let c=a?$e(t,i,o):i,f=Y(n,"package.json"),u=l==="throw";try{let g=JSON.parse(Dn(f,"utf8"));if(typeof g!=="object"||g===null||Array.isArray(g))throw Error("package.json must contain an object");let m=g,h=r===void 0?[]:Array.isArray(r)?r:[r],d=[t,...h.filter(Boolean)].find((T)=>Object.hasOwn(m,T)&&(u||Boolean(m[T])));if(d===void 0)return null;let p=m[d];if(typeof p!=="object"||p===null||Array.isArray(p))throw Error(`Configuration field "${d}" must contain an object`);if(o)q.success(`Configuration loaded from package.json: ${d}`);return{config:xn(c,p,s),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(g){if($n(g))return null;if(u)throw ne.configLoad(f,g instanceof Error?g:Error(String(g)));if(o)q.warn("Failed to load package.json:",[g instanceof Error?g:Error(String(g))]);return null}}async applyEnvironmentVariables(t,r,n,i){if(!n||!t||typeof r!=="object"||r===null||Array.isArray(r))return{config:r,source:{type:"default",priority:10,timestamp:new Date}};return{config:$e(t,r,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,r,n,i,s){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,r,n,i){let s=[];if(n){let o=n(t);if(o)s.push(...o)}if(r){let o=await this.validator.validateConfiguration(t,r);if(!o.isValid)s.push(...o.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw ne.configValidation(i||"unknown",s,i)}checkCache(t,r){let n=this.generateCacheKey(t,r);return Ue.get(n)||null}cacheResult(t,r,n,i){let s=this.generateCacheKey(t,i);Ue.set(s,r,void 0,n.ttl)}generateCacheKey(t,r){let n=[t];if(r.alias){let i=Array.isArray(r.alias)?r.alias.join(","):r.alias;n.push(`alias:${i}`)}if(r.cwd)n.push(`cwd:${r.cwd}`);if(r.configFile)n.push(`configFile:${r.configFile}`);if(r.configDir)n.push(`configDir:${r.configDir}`);if("checkEnv"in r)n.push(`checkEnv:${r.checkEnv}`);return n.join("|")}getLocalDirectories(t,r){return Pn({cwd:t,configDir:r})}getAllSearchPaths(t,r,n,i){let s=[];return s.push(...this.getLocalSearchPaths(t,r,n,i)),s.push(...this.getHomeSearchPaths(t,r)),s.push(Y(n,"package.json")),s}getLocalSearchPaths(t,r,n,i){let s=this.getLocalDirectories(n,i),o=[];for(let a of s)o.push(...this.fileLoader.generateConfigPaths(t,a,r));return o}getHomeSearchPaths(t,r){if(!t)return[];let n=[Y(ae(),".config",t),Y(ae(),".config"),ae()],i=[];for(let s of n)i.push(...this.fileLoader.generateConfigPaths(t,s,r));return i}async loadConfigWithResult(t){return this.loadConfig(t)}}var Ft=new kn;async function An(t){let r="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let i;if(n)i=await Ft.loadConfig(t);else i=await Ft.loadConfig({...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??r}catch(i){if(t.configFile||t.errorPolicy==="throw")throw i;let s=i instanceof Error?i.message:String(i);if(!(i instanceof we||i instanceof se||i instanceof Ht||s.includes("config"))&&t.verbose)q.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=n?{...t,defaultConfig:r}:{...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Ft.applyEnvironmentVariables(a.name||"",r,!0,a.verbose||!1))?.config??r;return r}}function $e(t,r,n=!1){let i=new Xt,s=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=[`${s}_${g.join("_").toUpperCase()}`,`${s}_${g.map((d)=>d.toUpperCase()).join("")}`,`${s}_${g.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,y;for(let d of m)if(h=it.env[d],h!==void 0){y=d;break}if(h!==void 0&&y)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let d=Number(h);if(!Number.isNaN(d))c[f]=d}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((d)=>d.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,g)}return c}return o(r)}var Ka=Y(it.cwd(),"config"),Va=Y(it.cwd(),"src/generated");var j={cwd:Qt.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",moduleSpecifierMode:"preserve",verbose:!1,importOrder:["bun"],declarationMap:!1},Js=["dtsx.config.ts","dtsx.config.js","dtsx.config.mjs","dtsx.config.mts","dts.config.ts","dts.config.js"];async function qs(t=Qt.cwd()){for(let r of Js){let n=Fn(t,r);if(Us(n))try{let s=await import(Gs(n).href),o=s.default||s.config||s,a=typeof o==="function"?await o():o;return{...j,...a,cwd:t}}catch(i){let s=i instanceof Error?i.message:String(i);e.warn(`Failed to load config from ${r}: ${s}`)}}return null}var ct=new Map;async function oa(t){let r=Fn(t??Qt.cwd()),n=ct.get(r);if(!n)n=(async()=>{let i=await qs(r);if(i)return i;return{...await An({name:"dts",cwd:r,defaultConfig:{...j,cwd:r}}),cwd:r}})(),ct.set(r,n);try{return await n}catch(i){throw ct.delete(r),i}}function aa(){ct.clear()}function ca(t){return{...j,...t}}function la(t){return async()=>{let r=await t();return{...j,...r}}}var P=j;
62
+ export{j,oa,aa,ca,la,P};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{p}from"./chunk-v6fwy63g.js";import{existsSync as u,mkdirSync as H,readFileSync as l,renameSync as b,rmdirSync as D,rmSync as C,statSync as g,writeFileSync as S}from"fs";import{join as d,relative as h,resolve as y}from"path";var f=26,m=".dtsx-cache",v="manifest.json";function pi(t){try{C(d(t,v),{force:!0});try{D(t)}catch{}}catch{}}class et{cacheDir;manifestPath;manifest=null;configHash;constructor(t,n){this.cacheDir=y(t.cwd,t.cacheDir??m),this.manifestPath=d(this.cacheDir,v),this.configHash=this.hashConfig(t,n)}hashConfig(t,n){let s={resolutionContext:n,keepComments:t.keepComments,importOrder:t.importOrder,outputStructure:t.outputStructure,moduleSpecifierMode:t.moduleSpecifierMode??"preserve",root:y(t.cwd,t.root),exclude:t.exclude??[],isolatedDeclarations:t.isolatedDeclarations,declarationMap:t.declarationMap,indentStyle:t.indentStyle,indentSize:t.indentSize,prettier:t.prettier,typeMappings:t.typeMappings?{includeDefaults:t.typeMappings.includeDefaults,presets:t.typeMappings.presets,cacheKey:t.typeMappings.cacheKey,rules:t.typeMappings.rules.map((e)=>({pattern:typeof e.pattern==="string"?{kind:"string",value:e.pattern}:{kind:"regex",source:e.pattern.source,flags:e.pattern.flags},replacement:e.replacement,global:e.global,priority:e.priority,hasCondition:Boolean(e.condition)}))}:void 0,lineEnding:t.lineEnding,normalizeOutput:t.normalizeOutput,declarationOrder:t.declarationOrder,plugins:t.plugins?.map((e)=>({name:e.name,version:e.version,cacheKey:e.cacheKey}))};return String(p(JSON.stringify(s)))}hashString(t){return String(p(t))}load(){try{if(!u(this.manifestPath))return!1;let t=l(this.manifestPath,"utf-8"),n=JSON.parse(t);if(n.version!==f)return!1;if(n.configHash!==this.configHash)return!1;if(!n.entries||typeof n.entries!=="object"||Array.isArray(n.entries))return!1;return this.manifest=n,!0}catch{return!1}}save(){if(!this.manifest)this.manifest={version:f,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!u(this.cacheDir))H(this.cacheDir,{recursive:!0});let t=`${this.manifestPath}.${process.pid}.tmp`;try{S(t,JSON.stringify(this.manifest,null,2)),b(t,this.manifestPath)}finally{if(u(t))C(t,{force:!0})}}needsRegeneration(t,n){return this.getCachedIfValid(t,n)===null}getCached(t,n){return this.getCachedIfValid(t,n)}getCachedIfValid(t,n){if(!this.manifest)return null;let s=h(n,t),e=this.manifest.entries[s];if(!e)return null;if(typeof e.dtsContent!=="string"||typeof e.dtsHash!=="string"||e.configHash!==this.configHash||this.hashString(e.dtsContent)!==e.dtsHash)return null;try{let i=g(t),{mtimeMs:r,ctimeMs:a}=i;if(i.size!==e.sourceSize)return null;if(r!==e.sourceMtime||a!==e.sourceCtime){let o=l(t,"utf-8");if(this.hashString(o)!==e.sourceHash)return null;e.sourceMtime=r,e.sourceCtime=a}return e.dtsContent}catch{return null}}update(t,n,s,e){if(!this.manifest)this.manifest={version:f,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=h(e,t),r,a,o;try{let c=g(t);r=c.mtimeMs,a=c.ctimeMs,o=c.size}catch{r=Date.now(),a=r,o=Buffer.byteLength(n)}this.manifest.entries[i]={sourcePath:i,sourceHash:this.hashString(n),sourceMtime:r,sourceCtime:a,sourceSize:o,dtsContent:s,dtsHash:this.hashString(s),generatedAt:Date.now(),configHash:this.configHash}}remove(t,n){if(!this.manifest)return;let s=h(n,t);delete this.manifest.entries[s]}clear(){this.manifest=null,pi(this.cacheDir)}getStats(){if(!this.manifest)return{entries:0,size:0};let t=Object.keys(this.manifest.entries).length,n=0;for(let s of Object.values(this.manifest.entries))n+=s.dtsContent.length;return{entries:t,size:n}}prune(t,n){if(!this.manifest)return 0;let s=0,e=new Set(Array.from(t).map((i)=>h(n,i)));for(let i of Object.keys(this.manifest.entries))if(!e.has(i))delete this.manifest.entries[i],s++;return s}}function kt(t){let n=d(t,".gitignore");try{let s="";if(u(n))s=l(n,"utf-8");if(!s.split(/\r?\n/).some((i)=>i.trim()===m||i.trim()===`${m}/`)){let i=s.trimEnd(),r=`${i}${i?`
2
+ import{p}from"./chunk-v6fwy63g.js";import{existsSync as u,mkdirSync as H,readFileSync as l,renameSync as b,rmdirSync as D,rmSync as C,statSync as g,writeFileSync as S}from"fs";import{join as d,relative as h,resolve as y}from"path";var f=27,m=".dtsx-cache",v="manifest.json";function pi(t){try{C(d(t,v),{force:!0});try{D(t)}catch{}}catch{}}class et{cacheDir;manifestPath;manifest=null;configHash;constructor(t,n){this.cacheDir=y(t.cwd,t.cacheDir??m),this.manifestPath=d(this.cacheDir,v),this.configHash=this.hashConfig(t,n)}hashConfig(t,n){let s={resolutionContext:n,keepComments:t.keepComments,importOrder:t.importOrder,outputStructure:t.outputStructure,moduleSpecifierMode:t.moduleSpecifierMode??"preserve",root:y(t.cwd,t.root),exclude:t.exclude??[],isolatedDeclarations:t.isolatedDeclarations,declarationMap:t.declarationMap,indentStyle:t.indentStyle,indentSize:t.indentSize,prettier:t.prettier,typeMappings:t.typeMappings?{includeDefaults:t.typeMappings.includeDefaults,presets:t.typeMappings.presets,cacheKey:t.typeMappings.cacheKey,rules:t.typeMappings.rules.map((e)=>({pattern:typeof e.pattern==="string"?{kind:"string",value:e.pattern}:{kind:"regex",source:e.pattern.source,flags:e.pattern.flags},replacement:e.replacement,global:e.global,priority:e.priority,hasCondition:Boolean(e.condition)}))}:void 0,lineEnding:t.lineEnding,normalizeOutput:t.normalizeOutput,declarationOrder:t.declarationOrder,plugins:t.plugins?.map((e)=>({name:e.name,version:e.version,cacheKey:e.cacheKey}))};return String(p(JSON.stringify(s)))}hashString(t){return String(p(t))}load(){try{if(!u(this.manifestPath))return!1;let t=l(this.manifestPath,"utf-8"),n=JSON.parse(t);if(n.version!==f)return!1;if(n.configHash!==this.configHash)return!1;if(!n.entries||typeof n.entries!=="object"||Array.isArray(n.entries))return!1;return this.manifest=n,!0}catch{return!1}}save(){if(!this.manifest)this.manifest={version:f,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!u(this.cacheDir))H(this.cacheDir,{recursive:!0});let t=`${this.manifestPath}.${process.pid}.tmp`;try{S(t,JSON.stringify(this.manifest,null,2)),b(t,this.manifestPath)}finally{if(u(t))C(t,{force:!0})}}needsRegeneration(t,n){return this.getCachedIfValid(t,n)===null}getCached(t,n){return this.getCachedIfValid(t,n)}getCachedIfValid(t,n){if(!this.manifest)return null;let s=h(n,t),e=this.manifest.entries[s];if(!e)return null;if(typeof e.dtsContent!=="string"||typeof e.dtsHash!=="string"||e.configHash!==this.configHash||this.hashString(e.dtsContent)!==e.dtsHash)return null;try{let i=g(t),{mtimeMs:r,ctimeMs:a}=i;if(i.size!==e.sourceSize)return null;if(r!==e.sourceMtime||a!==e.sourceCtime){let o=l(t,"utf-8");if(this.hashString(o)!==e.sourceHash)return null;e.sourceMtime=r,e.sourceCtime=a}return e.dtsContent}catch{return null}}update(t,n,s,e){if(!this.manifest)this.manifest={version:f,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=h(e,t),r,a,o;try{let c=g(t);r=c.mtimeMs,a=c.ctimeMs,o=c.size}catch{r=Date.now(),a=r,o=Buffer.byteLength(n)}this.manifest.entries[i]={sourcePath:i,sourceHash:this.hashString(n),sourceMtime:r,sourceCtime:a,sourceSize:o,dtsContent:s,dtsHash:this.hashString(s),generatedAt:Date.now(),configHash:this.configHash}}remove(t,n){if(!this.manifest)return;let s=h(n,t);delete this.manifest.entries[s]}clear(){this.manifest=null,pi(this.cacheDir)}getStats(){if(!this.manifest)return{entries:0,size:0};let t=Object.keys(this.manifest.entries).length,n=0;for(let s of Object.values(this.manifest.entries))n+=s.dtsContent.length;return{entries:t,size:n}}prune(t,n){if(!this.manifest)return 0;let s=0,e=new Set(Array.from(t).map((i)=>h(n,i)));for(let i of Object.keys(this.manifest.entries))if(!e.has(i))delete this.manifest.entries[i],s++;return s}}function kt(t){let n=d(t,".gitignore");try{let s="";if(u(n))s=l(n,"utf-8");if(!s.split(/\r?\n/).some((i)=>i.trim()===m||i.trim()===`${m}/`)){let i=s.trimEnd(),r=`${i}${i?`
3
3
 
4
4
  `:""}# dtsx cache
5
5
  ${m}/