pickier 0.1.68 → 0.1.70

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 (136) hide show
  1. package/dist/bin/cli.js +2 -2
  2. package/dist/chunk-0b2yx624.js +3 -0
  3. package/dist/chunk-1jtr81zg.js +25 -0
  4. package/dist/chunk-5c026tb4.js +3 -0
  5. package/dist/chunk-5tx5kfq7.js +2 -0
  6. package/dist/chunk-8m82hwdv.js +3 -0
  7. package/dist/chunk-c82emw32.js +3 -0
  8. package/dist/chunk-dxrcbgyc.js +49 -0
  9. package/dist/chunk-gpfjzx90.js +2 -0
  10. package/dist/chunk-he3fbz3w.js +8 -0
  11. package/dist/chunk-m9ym248d.js +2 -0
  12. package/dist/chunk-mqjmcycy.js +128 -0
  13. package/dist/chunk-ng3egs14.js +2 -0
  14. package/dist/chunk-pvptb0h1.js +3 -0
  15. package/dist/chunk-qjzzx1m2.js +61 -0
  16. package/dist/chunk-t4eg5fx5.js +41 -0
  17. package/dist/chunk-t776wefr.js +2 -0
  18. package/dist/chunk-wx92kdf9.js +9 -0
  19. package/dist/chunk-xjt8q744.js +3 -0
  20. package/dist/native/darwin-arm64/pickier-native +0 -0
  21. package/dist/native/darwin-x64/pickier-native +0 -0
  22. package/dist/native/linux-arm64/pickier-native +0 -0
  23. package/dist/native/linux-x64/pickier-native +0 -0
  24. package/dist/native/win32-arm64/pickier-native.exe +0 -0
  25. package/dist/native/win32-x64/pickier-native.exe +0 -0
  26. package/dist/src/cache.d.ts +21 -0
  27. package/dist/src/index.js +1 -1
  28. package/dist/src/lexer.d.ts +2 -0
  29. package/dist/src/lint-worker.d.ts +1 -0
  30. package/dist/src/lint-worker.js +2 -0
  31. package/dist/src/linter.d.ts +17 -1
  32. package/dist/src/logger.d.ts +20 -0
  33. package/dist/src/native.d.ts +64 -0
  34. package/dist/src/parallel.d.ts +17 -0
  35. package/dist/src/plugins/lazy.d.ts +10 -0
  36. package/dist/src/plugins/manifest.d.ts +123 -0
  37. package/dist/src/plugins/utils.d.ts +6 -0
  38. package/dist/src/rules/shell/_continuation.d.ts +4 -0
  39. package/dist/src/rules/style/consistent-list-newline.d.ts +2 -0
  40. package/dist/src/types.d.ts +1 -0
  41. package/dist/src/utils.d.ts +1 -0
  42. package/package.json +3 -2
  43. package/dist/chunk-5dpt7qv4.js +0 -2
  44. package/dist/chunk-ek25vxkw.js +0 -2
  45. package/dist/chunk-jcy3sgzh.js +0 -2
  46. package/dist/chunk-q47v401h.js +0 -92
  47. package/dist/chunk-s0n5r5hb.js +0 -227
  48. package/dist/chunk-zeaz9zt8.js +0 -2
  49. package/dist/src/plugins/index.d.ts +0 -2
  50. package/dist/src/plugins/lockfile.d.ts +0 -22
  51. package/dist/src/plugins/markdown.d.ts +0 -2
  52. package/dist/src/plugins/publint.d.ts +0 -10
  53. package/dist/src/plugins/shell.d.ts +0 -2
  54. package/dist/src/plugins/spell.d.ts +0 -3
  55. package/dist/src/rules/lockfile/parser.d.ts +0 -85
  56. package/dist/src/rules/lockfile/validate-host.d.ts +0 -18
  57. package/dist/src/rules/lockfile/validate-https.d.ts +0 -14
  58. package/dist/src/rules/lockfile/validate-integrity.d.ts +0 -19
  59. package/dist/src/rules/lockfile/validate-package-names.d.ts +0 -23
  60. package/dist/src/rules/lockfile/validate-scheme.d.ts +0 -17
  61. package/dist/src/rules/markdown/_fence-tracking.d.ts +0 -70
  62. package/dist/src/rules/markdown/_shared.d.ts +0 -9
  63. package/dist/src/rules/markdown/blanks-around-fences.d.ts +0 -5
  64. package/dist/src/rules/markdown/blanks-around-headings.d.ts +0 -5
  65. package/dist/src/rules/markdown/blanks-around-lists.d.ts +0 -5
  66. package/dist/src/rules/markdown/blanks-around-tables.d.ts +0 -5
  67. package/dist/src/rules/markdown/code-block-style.d.ts +0 -5
  68. package/dist/src/rules/markdown/code-fence-style.d.ts +0 -5
  69. package/dist/src/rules/markdown/commands-show-output.d.ts +0 -5
  70. package/dist/src/rules/markdown/descriptive-link-text.d.ts +0 -5
  71. package/dist/src/rules/markdown/emphasis-style.d.ts +0 -5
  72. package/dist/src/rules/markdown/fenced-code-language.d.ts +0 -5
  73. package/dist/src/rules/markdown/first-line-heading.d.ts +0 -5
  74. package/dist/src/rules/markdown/heading-increment.d.ts +0 -5
  75. package/dist/src/rules/markdown/heading-start-left.d.ts +0 -5
  76. package/dist/src/rules/markdown/heading-style.d.ts +0 -5
  77. package/dist/src/rules/markdown/hr-style.d.ts +0 -5
  78. package/dist/src/rules/markdown/line-length.d.ts +0 -5
  79. package/dist/src/rules/markdown/link-fragments.d.ts +0 -5
  80. package/dist/src/rules/markdown/link-image-reference-definitions.d.ts +0 -5
  81. package/dist/src/rules/markdown/link-image-style.d.ts +0 -5
  82. package/dist/src/rules/markdown/list-indent.d.ts +0 -5
  83. package/dist/src/rules/markdown/list-marker-space.d.ts +0 -5
  84. package/dist/src/rules/markdown/no-alt-text.d.ts +0 -5
  85. package/dist/src/rules/markdown/no-bare-urls.d.ts +0 -5
  86. package/dist/src/rules/markdown/no-blanks-blockquote.d.ts +0 -5
  87. package/dist/src/rules/markdown/no-duplicate-heading.d.ts +0 -10
  88. package/dist/src/rules/markdown/no-emphasis-as-heading.d.ts +0 -9
  89. package/dist/src/rules/markdown/no-empty-links.d.ts +0 -5
  90. package/dist/src/rules/markdown/no-hard-tabs.d.ts +0 -5
  91. package/dist/src/rules/markdown/no-inline-html.d.ts +0 -5
  92. package/dist/src/rules/markdown/no-missing-space-atx.d.ts +0 -5
  93. package/dist/src/rules/markdown/no-missing-space-closed-atx.d.ts +0 -5
  94. package/dist/src/rules/markdown/no-multiple-blanks.d.ts +0 -5
  95. package/dist/src/rules/markdown/no-multiple-space-atx.d.ts +0 -5
  96. package/dist/src/rules/markdown/no-multiple-space-blockquote.d.ts +0 -5
  97. package/dist/src/rules/markdown/no-multiple-space-closed-atx.d.ts +0 -5
  98. package/dist/src/rules/markdown/no-reversed-links.d.ts +0 -5
  99. package/dist/src/rules/markdown/no-space-in-code.d.ts +0 -5
  100. package/dist/src/rules/markdown/no-space-in-emphasis.d.ts +0 -5
  101. package/dist/src/rules/markdown/no-space-in-links.d.ts +0 -5
  102. package/dist/src/rules/markdown/no-trailing-punctuation.d.ts +0 -5
  103. package/dist/src/rules/markdown/no-trailing-spaces.d.ts +0 -5
  104. package/dist/src/rules/markdown/ol-prefix.d.ts +0 -5
  105. package/dist/src/rules/markdown/proper-names.d.ts +0 -5
  106. package/dist/src/rules/markdown/reference-links-images.d.ts +0 -14
  107. package/dist/src/rules/markdown/required-headings.d.ts +0 -5
  108. package/dist/src/rules/markdown/single-title.d.ts +0 -5
  109. package/dist/src/rules/markdown/single-trailing-newline.d.ts +0 -5
  110. package/dist/src/rules/markdown/strong-style.d.ts +0 -16
  111. package/dist/src/rules/markdown/table-column-count.d.ts +0 -5
  112. package/dist/src/rules/markdown/table-column-style.d.ts +0 -5
  113. package/dist/src/rules/markdown/table-pipe-style.d.ts +0 -5
  114. package/dist/src/rules/markdown/ul-indent.d.ts +0 -14
  115. package/dist/src/rules/markdown/ul-style.d.ts +0 -5
  116. package/dist/src/rules/shell/command-substitution.d.ts +0 -6
  117. package/dist/src/rules/shell/consistent-case-terminators.d.ts +0 -9
  118. package/dist/src/rules/shell/function-style.d.ts +0 -6
  119. package/dist/src/rules/shell/heredoc-indent.d.ts +0 -7
  120. package/dist/src/rules/shell/indent.d.ts +0 -2
  121. package/dist/src/rules/shell/keyword-spacing.d.ts +0 -10
  122. package/dist/src/rules/shell/no-broken-redirect.d.ts +0 -7
  123. package/dist/src/rules/shell/no-cd-without-check.d.ts +0 -6
  124. package/dist/src/rules/shell/no-eval.d.ts +0 -6
  125. package/dist/src/rules/shell/no-exit-in-subshell.d.ts +0 -7
  126. package/dist/src/rules/shell/no-ls-parsing.d.ts +0 -7
  127. package/dist/src/rules/shell/no-trailing-semicolons.d.ts +0 -6
  128. package/dist/src/rules/shell/no-trailing-whitespace.d.ts +0 -5
  129. package/dist/src/rules/shell/no-useless-cat.d.ts +0 -6
  130. package/dist/src/rules/shell/no-variable-in-single-quotes.d.ts +0 -7
  131. package/dist/src/rules/shell/operator-spacing.d.ts +0 -11
  132. package/dist/src/rules/shell/prefer-double-brackets.d.ts +0 -6
  133. package/dist/src/rules/shell/prefer-printf.d.ts +0 -6
  134. package/dist/src/rules/shell/quote-variables.d.ts +0 -2
  135. package/dist/src/rules/shell/set-options.d.ts +0 -8
  136. package/dist/src/rules/shell/shebang.d.ts +0 -2
@@ -0,0 +1,49 @@
1
+ // @bun
2
+ import{existsSync as kt,statSync as Ft}from"fs";import{existsSync as at,mkdirSync as Lr,readdirSync as Ir,writeFileSync as jr}from"fs";import{homedir as X}from"os";import{dirname as At,resolve as M}from"path";import Z from"process";import{join as _r,relative as Kr,resolve as Ot}from"path";import Oe from"process";import{existsSync as hr,mkdirSync as Ii,readdirSync as ji,writeFileSync as _i}from"fs";import{homedir as Ve}from"os";import{dirname as Vi,resolve as D}from"path";import fe from"process";import{join as Wr,relative as Vr,resolve as Pt}from"path";import Pe from"process";import{existsSync as gr,mkdirSync as Ji,readdirSync as qi,writeFileSync as Hi}from"fs";import{dirname as Xi,resolve as Ne}from"path";import ct from"process";import{Buffer as q}from"buffer";import{createCipheriv as zr,createDecipheriv as Ur,randomBytes as ze}from"crypto";import{closeSync as Ue,createReadStream as Nt,createWriteStream as Yr,existsSync as Ye,fsyncSync as Rt,openSync as Bt,writeFileSync as Gr}from"fs";import{access as Jr,constants as Dt,mkdir as qr,readdir as me,rename as Mt,stat as Q,unlink as de,writeFile as Ge}from"fs/promises";import{join as ee}from"path";import O from"process";import{pipeline as Hr}from"stream/promises";import{createGzip as Lt}from"zlib";import te from"process";import U from"process";import{Buffer as V}from"buffer";import{createCipheriv as Zr,createDecipheriv as Xr,randomBytes as Je}from"crypto";import{closeSync as qe,createReadStream as It,createWriteStream as Qr,existsSync as pe,fsyncSync as jt,openSync as _t,writeFileSync as en}from"fs";import{access as tn,constants as Kt,mkdir as rn,readdir as ye,rename as Wt,stat as re,unlink as we,writeFile as He}from"fs/promises";import{isAbsolute as nn,join as ne,resolve as sn}from"path";import y from"process";import{pipeline as on}from"stream/promises";import{createGzip as Vt}from"zlib";import ie from"process";import Y from"process";import $e from"process";import{existsSync as ve}from"fs";import{resolve as Ze}from"path";import{existsSync as an}from"fs";import{existsSync as cn,readdirSync as ln}from"fs";import{extname as Xe,resolve as zt}from"path";import fn from"process";import{join as ui,relative as hi,resolve as rr}from"path";import je from"process";import{Buffer as z}from"buffer";import{createCipheriv as di,createDecipheriv as pi,randomBytes as nt}from"crypto";import{closeSync as it,createReadStream as nr,createWriteStream as yi,existsSync as Ee,fsyncSync as ir,openSync as sr,writeFileSync as wi}from"fs";import{access as $i,constants as or,mkdir as vi,readdir as be,rename as ar,stat as se,unlink as Te,writeFile as st}from"fs/promises";import{isAbsolute as Ci,join as oe,resolve as Ei}from"path";import w from"process";import{pipeline as bi}from"stream/promises";import{createGzip as cr}from"zlib";import ae from"process";import G from"process";var Nr=Object.defineProperty;var Rr=(e)=>e;function Br(e,t){this[e]=Rr.bind(null,t)}var Dr=(e,t)=>{for(var r in t)Nr(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Br.bind(t,r)})},Mr=(e,t)=>()=>(e&&(t=e(e=0)),t);var ur={};Dr(ur,{withErrorRecovery:()=>pr,tryLoadConfig:()=>Rn,loadConfigWithResult:()=>Pn,loadConfig:()=>Cr,isRetryableError:()=>xn,isConfigNotFoundError:()=>Tn,isBunfigError:()=>yr,globalPerformanceMonitor:()=>ge,globalCache:()=>ce,getEnvOrDefault:()=>Sn,generateConfigTypes:()=>Bn,defaultGeneratedDir:()=>Ar,defaultConfigDir:()=>Fr,deepMergeWithArrayStrategy:()=>Et,deepMerge:()=>wr,createLibraryConfig:()=>Dn,config:()=>Nn,bunfigPlugin:()=>Mn,applyEnvVarsToConfig:()=>le,TypeGenerationError:()=>dt,SchemaValidationError:()=>he,PluginError:()=>yt,PerformanceMonitor:()=>$t,FileSystemError:()=>mt,ErrorFactory:()=>H,EnvVarError:()=>Ie,EnvProcessor:()=>Ke,ConfigValidator:()=>bt,ConfigValidationError:()=>ht,ConfigNotFoundError:()=>Le,ConfigMergeError:()=>gt,ConfigLoader:()=>Tt,ConfigLoadError:()=>ue,ConfigFileLoader:()=>We,ConfigCache:()=>wt,CacheUtils:()=>br,BunfigError:()=>L,BrowserConfigError:()=>pt,ArrayMergeStrategies:()=>Sr});class wt{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!kt(e))return!0;return Ft(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=kt(r)?Ft(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class $t{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function un(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function hn(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function gn(e){return e.getStats().size*2}function vt(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&b(t[0])&&"id"in t[0]&&t[0].id===3&&b(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(b(t)&&b(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(b(e)&&"arr"in e&&Array.isArray(e.arr)&&b(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&b(t[0])&&b(e[0])){let n=[...t];for(let i of e)if(b(i)&&"name"in i){if(!n.find((o)=>b(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(b(i)&&"path"in i){if(!n.find((o)=>b(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>Re(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!b(t)||!b(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(b(i)&&b(r[n]))r[n]=vt(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&b(i[0])&&b(r[n][0])){let s=[...i];for(let o of r[n])if(b(o)&&"name"in o){if(!s.find((a)=>b(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(b(o)&&"path"in o){if(!s.find((a)=>b(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Re(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function Re(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Re(e[r],t[r]))return!1;return!0}if(b(e)&&b(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Re(e[i],t[i]))return!1}return!0}return!1}function b(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function mn(e,t){if(!gr(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return vt(t,n)}catch{return null}}catch{return null}}async function dn({name:e="",cwd:t,defaultConfig:r}){let n=t||ct.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of i){let a=Ne(n,`${o}${c}`),l=await mn(a,r);if(l!==null)return l}try{let o=Ne(n,"package.json");if(gr(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return vt(r,a)}catch{}}}catch{}return r}function pn(e,t={}){let r=Pe.cwd();while(r.includes("storage"))r=Pt(r,"..");let n=Pt(r,e||"");if(t?.relative)return Vr(Pe.cwd(),n);return n}async function yn(){try{let e=await dn({name:"clarity",defaultConfig:Se,cwd:Pe.cwd(),endpoint:"",headers:{}});return{...Se,...e}}catch{return Se}}function x(){if(U.env.NODE_ENV==="test"||U.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wn(){if(U.env.NODE_ENV==="test"||U.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof U<"u"){let e=U.type;if(e==="renderer"||e==="worker")return!1;return!!(U.versions&&(U.versions.node||U.versions.bun))}return!1}class mr{async format(e){let t=await wn(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:te.pid,hostname:t(),environment:te.env.NODE_ENV||"development",platform:te.platform,version:te.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:te.env.NODE_ENV||te.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Be{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...ft},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new mr,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??O.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ke,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ke};return{...ke,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ft.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await Jr(this.config.logDirectory,Dt.F_OK|Dt.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await qr(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:q.from(e);try{if(!Ye(this.currentLogFile))await Ge(this.currentLogFile,"",{mode:420});if(i=Bt(this.currentLogFile,"a",420),Gr(i,a,{flag:"a"}),Rt(i),i!==void 0)Ue(i),i=void 0;if((await Q(this.currentLogFile)).size===0){if(await Ge(this.currentLogFile,a,{flag:"w",mode:420}),(await Q(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let g=c*2**s;await new Promise((h)=>setTimeout(h,g)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{Ue(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 ee(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 ee(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ee(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(x())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ze(16).toString("hex")}generateKey(){return ze(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=ze(16),n=zr("aes-256-gcm",t,r),i=q.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:q.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Lt(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(q.from(q.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(x())return;let e=await Q(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await me(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Q(r).catch(()=>null))try{if(await Mt(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await de(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Ge(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Q(r).catch(()=>null))await Mt(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await me(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await de(ee(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Nt(e),n=Yr(t),i=Lt();await Hr(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Ye(this.currentLogFile))try{let e=Bt(this.currentLogFile,"r+");Rt(e),Ue(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!x()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await me(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await de(ee(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?E.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(o)h.push(t);if(s==="warning")h.push("WARN");else if(s==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let a=O.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${E.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,g=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!x()){let l=Tr[e],f=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:E.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:E.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.error(u),c){let g=c.split(`
3
+ `);for(let h of g)if(h.trim()&&!h.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:E.gray(` ${h}`),level:e,showTimestamp:!1}))}break}}else if(!x()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
4
+ `;if(c)a+=`${c}
5
+ `;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!x()){let r=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:E.blue("\u25D0"),tag:r,message:`${E.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
6
+ `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!x()){let f=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:E.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!x())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Be(t,{...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(r),r}createReadStream(){if(x())throw Error("createReadStream is not supported in browser environments");if(!Ye(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Nt(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=q.isBuffer(e)?e:q.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),c=Ur("aes-256-gcm",r,i);return c.setAuthTag(s),q.concat([c.update(o),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return x()}isServerMode(){return!x()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!x()){let s=e.split(`
7
+ `),o=Math.max(...s.map((f)=>f.length))+2,c=`\u250C${"\u2500".repeat(o)}\u2510`,a=`\u2514${"\u2500".repeat(o)}\u2518`,l=s.map((f)=>{let u=" ".repeat(o-f.length-2);return`\u2502 ${f}${u} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:E.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:E.cyan(c)})),l.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:r,message:E.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:E.cyan(a),showTimestamp:!1}))}else if(!x())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(x())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${E.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();O.stdin.removeListener("data",r);try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!1)}catch{}O.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!0)}catch{}O.stdin.resume(),O.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let f=t[c++];switch(l){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!x()){let o=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",c=E.blue("\u25D0");console.error(`${c} ${o} ${E.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||x()||e<=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 r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;O.stdout.write(`${"\r".padEnd(O.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||x()||!O.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=E.green("\u2501".repeat(n)),o=E.gray("\u2501".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=t||r===100?E.green("\u2713"):E.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${E.gray(this.formatTag(this.name))}`:"",g=`\r${f}${u} ${c} ${a}${l}`,h=O.stdout.columns||80,T=" ".repeat(Math.max(0,h-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${T}`,O.stdout.write(e.lastRenderedLine),t)O.stdout.write(`
10
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||x()||!O.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(x()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await me(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=ee(this.config.logDirectory,n);if(e.before)try{if((await Q(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await de(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function xe(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&v(t[0])&&"id"in t[0]&&t[0].id===3&&v(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(v(t)&&v(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(v(e)&&"arr"in e&&Array.isArray(e.arr)&&v(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&v(t[0])&&v(e[0])){let n=[...t];for(let i of e)if(v(i)&&"name"in i){if(!n.find((o)=>v(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(v(i)&&"path"in i){if(!n.find((o)=>v(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>De(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!v(t)||!v(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(v(i)&&v(r[n]))r[n]=xe(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&v(i[0])&&v(r[n][0])){let s=[...i];for(let o of r[n])if(v(o)&&"name"in o){if(!s.find((a)=>v(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(v(o)&&"path"in o){if(!s.find((a)=>v(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>De(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function Ct(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:xe(e,t);if(Array.isArray(e))return r==="replace"?t:xe(e,t);if(!v(t)||!v(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=xe(o,s);else if(v(s)&&v(o))n[i]=Ct(o,s,r);else n[i]=s}return n}function De(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!De(e[r],t[r]))return!1;return!0}if(v(e)&&v(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!De(e[i],t[i]))return!1}return!0}return!1}function v(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Ce(e,t,r="replace"){if(!hr(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Ct(t,i,r)}catch{return null}}catch{return null}}function $n(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],g=(m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase(),h=`${n}_${u.map(g).join("_")}`,T=`${n}_${u.map((m)=>m.toUpperCase()).join("_")}`;if(r)N.info(`Checking environment variable ${h} for config ${e}.${u.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))a[l]=s(f,u);else{let m=fe.env[h]||fe.env[T];if(m!==void 0){if(r)N.info(`Using environment variable ${m?h:T} for config ${e}.${u.join(".")}`);if(typeof f==="number")a[l]=Number(m);else if(typeof f==="boolean")a[l]=m.toLowerCase()==="true";else if(Array.isArray(f))try{let C=JSON.parse(m);if(Array.isArray(C))a[l]=C;else a[l]=m.split(",").map((R)=>R.trim())}catch{a[l]=m.split(",").map((C)=>C.trim())}else a[l]=m}}}return a}return s(i)}async function vn({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?$n(e,i,s):i,l=r||fe.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(s)N.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let u=[e,`.${e}`].filter(Boolean),g=[`${e}.config`,`.${e}.config`].filter(Boolean),h=t?[t,`.${t}`]:[],T=t?[`${t}.config`,`.${t}.config`]:[],m=Array.from(new Set([l,D(l,"config"),D(l,".config"),n?D(l,n):void 0].filter(Boolean)));for(let C of m){if(s)N.info(`Searching for configuration in: ${C}`);let B=[D(l,"config"),D(l,".config")].concat(n?[D(l,n)]:[]).includes(C)?[...u,...g,...h,...T]:[...g,...u,...T,...h];for(let W of B)for(let K of f){let j=D(C,`${W}${K}`),St=await Ce(j,a,c);if(St!==null){if(s)N.success(`Configuration loaded from: ${j}`);return St}}}if(e){let C=D(Ve(),".config",e),R=["config",`${e}.config`];if(t)R.push(`${t}.config`);if(s)N.info(`Checking user config directory: ${C}`);for(let B of R)for(let W of f){let K=D(C,`${B}${W}`),j=await Ce(K,a,c);if(j!==null){if(s)N.success(`Configuration loaded from user config directory: ${K}`);return j}}}if(e){let C=D(Ve(),".config"),R=[`.${e}.config`];if(t)R.push(`.${t}.config`);if(s)N.info(`Checking user config directory for dotfile configs: ${C}`);for(let B of R)for(let W of f){let K=D(C,`${B}${W}`),j=await Ce(K,a,c);if(j!==null){if(s)N.success(`Configuration loaded from user config directory dotfile: ${K}`);return j}}}if(e){let C=Ve(),R=[`.${e}.config`,`.${e}`];if(t)R.push(`.${t}.config`),R.push(`.${t}`);if(s)N.info(`Checking user home directory for dotfile configs: ${C}`);for(let B of R)for(let W of f){let K=D(C,`${B}${W}`),j=await Ce(K,a,c);if(j!==null){if(s)N.success(`Configuration loaded from user home directory: ${K}`);return j}}}try{let C=D(l,"package.json");if(hr(C)){let R=await import(C),B=R[e];if(!B&&t){if(B=R[t],B&&s)N.success(`Using alias "${t}" configuration from package.json`)}if(B&&typeof B==="object"&&!Array.isArray(B))try{if(s)N.success(`Configuration loaded from package.json: ${B===R[e]?e:t}`);return Ct(a,B,c)}catch(W){if(s)N.warn("Failed to merge package.json config:",W)}}}catch(C){if(s)N.warn("Failed to load package.json:",C)}if(s)N.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function Cn(e,t={}){let r=Oe.cwd();while(r.includes("storage"))r=Ot(r,"..");let n=Ot(r,e||"");if(t?.relative)return Kr(Oe.cwd(),n);return n}async function En(){try{let e=await vn({name:"clarity",alias:"logging",defaultConfig:Fe,cwd:Oe.cwd()});return{...Fe,...e||{}}}catch{return Fe}}function S(){if(Y.env.NODE_ENV==="test"||Y.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bn(){if(Y.env.NODE_ENV==="test"||Y.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Y<"u"){let e=Y.type;if(e==="renderer"||e==="worker")return!1;return!!(Y.versions&&(Y.versions.node||Y.versions.bun))}return!1}class dr{async format(e){let t=await bn(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ie.pid,hostname:t(),environment:ie.env.NODE_ENV||"development",platform:ie.platform,version:ie.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ie.env.NODE_ENV||ie.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Me{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(e,t={}){this.name=e,this.config={...ut},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new dr,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??y.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ae,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ae};return{...Ae,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ut.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!S()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await tn(this.config.logDirectory,Kt.F_OK|Kt.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await rn(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:V.from(e);try{if(!pe(this.currentLogFile))await He(this.currentLogFile,"",{mode:420});if(i=_t(this.currentLogFile,"a",420),en(i,a,{flag:"a"}),jt(i),i!==void 0)qe(i),i=void 0;if((await re(this.currentLogFile)).size===0){if(await He(this.currentLogFile,a,{flag:"w",mode:420}),(await re(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let g=c*2**s;await new Promise((h)=>setTimeout(h,g)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{qe(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ne(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ne(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ne(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(S())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Je(16).toString("hex")}generateKey(){return Je(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Je(16),n=Zr("aes-256-gcm",t,r),i=V.isBuffer(e)?e:V.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=V.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Vt(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(V.from(V.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(S())return;if(!this.shouldWriteToFile())return;let e=await re(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ye(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await re(r).catch(()=>null))try{if(await Wt(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await we(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await He(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await re(r).catch(()=>null))await Wt(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await ye(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await we(ne(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=It(e),n=Qr(t),i=Vt();await on(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),pe(this.currentLogFile))try{let e=_t(this.currentLogFile,"r+");jt(e),qe(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await ye(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await we(ne(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?d.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||S())return!1;let e=typeof y.env.NO_COLOR<"u",t=y.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof y.stderr<"u"&&y.stderr.isTTY||typeof y.stdout<"u"&&y.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(o)h.push(t);if(s==="warning")h.push("WARN");else if(s==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let a=y.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${d.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,g=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=d.underline(d.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>d.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>d.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>d.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>d.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>d.strikethrough(n)),t}supportsHyperlinks(){if(S())return!1;let e=y.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=y.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(nn(t)||t.startsWith("./")||t.startsWith("../"))t=sn(t);else return null;return pe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":xr[e],g=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:u,tag:g,message:d.gray(a),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:u,tag:g,message:a,level:e}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:u,tag:g,message:d.green(a),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:u,tag:g,message:a,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:u,tag:g,message:a,level:e}),console.error(h),c){let T=c.split(`
11
+ `);for(let m of T)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:d.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
12
+ `;if(c)f+=`${c}
13
+ `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!S()&&y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!S()&&y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!S()&&y.stdout.isTTY)y.stdout.write(`
14
+ `);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!S()&&y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":d.blue("\u25D0"),tag:r,message:`${d.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
15
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":d.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!S())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Me(t,{...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(r),r}createReadStream(){if(S())throw Error("createReadStream is not supported in browser environments");if(!pe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return It(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=V.isBuffer(e)?e:V.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=Xr("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),f=a.length+l.length,u=V.allocUnsafe(f);return a.copy(u,0),l.copy(u,a.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S()}isServerMode(){return!S()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
16
+ `),a=Math.max(...c.map((g)=>g.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,f=`\u2514${"\u2500".repeat(a)}\u2518`,u=c.map((g)=>this.formatConsoleMessage({timestamp:r,message:d.cyan(g),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:d.cyan(l),showTimestamp:!1})),u.forEach((g)=>console.error(g)),console.error(this.formatConsoleMessage({timestamp:r,message:d.cyan(f),showTimestamp:!1}))}else if(!S())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(S())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${d.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();y.stdin.removeListener("data",r);try{if(typeof y.stdin.setRawMode==="function")y.stdin.setRawMode(!1)}catch{}y.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof y.stdin.setRawMode==="function")y.stdin.setRawMode(!0)}catch{}y.stdin.resume(),y.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let g=t[l++];switch(u){case"s":return String(g);case"d":case"i":return Number(g).toString();case"j":case"o":return JSON.stringify(g,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${d.blue("\u25D0")} `;console.error(`${l}${a} ${d.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!y.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=d.green("\u2501".repeat(n)),o=d.gray("\u2501".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?d.green("\u2713"):d.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${d.gray(this.formatTag(this.name))}`:"",g=`\r${f}${u} ${c} ${a}${l}`,h=y.stdout.columns||80,T=" ".repeat(Math.max(0,h-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${T}`,y.stdout.write(e.lastRenderedLine),t)y.stdout.write(`
19
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||S()||!y.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ye(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=ne(this.config.logDirectory,n);if(e.before)try{if((await re(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await we(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function pr(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function yr(e){return e instanceof L}function Tn(e){return e instanceof Le}function xn(e){if(yr(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class Ke{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=n||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return ge.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((f)=>this.formatEnvKey(f,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let f=$e.env[a]||(l?$e.env[l]:void 0);if(f!==void 0){if(n.verbose){let u=$e.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(f,typeof s,a,n.customParsers,n.configName)}catch(u){if(u instanceof Ie)throw u;throw H.envVar(a,f,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw H.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries($e.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
20
+
21
+ `;for(let n of e)r+=`${n.key}
22
+ `,r+=` Type: ${n.type}
23
+ `,r+=` Description: ${n.description}
24
+ `,r+=` Example: ${n.example}
25
+
26
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
27
+
28
+ `;r+=`| Variable | Type | Description | Example |
29
+ `,r+=`|----------|------|-------------|----------|
30
+ `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
31
+ `;return r}}function Sn(e,t){let r=Er("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function wr(e,t,r={}){return $r(e,t,r,new WeakMap)}function $r(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return vr(e,t,i,n);if(!I(t)||!I(e))return t;return On(e,t,r,n)}function vr(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return kn(e,t);case"smart":return Fn(e,t,n);default:return t}return t}function kn(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>lt(i,n)))r.push(n);return r}function Fn(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(I(t[0])&&I(e[0]))return An(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function An(e,t,r){let n=[...t];for(let i of e){if(!I(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>I(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function On(e,t,r,n){let i=t;if(I(i)&&n.has(i))return n.get(i);let s={...e};if(I(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(I(c)&&I(a))s[o]=$r(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=vr(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function Et(e,t,r="replace"){return wr(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function lt(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!lt(e[r],t[r]))return!1;return!0}if(I(e)&&I(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!lt(e[i],t[i]))return!1}return!0}return!1}function I(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class We{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=ce.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!ve(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,g="default"in f,h=Object.keys(f).length>0;if(!g&&!h)throw new ue(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new ue(e,Error("Configuration must export a valid object"),"unknown");let C={config:Et(t,u,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)ce.setWithFileCheck("file",C,e,s);return C}catch(l){throw l instanceof Error?H.configLoad(e,l):H.configLoad(e,Error(String(l)))}};if(o)return ge.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(Ze(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return pr(async()=>ve(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ve(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=Ze(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=Ze(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){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((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!ve(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class bt{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let f=[],u=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],g);else return this.validateWithJSONSchema(e,t,g)}catch(h){return f.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(c)return await ge.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!an(t))throw new he(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new he(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:kr},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Tt{fileLoader=new We;envProcessor=new Ke;validator=new bt;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let f=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),u=!f&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),g=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(g||f))throw a;if(u&&(!l||!g))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)_.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw _.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||Z.cwd(),g=[],h=await this.loadLocalConfiguration(n,i,u,o,c,l,f,a,r);if(h)return g.push(...this.getLocalSearchPaths(n,i,u,o)),this.finalizeResult(h,g,a,n,f);let T=await this.loadHomeConfiguration(n,i,c,l,f,a);if(T)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(T,g,a,n,f);let m=await this.loadPackageJsonConfiguration(n,i,u,c,l,f,a);if(m)return g.push(M(u,"package.json")),this.finalizeResult(m,g,a,n,f);if(g.push(...this.getAllSearchPaths(n,i,u,o)),t)throw H.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,c,a,f),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?le(e,i,o):i,f=this.getLocalDirectories(r,n);for(let u of f){if(o)_.info(`Searching for configuration in: ${u}`);let g=this.fileLoader.generateConfigPaths(e,u,t),h=await this.fileLoader.tryLoadFromPaths(g,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(h){if(o)_.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?le(e,r,i):r,c=[M(X(),".config",e),M(X(),".config"),X()];for(let a of c){if(i)_.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(f){if(i)_.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?le(e,n,s):n;try{let a=M(r,"package.json");if(!at(a))return null;let l=await import(a),f=l[e],u=e;if(!f&&t)f=l[t],u=t;if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)_.success(`Configuration loaded from package.json: ${u}`);return{config:Et(c,f,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)_.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:le(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw H.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ce.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);ce.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,M(e,"config"),M(e,".config"),t?M(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(M(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[M(X(),".config",e),M(X(),".config"),X()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Ut(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function Pn(e){return J.loadConfig({...e,__strictErrorHandling:!0})}async function Cr(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await J.loadConfig(e);else n=await J.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)_.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await J.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function Nn(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await J.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Ut(r)))return(await J.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await J.loadConfig({...e,cwd:e.cwd||Z.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Ut(t)))return(await J.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Rn(e,t,r="replace"){let n=new We;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function le(e,t,r=!1){let n=new Ke,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],g=[`${i}_${u.join("_").toUpperCase()}`,`${i}_${u.map((m)=>m.toUpperCase()).join("")}`,`${i}_${u.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,T;for(let m of g)if(h=Z.env[m],h!==void 0){T=m;break}if(h!==void 0&&T)if(typeof f==="boolean")a[l]=["true","1","yes"].includes(h.toLowerCase());else if(typeof f==="number"){let m=Number(h);if(!Number.isNaN(m))a[l]=m}else if(Array.isArray(f))try{a[l]=JSON.parse(h)}catch{a[l]=h.split(",").map((m)=>m.trim())}else a[l]=h;else if(f&&typeof f==="object"&&!Array.isArray(f))a[l]=s(f,u)}return a}return s(t)}function Bn(e){let t=M(Z.cwd(),e.configDir),r=M(Z.cwd(),e.generatedDir),n=M(r,"config-types.ts");if(!at(At(n)))Lr(At(n),{recursive:!0,mode:511});let i=at(t)?Ir(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${li}
32
+ export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
33
+ `;jr(n,s,{mode:438})}function Dn(e){let t=null,r=null,n=()=>{if(!r)r=Cr(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)_.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let c=i[o];return n(),c},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,c){if(!t)t={...i};return t[o]=c,!0}})}function Mn(e){let t=zt(fn.cwd(),e?.configDir||"./config");function r(){if(!cn(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=ln(t).filter((a)=>i.has(Xe(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let f=Xe(l).toLowerCase(),u=c.get(a);if(!u){c.set(a,l);continue}let g=Xe(u).toLowerCase();if(s.indexOf(f)<s.indexOf(g))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=i.length?`{
34
+ ${i.map((l)=>{let f=zt(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
35
+ `)}
36
+ }`:"Record<string, any>";return`export type ConfigNames = ${o}
37
+ export type ConfigByName = ${c}
38
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
+ export type ConfigOf = Config
40
+ `}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}var Er,ce,ge,br,Ln,In,Yt,Se,ft,P,E,jn,Gt,_n,Jt,Kn,Wn,Qe,Vn,qt,Ht,et,zn,Un,Yn,Gn,ke,Tr,Jn,N,qn,Hn,Zt,Fe,ut,k,d,Zn,Xt,Xn,Qt,Qn,ei,tt,ti,er,tr,ri,rt,ni,ii,si,oi,ai,Ae,xr,ci,li="0.15.6",L,Le,ue,ht,gt,Ie,mt,dt,he,pt,yt,H,Sr,kr,_,J,Fr,Ar,fi=Mr(async()=>{Er=import.meta.require,ce=new wt,ge=new $t,br={createKey:un,isEquivalent:hn,estimateMemoryUsage:gn},Ln=Ne(ct.cwd(),"config"),In=Ne(ct.cwd(),"src/generated"),Yt=Pe.env.CLARITY_LOG_DIR||Wr(pn(),"logs"),Se={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Yt,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},ft=await yn(),P={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},E=P,jn=P.red,Gt=P.green,_n=P.yellow,Jt=P.blue,Kn=P.magenta,Wn=P.cyan,Qe=P.white,Vn=P.gray,qt=P.bgRed,Ht=P.bgYellow,et=P.bold,zn=P.dim,Un=P.italic,Yn=P.underline,Gn=P.reset,ke={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Tr={debug:"\uD83D\uDD0D",info:Jt("\u2139"),success:Gt("\u2713"),warning:Ht(Qe(et(" WARN "))),error:qt(Qe(et(" ERROR ")))},Jn=new Be("stacks"),N=new Be("bunfig",{showTags:!0}),qn=D(fe.cwd(),"config"),Hn=D(fe.cwd(),"src/generated"),Zt=Oe.env.CLARITY_LOG_DIR||_r(Cn(),"logs"),Fe={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Zt,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ut=await En(),k={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},d=k,Zn=k.red,Xt=k.green,Xn=k.yellow,Qt=k.blue,Qn=k.magenta,ei=k.cyan,tt=k.white,ti=k.gray,er=k.bgRed,tr=k.bgYellow,ri=k.bgGray,rt=k.bold,ni=k.dim,ii=k.italic,si=k.underline,oi=k.strikethrough,ai=k.reset,Ae={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xr={debug:"\uD83D\uDD0D",info:Qt("\u2139"),success:Xt("\u2713"),warning:tr(tt(rt(" WARN "))),error:er(tt(rt(" ERROR ")))},ci=new Me("stacks"),L=class 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}`}},Le=class extends L{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},ue=class extends L{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}},ht=class extends L{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},gt=class extends L{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}},Ie=class extends L{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})}},mt=class extends L{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}},dt=class extends L{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}},he=class extends L{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})}},pt=class extends L{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})}},yt=class extends L{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}},H={configNotFound(e,t,r){return new Le(e,t,r)},configLoad(e,t,r){return new ue(e,t,r)},configValidation(e,t,r){return new ht(e,t,r)},configMerge(e,t,r,n){return new gt(e,t,r,n)},envVar(e,t,r,n){return new Ie(e,t,r,n)},fileSystem(e,t,r){return new mt(e,t,r)},typeGeneration(e,t,r){return new dt(e,t,r)},schemaValidation(e,t,r){return new he(e,t,r)},browserConfig(e,t,r,n){return new pt(e,t,r,n)},plugin(e,t,r){return new yt(e,t,r)}},Sr={replace:"replace",concat:"concat",smart:"smart"},kr=/^https?:\/\//,_=new Me("bunfig",{showTags:!0}),J=new Tt,Fr=M(Z.cwd(),"config"),Ar=M(Z.cwd(),"src/generated")});function gi(e,t={}){let r=je.cwd();while(r.includes("storage"))r=rr(r,"..");let n=rr(r,e||"");if(t?.relative)return hi(je.cwd(),n);return n}var mi=je.env.CLARITY_LOG_DIR||ui(gi(),"logs"),Or={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:mi,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},_e={...Or},As=(async()=>{try{let{loadConfig:e}=await fi().then(()=>ur),t=await e({name:"clarity",alias:"logging",defaultConfig:Or,cwd:je.cwd()});if(t)Object.assign(_e,t)}catch{}return _e})();function F(){if(G.env.NODE_ENV==="test"||G.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ti(){if(G.env.NODE_ENV==="test"||G.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof G<"u"){let e=G.type;if(e==="renderer"||e==="worker")return!1;return!!(G.versions&&(G.versions.node||G.versions.bun))}return!1}class Pr{async format(e){let t=await Ti(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ae.pid,hostname:t(),environment:ae.env.NODE_ENV||"development",platform:ae.platform,version:ae.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ae.env.NODE_ENV||ae.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var A={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},p=A,{red:_s,green:xi,yellow:Ks,blue:Si,magenta:Ws,cyan:Vs,white:lr,gray:zs,bgRed:ki,bgYellow:Fi,bgGray:Us,bold:fr,dim:Ys,italic:Gs,underline:Js,strikethrough:qs,reset:Hs}=A,ot={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ai={debug:"\uD83D\uDD0D",info:Si("\u2139"),success:xi("\u2713"),warning:Fi(lr(fr(" WARN "))),error:ki(lr(fr(" ERROR ")))};class xt{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(e,t={}){this.name=e,this.config={..._e},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Pr,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??w.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ot,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ot};return{...ot,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:_e.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!F()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await $i(this.config.logDirectory,or.F_OK|or.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await vi(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:z.from(e);try{if(!Ee(this.currentLogFile))await st(this.currentLogFile,"",{mode:420});if(i=sr(this.currentLogFile,"a",420),wi(i,a,{flag:"a"}),ir(i),i!==void 0)it(i),i=void 0;if((await se(this.currentLogFile)).size===0){if(await st(this.currentLogFile,a,{flag:"w",mode:420}),(await se(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let g=c*2**s;await new Promise((h)=>setTimeout(h,g)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{it(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 oe(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 oe(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return oe(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(F())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return nt(16).toString("hex")}generateKey(){return nt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=nt(16),n=di("aes-256-gcm",t,r),i=z.isBuffer(e)?e:z.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=z.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=cr(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(z.from(z.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(F())return;if(!this.shouldWriteToFile())return;let e=await se(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await be(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await se(r).catch(()=>null))try{if(await ar(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Te(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await st(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await se(r).catch(()=>null))await ar(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await be(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Te(oe(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=nr(e),n=yi(t),i=cr();await bi(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Ee(this.currentLogFile))try{let e=sr(this.currentLogFile,"r+");ir(e),it(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!F()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await be(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Te(oe(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?p.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F())return!1;let e=typeof w.env.NO_COLOR<"u",t=w.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof w.stderr<"u"&&w.stderr.isTTY||typeof w.stdout<"u"&&w.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(o)h.push(t);if(s==="warning")h.push("WARN");else if(s==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let a=w.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${p.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,g=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=p.underline(p.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>p.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>p.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>p.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>p.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>p.strikethrough(n)),t}supportsHyperlinks(){if(F())return!1;let e=w.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=w.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Ci(t)||t.startsWith("./")||t.startsWith("../"))t=Ei(t);else return null;return Ee(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Ai[e],g=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:u,tag:g,message:p.gray(a),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:u,tag:g,message:a,level:e}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:u,tag:g,message:p.green(a),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:u,tag:g,message:a,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:u,tag:g,message:a,level:e}),console.error(h),c){let T=c.split(`
41
+ `);for(let m of T)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:p.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!F()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
42
+ `;if(c)f+=`${c}
43
+ `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!F()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!F()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!F()&&w.stdout.isTTY)w.stdout.write(`
44
+ `);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!F()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":p.blue("\u25D0"),tag:r,message:`${p.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
45
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":p.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!F())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new xt(t,{...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(r),r}createReadStream(){if(F())throw Error("createReadStream is not supported in browser environments");if(!Ee(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return nr(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=z.isBuffer(e)?e:z.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=pi("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),f=a.length+l.length,u=z.allocUnsafe(f);return a.copy(u,0),l.copy(u,a.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}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(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
46
+ `),a=Math.max(...c.map((g)=>g.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,f=`\u2514${"\u2500".repeat(a)}\u2518`,u=c.map((g)=>this.formatConsoleMessage({timestamp:r,message:p.cyan(g),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:p.cyan(l),showTimestamp:!1})),u.forEach((g)=>console.error(g)),console.error(this.formatConsoleMessage({timestamp:r,message:p.cyan(f),showTimestamp:!1}))}else if(!F())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(F())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${p.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();w.stdin.removeListener("data",r);try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!1)}catch{}w.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!0)}catch{}w.stdin.resume(),w.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let g=t[l++];switch(u){case"s":return String(g);case"d":case"i":return Number(g).toString();case"j":case"o":return JSON.stringify(g,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${p.blue("\u25D0")} `;console.error(`${l}${a} ${p.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
48
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!w.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=p.green("\u2501".repeat(n)),o=p.gray("\u2501".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?p.green("\u2713"):p.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${p.gray(this.formatTag(this.name))}`:"",g=`\r${f}${u} ${c} ${a}${l}`,h=w.stdout.columns||80,T=" ".repeat(Math.max(0,h-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${T}`,w.stdout.write(e.lastRenderedLine),t)w.stdout.write(`
49
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||F()||!w.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(F()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await be(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=oe(this.config.logDirectory,n);if(e.before)try{if((await se(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Te(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var Zs=new xt("stacks");export{xt as Logger};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{J}from"./chunk-0b2yx624.js";var i=null,r=null,l=!1,a=!0;function b(){if(l)return a;try{return i=(()=>{throw new Error("Cannot require module "+"@stacksjs/ts-spell-check");})(),i.SpellChecker.create({minWordLength:3,maxSuggestions:3}).then((n)=>{r=n}).catch(()=>{a=!1}),l=!0,!0}catch{return l=!0,a=!1,!1}}function u(n,t){return{meta:{docs:n==="spell/check"?"Check spelling in text content":n==="spell/check-comments"?"Check spelling in code comments only":"Check spelling in markdown files"},check(d,h){if(!b()||!i)return[];let{extractWords:C,parseDirectives:y,isSuppressed:L,getProgrammingWords:W}=i,f=h.options,c=new Set((f?.words||[]).map((s)=>s.toLowerCase())),P=f?.minWordLength||3,x=W(),g=y(d);for(let s of g)if(s.type==="word")s.words.forEach((o)=>c.add(o.toLowerCase()));let m=d.split(/\r?\n/),p=[];for(let s=0;s<m.length;s++){let o=m[s],k=s+1;if(t&&!t(o))continue;let R=C(o);for(let{word:e,offset:S}of R){if(e.length<P)continue;if(e===e.toUpperCase()&&e.length<=5)continue;if(c.has(e.toLowerCase()))continue;if(x.has(e.toLowerCase()))continue;if(L(e,k,g,c))continue;if(r){if(r.isCorrect(e))continue;let w=r.suggest(e);p.push({filePath:h.filePath,line:k,column:S+1,ruleId:n,message:`Unknown word: "${e}"`,severity:"warning",help:w.length?`Did you mean: ${w.slice(0,3).join(", ")}? Or add to config words.`:`Add "${e}" to your config words array, or use: // spell-check:ignore ${e}`})}}}return p}}}function v(n){let t=n.trimStart();return t.startsWith("//")||t.startsWith("/*")||t.startsWith("*")||t.startsWith("#")}var _={name:"spell",rules:{check:u("spell/check"),"check-comments":u("spell/check-comments",v),"check-markdown":{meta:{docs:"Check spelling in markdown files"},check(n,t){if(!t.filePath.endsWith(".md"))return[];return u("spell/check-markdown").check(n,t)}}}};export{_ as spellPlugin};
@@ -0,0 +1,8 @@
1
+ // @bun
2
+ var k={npm:"registry.npmjs.org",yarn:"registry.yarnpkg.com",verdaccio:"registry.verdaccio.org"};function v(s){let t=s.split("/").pop()||"";if(t==="package-lock.json")return"npm";if(t==="yarn.lock")return"yarn";if(t==="bun.lockb"||t==="bun.lock")return"bun";return null}function p(s,t){let e=v(t);if(!e)return!1;if(e==="npm")try{let r=JSON.parse(s);return"lockfileVersion"in r||"dependencies"in r||"packages"in r}catch{return!1}if(e==="yarn")return s.startsWith("#")||s.includes("__metadata:")||s.includes('resolved "');if(e==="bun")try{let r=JSON.parse(s);return"lockfileVersion"in r||"packages"in r}catch{return!1}return!1}function A(s){let t=new Map,e=JSON.parse(s);if((e.lockfileVersion||1)>=2&&e.packages)for(let[i,n]of Object.entries(e.packages)){if(!i||i==="")continue;let o=i.replace(/^node_modules\//,"").replace(/\/node_modules\//g,"/"),c=o.split("/node_modules/").pop()||o;t.set(i,{name:c,version:n.version||"",resolved:n.resolved,integrity:n.integrity})}else if(e.dependencies)P(e.dependencies,t,"");return{type:"npm",packages:t}}function P(s,t,e){for(let[r,i]of Object.entries(s)){let n=e?`${e}/${r}`:r;if(t.set(n,{name:r,version:i.version||"",resolved:i.resolved,integrity:i.integrity}),i.dependencies)P(i.dependencies,t,n)}}function M(s){let t=new Map,e=s.includes("__metadata:"),r=e?"yarn-berry":"yarn",i=s.split(`
3
+ `),n="",o={};for(let c of i){if(c.startsWith("#")||c.trim()==="")continue;if(!c.startsWith(" ")&&c.includes("@")&&c.endsWith(":")){if(n&&(o.resolved||o.integrity))t.set(n,o);if(n=c.slice(0,-1).trim(),n.startsWith('"')&&n.endsWith('"'))n=n.slice(1,-1);let a=n.match(/^(@?[^@]+)@/);o={name:a?a[1]:n.split("@")[0],version:""}}else if(c.startsWith(" ")||c.startsWith("\t")){let a=c.trim();if(a.startsWith("version")){let l=a.match(/version[:\s]+"?([^"]+)"?/);if(l)o.version=l[1]}else if(a.startsWith("resolved")){let l=a.match(/resolved[:\s]+"?([^"]+)"?/);if(l)o.resolved=l[1]}else if(a.startsWith("resolution:")&&e){let l=a.match(/resolution[:\s]+"?([^"]+)"?/);if(l)o.resolved=l[1]}else if(a.startsWith("integrity")||a.startsWith("checksum")){let l=a.match(/(integrity|checksum)[:\s]+"?([^"]+)"?/);if(l)o.integrity=l[2]}}}if(n&&(o.resolved||o.integrity))t.set(n,o);return{type:r,packages:t}}function W(s){let t=new Map,e=JSON.parse(s);if(e.packages)for(let[r,i]of Object.entries(e.packages)){if(!r||r==="")continue;if(Array.isArray(i)){let[n,o,c,a]=i,l=r,f="";if(typeof n==="string"&&n.includes("@")){let u=n.lastIndexOf("@");if(u>0)l=n.substring(0,u),f=n.substring(u+1)}t.set(r,{name:l,version:f,resolved:o||void 0,integrity:a||void 0})}else if(typeof i==="object")t.set(r,{name:i.name||r.split("@")[0],version:i.version||"",resolved:i.resolved,integrity:i.integrity||i.hash})}return{type:"bun",packages:t}}function m(s,t){let e=v(t);if(!e)return null;try{switch(e){case"npm":return A(s);case"yarn":return M(s);case"bun":return W(s);default:return null}}catch{return null}}function L(s){try{return new URL(s).hostname}catch{return null}}function y(s){try{return new URL(s).protocol}catch{return null}}function R(s){try{let e=new URL(s).pathname,r=e.indexOf("/-/");if(r===-1)return null;let i=e.substring(1,r);if(i.startsWith("@"))return i;return i}catch{return null}}function b(s){if(!s)return null;let t=s.match(/^(sha\d+)-/);return t?t[1]:null}function x(s){return s.map((t)=>{let e=t.toLowerCase();return k[e]||t})}var w={meta:{docs:"Ensure all packages are from allowed registry hosts",recommended:!0},check(s,t){let e=[];if(!p(s,t.filePath))return e;let r=m(s,t.filePath);if(!r)return e;let i=t.options||{},n=i.allowedHosts||["npm","yarn"],o=i.emptyHostname!==!1,c=x(n),a=s.split(`
4
+ `);for(let[l,f]of r.packages){if(!f.resolved){if(!o){let d=I(a,l);e.push({filePath:t.filePath,line:d,column:1,ruleId:"lockfile/validate-host",message:`Package "${f.name}" has no resolved URL`,severity:"error",help:"All packages should have a resolved URL from an allowed registry."})}continue}let u=L(f.resolved);if(!u)continue;if(!c.includes(u)){let d=I(a,l),h=n.map((g)=>k[g.toLowerCase()]||g).join(", ");e.push({filePath:t.filePath,line:d,column:1,ruleId:"lockfile/validate-host",message:`Invalid host for package "${f.name}": expected one of [${h}], got "${u}"`,severity:"error",help:`Package is resolving from an unauthorized registry. This could indicate a supply chain attack. Allowed hosts: ${h}`})}}return e}};function I(s,t){for(let e=0;e<s.length;e++)if(s[e].includes(t)||s[e].includes(`"${t}"`))return e+1;return 1}var S={meta:{docs:"Ensure all packages use HTTPS protocol",recommended:!0},check(s,t){let e=[];if(!p(s,t.filePath))return e;let r=m(s,t.filePath);if(!r)return e;let i=s.split(`
5
+ `);for(let[n,o]of r.packages){if(!o.resolved)continue;let c=y(o.resolved);if(!c)continue;if(c!=="https:"){let a=T(i,n);e.push({filePath:t.filePath,line:a,column:1,ruleId:"lockfile/validate-https",message:`Package "${o.name}" uses insecure protocol: "${c}" instead of "https:"`,severity:"error",help:"All packages should be downloaded over HTTPS to prevent man-in-the-middle attacks."})}}return e}};function T(s,t){for(let e=0;e<s.length;e++)if(s[e].includes(t)||s[e].includes(`"${t}"`))return e+1;return 1}var N={meta:{docs:"Ensure all packages use strong integrity hashes (SHA512)",recommended:!0},check(s,t){let e=[];if(!p(s,t.filePath))return e;let r=m(s,t.filePath);if(!r)return e;let i=t.options||{},n=i.requiredAlgorithm||"sha512",o=new Set(i.exclude||[]),c={sha1:1,sha256:2,sha384:3,sha512:4},a=c[n]||4,l=s.split(`
6
+ `);for(let[f,u]of r.packages){if(o.has(u.name))continue;if(!u.integrity)continue;let d=b(u.integrity);if(!d)continue;if((c[d.toLowerCase()]||0)<a){let g=U(l,f);e.push({filePath:t.filePath,line:g,column:1,ruleId:"lockfile/validate-integrity",message:`Package "${u.name}" uses weak hash algorithm: "${d}" (required: ${n})`,severity:"error",help:`Weak hash algorithms are susceptible to collision attacks. Upgrade to ${n} by regenerating your lockfile with a recent package manager.`})}}return e}};function U(s,t){for(let e=0;e<s.length;e++)if(s[e].includes(t)||s[e].includes(`"${t}"`))return e+1;return 1}var C={meta:{docs:"Ensure package names match their resolved URLs",recommended:!0},check(s,t){let e=[];if(!p(s,t.filePath))return e;let r=m(s,t.filePath);if(!r)return e;let n=(t.options||{}).aliases||{},o=Object.values(k),c=s.split(`
7
+ `);for(let[a,l]of r.packages){if(!l.resolved)continue;let f=!1;try{let g=new URL(l.resolved);f=o.includes(g.hostname)}catch{continue}if(!f)continue;let u=R(l.resolved);if(!u)continue;let d=l.name,h=n[d]||d;if(u!==h){let g=E(c,a);e.push({filePath:t.filePath,line:g,column:1,ruleId:"lockfile/validate-package-names",message:`Package name mismatch: "${d}" resolves to "${u}"`,severity:"error",help:`This could indicate a package substitution attack. The lockfile entry is for "${d}" but the resolved URL points to "${u}".`})}}return e}};function E(s,t){for(let e=0;e<s.length;e++)if(s[e].includes(t)||s[e].includes(`"${t}"`))return e+1;return 1}var H={meta:{docs:"Ensure all packages use allowed URL schemes",recommended:!0},check(s,t){let e=[];if(!p(s,t.filePath))return e;let r=m(s,t.filePath);if(!r)return e;let o=((t.options||{}).allowedSchemes||["https:","git+https:","git+ssh:"]).map((a)=>a.endsWith(":")?a:`${a}:`),c=s.split(`
8
+ `);for(let[a,l]of r.packages){if(!l.resolved)continue;let f=y(l.resolved);if(!f)continue;if(!o.includes(f)){let u=O(c,a);e.push({filePath:t.filePath,line:u,column:1,ruleId:"lockfile/validate-scheme",message:`Package "${l.name}" uses disallowed URL scheme: "${f}"`,severity:"error",help:`Only the following URL schemes are allowed: ${o.join(", ")}. Using "${f}" could be a security risk.`})}}return e}};function O(s,t){for(let e=0;e<s.length;e++)if(s[e].includes(t)||s[e].includes(`"${t}"`))return e+1;return 1}var te={name:"lockfile",rules:{"validate-host":w,"validate-https":S,"validate-integrity":N,"validate-package-names":C,"validate-scheme":H}};export{te as lockfilePlugin};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{l,Y,W}from"./chunk-1jtr81zg.js";export{W as config,l as defaultConfig,Y as getConfig};