@stacksjs/build 0.70.161 → 0.70.162
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +143 -124
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,97 +1,116 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`||c==="\r"?c:" ":c;continue}if(
|
|
2
|
+
var Ll=Object.defineProperty;var jl=(e)=>e;function _l(e,t){this[e]=jl.bind(null,t)}var Zl=(e,t)=>{for(var r in t)Ll(e,r,{get:t[r],enumerable:!0,configurable:!0,set:_l.bind(t,r)})};var ue=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ye=import.meta.require;import{readFile as Jl,stat as qd,writeFile as Vl}from"fs/promises";async function us(e,t){if(Er)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await Vl(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function ot(e){if(Er)return globalThis.Bun.file(e).text();return Jl(e,"utf-8")}var Er,zd;var Or=ue(()=>{Er=typeof globalThis.Bun<"u",zd=!Er&&typeof process<"u"&&!!process.versions?.node});import{existsSync as Yl,statSync as Kl}from"fs";import{dirname as Gl,extname as Ul,isAbsolute as Ii,resolve as Hl}from"path";function kr(e){try{return Kl(e).isFile()}catch{return!1}}function Sr(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!Ii(r))return{resolved:null,isRelative:!1};let i=Gl(t),n=Ii(r)?r:Hl(i,r);if(kr(n))return{resolved:n,isRelative:!0};let s=Ul(n),o=ql[s];if(o){let a=n.slice(0,-s.length);for(let c of o){let f=a+c;if(kr(f))return{resolved:f,isRelative:!0}}}for(let a of hs){let c=n+a;if(kr(c))return{resolved:c,isRelative:!0}}if(Yl(n))for(let a of hs){let c=`${n}/index${a}`;if(kr(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function zl(e){let t=e.length,r="",i=0;while(i<t){let n=e.charCodeAt(i);if(n===34||n===39||n===96){let s=n;r+=e[i++];while(i<t){let o=e.charCodeAt(i),a=e[i++];if(r+=s===96&&o!==s?o===10||o===13?a:" ":a,o===92&&i<t){let c=e[i++];r+=s===96?c===`
|
|
3
|
+
`||c==="\r"?c:" ":c;continue}if(o===s)break}continue}if(n===47&&i+1<t){let s=e.charCodeAt(i+1);if(s===47){i+=2;while(i<t&&e.charCodeAt(i)!==10)i++;continue}if(s===42){i+=2;while(i+1<t&&!(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47))i++;i+=2;continue}}r+=e[i++]}return r}function Bi(e,t={}){let r=[],i=zl(e);ds.lastIndex=0;let n;while((n=ds.exec(i))!==null){let s=!!n[1],o=n[3],a=n[0],c;if(a.includes("* as "))c="export-star-as";else if(a.includes("*"))c="export-star";else c="export-named";r.push({specifier:o,kind:c,isTypeOnly:s})}if(t.includeImports){ms.lastIndex=0;while((n=ms.exec(i))!==null)r.push({specifier:n[3],kind:"import",isTypeOnly:!!n[1]})}return r}async function Li(e,t={}){let r=new Set,i=new Map,n=[],s=[];for(let o of e)if(!r.has(o))r.add(o),s.push(o);while(s.length>0){let o=s.shift(),a;try{a=await ot(o)}catch{continue}let c=Bi(a,t);i.set(o,c);for(let f of c){if(!(f.specifier.startsWith(".")||Ii(f.specifier)))continue;let u=Sr(f.specifier,o);if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),s.push(u.resolved)}else n.push({from:o,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:r,reExports:i,unresolved:n}}var hs,ql,ds,ms;var gs=ue(()=>{Or();hs=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],ql={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};ds=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,ms=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";\n]+\s+from\s+)?(['"])([^'"]+)\2/g});function lr(e){if(Xl)return Bun.hash(e);let t=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=(t<<5)-t+i,t=t&t}return t}var Xl;var ji=ue(()=>{Xl=typeof globalThis.Bun?.hash==="function"});import{existsSync as cr,mkdirSync as Ql,readFileSync as Zi,renameSync as ec,rmSync as ps,statSync as ys,writeFileSync as $s}from"fs";import{join as ws,relative as Tr,resolve as tc}from"path";class Ji{cacheDir;manifestPath;manifest=null;configHash;constructor(e){this.cacheDir=tc(e.cwd,Rr),this.manifestPath=ws(this.cacheDir,rc),this.configHash=this.hashConfig(e)}hashConfig(e){let t={keepComments:e.keepComments,importOrder:e.importOrder,outputStructure:e.outputStructure,isolatedDeclarations:e.isolatedDeclarations,declarationMap:e.declarationMap,indentStyle:e.indentStyle,indentSize:e.indentSize,prettier:e.prettier,typeMappings:e.typeMappings?{includeDefaults:e.typeMappings.includeDefaults,presets:e.typeMappings.presets,cacheKey:e.typeMappings.cacheKey,rules:e.typeMappings.rules.map((r)=>({pattern:typeof r.pattern==="string"?{kind:"string",value:r.pattern}:{kind:"regex",source:r.pattern.source,flags:r.pattern.flags},replacement:r.replacement,global:r.global,priority:r.priority,hasCondition:Boolean(r.condition)}))}:void 0,lineEnding:e.lineEnding,normalizeOutput:e.normalizeOutput,declarationOrder:e.declarationOrder,plugins:e.plugins?.map((r)=>({name:r.name,version:r.version,cacheKey:r.cacheKey}))};return String(lr(JSON.stringify(t)))}hashString(e){return String(lr(e))}load(){try{if(!cr(this.manifestPath))return!1;let e=Zi(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==_i)return!1;if(t.configHash!==this.configHash)return!1;if(!t.entries||typeof t.entries!=="object"||Array.isArray(t.entries))return!1;return this.manifest=t,!0}catch{return!1}}save(){if(!this.manifest)this.manifest={version:_i,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!cr(this.cacheDir))Ql(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{$s(e,JSON.stringify(this.manifest,null,2)),ec(e,this.manifestPath)}finally{if(cr(e))ps(e,{force:!0})}}needsRegeneration(e,t){return this.getCachedIfValid(e,t)===null}getCached(e,t){return this.getCachedIfValid(e,t)}getCachedIfValid(e,t){if(!this.manifest)return null;let r=Tr(t,e),i=this.manifest.entries[r];if(!i)return null;if(typeof i.dtsContent!=="string"||typeof i.dtsHash!=="string"||i.configHash!==this.configHash||this.hashString(i.dtsContent)!==i.dtsHash)return null;try{let n=ys(e),s=n.mtimeMs,o=n.ctimeMs;if(n.size!==i.sourceSize)return null;if(s!==i.sourceMtime||o!==i.sourceCtime){let a=Zi(e,"utf-8");if(this.hashString(a)!==i.sourceHash)return null;i.sourceMtime=s,i.sourceCtime=o}return i.dtsContent}catch{return null}}update(e,t,r,i){if(!this.manifest)this.manifest={version:_i,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let n=Tr(i,e),s,o,a;try{let c=ys(e);s=c.mtimeMs,o=c.ctimeMs,a=c.size}catch{s=Date.now(),o=s,a=Buffer.byteLength(t)}this.manifest.entries[n]={sourcePath:n,sourceHash:this.hashString(t),sourceMtime:s,sourceCtime:o,sourceSize:a,dtsContent:r,dtsHash:this.hashString(r),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let r=Tr(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(cr(this.manifestPath))ps(this.cacheDir,{recursive:!0,force:!0})}catch{}}getStats(){if(!this.manifest)return{entries:0,size:0};let e=Object.keys(this.manifest.entries).length,t=0;for(let r of Object.values(this.manifest.entries))t+=r.dtsContent.length;return{entries:e,size:t}}prune(e,t){if(!this.manifest)return 0;let r=0,i=new Set(Array.from(e).map((n)=>Tr(t,n)));for(let n of Object.keys(this.manifest.entries))if(!i.has(n))delete this.manifest.entries[n],r++;return r}}function Cs(e){let t=ws(e,".gitignore");try{let r="";if(cr(t))r=Zi(t,"utf-8");if(!r.split(/\r?\n/).some((i)=>i.trim()===Rr||i.trim()===`${Rr}/`)){let i=r.trimEnd(),n=`${i}${i?`
|
|
4
4
|
|
|
5
5
|
`:""}# dtsx cache
|
|
6
|
-
${
|
|
7
|
-
|
|
8
|
-
`)||n.includes("\r"))return"string";return n}if(n.
|
|
9
|
-
|
|
6
|
+
${Rr}/
|
|
7
|
+
`;$s(t,n)}}catch{}}var _i=3,Rr=".dtsx-cache",rc="manifest.json";var bs=ue(()=>{ji()});function As(e,t){let r=Number.isFinite(t)?Math.max(1,Math.floor(t)):1;if(e===void 0||!Number.isFinite(e))return r;return Math.max(1,Math.floor(e))}var vs=()=>{};function ic(e){if(e.indexOf("/*")===-1)return e.trim();let t=[],r=0,i=0,n=e.length;while(i<n)if(e.charCodeAt(i)===47&&i+1<n&&e.charCodeAt(i+1)===42){if(i>r)t.push(e.substring(r,i));i+=2;while(i<n-1){if(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47){i+=2;break}i++}r=i}else i++;if(r<n)t.push(e.substring(r));return t.join("").trim()}function Hi(){Wr=!0,Le=null}function qi(){Wr=!1;let e=Le;return Le=null,e}function zi(e){let t=e.length;if(t===0)return!1;let r=0;if(e.charCodeAt(r)===45)r++;if(r>=t)return!1;let i=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===i)return!1;if(r<t&&e.charCodeAt(r)===46){r++;let n=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===n)return!1}return r===t}function nc(e){for(let t=0,r=e.length-1;t<r;t++){let i=e.charCodeAt(t);if(i<48||i>57)return!1}return!0}function Vi(e,t){let r=0,i=0;while((i=e.indexOf(t,i))!==-1)r++,i+=t.length;return r}function fr(e){let t=e.length,r=!1;for(let o=1;o<t;o++)if(e.charCodeAt(o)<=32&&e.charCodeAt(o-1)<=32){r=!0;break}if(!r)for(let o=0;o<t;o++){let a=e.charCodeAt(o);if(a===10||a===13||a===9){r=!0;break}}if(!r)return e;let i=[],n=-1,s=!1;for(let o=0;o<t;o++)if(e.charCodeAt(o)<=32){if(!s){if(n>=0)i.push(e.substring(n,o));i.push(" "),s=!0,n=-1}}else{if(s||n<0)n=o;s=!1}if(n>=0)i.push(e.substring(n));return i.join("")}function xe(e,t=!1,r=!1,i=0){if(!e||typeof e!=="string")return"unknown";if(i>=20)return"unknown";let n=e.trim();if(n.startsWith("BigInt("))return"bigint";if(n.startsWith("Symbol.for("))return"symbol";if(n.includes(".raw`")||n.includes("String.raw`"))return"string";if(n.startsWith("`")&&n.endsWith("`")){if(!t||n.includes("${")||n.includes(`
|
|
8
|
+
`)||n.includes("\r"))return"string";return n}if(n.charCodeAt(0)===39||n.charCodeAt(0)===34){let s=sc(n);if(s!==null){if(s==="string"||!t)return"string";return s}}if(zi(n)){if(!t)return"number";return n}if(n==="true"||n==="false"){if(!t)return"boolean";return n}if(n==="null")return"null";if(n==="undefined")return"undefined";if(n.startsWith("[")&&n.endsWith("]"))return Yi(n,t,i+1);if(n.startsWith("{")&&n.endsWith("}"))return wc(n,t,i+1);if(n.startsWith("class ")||n.startsWith("class{"))return yc(n);if(n.startsWith("new "))return pc(n);if(n.endsWith("as const")){let s=n.slice(0,-8).trim();if(s.startsWith("[")&&s.endsWith("]")){let o=s.slice(1,-1).trim();if(!o)return"readonly []";let a=Nr(o),c=[];for(let f=0;f<a.length;f++)c.push(xe(a[f].trim(),!0,!1,i+1));return`readonly [${c.join(", ")}]`}return xe(s,!0,r,i+1)}if(n.includes("=>")||n.startsWith("function")||n.startsWith("async"))return Ps(n,r,i,t);if(n.startsWith("`")&&n.endsWith("`"))return gc(n,t);if(n.startsWith("Promise."))return Ns(n,t,i);if(n.startsWith("await "))return"unknown";if(n.charCodeAt(n.length-1)===110&&n.length>1&&nc(n)){if(t)return n;return"bigint"}if(n.startsWith("Symbol(")||n==="Symbol.for")return"symbol";if(fc(n))return"boolean";if(cc(n))return"number";return"unknown"}function xs(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return Tt(e,0,t)===e.length}function sc(e){if(xs(e))return e;let t=oc(e);if(t.length<2)return null;let r=!1,i=!0,n="";for(let s of t){let o=s.trim();if(xs(o))r=!0,n+=ac(o);else i=!1}if(i)return lc(n);if(r)return"string";return null}function oc(e){let t=[],r=0,i=0,n=0;while(n<e.length){let s=e.charCodeAt(n);if(s===39||s===34||s===96){n=Tt(e,n,s);continue}if(s===40||s===91||s===123)r++;else if(s===41||s===93||s===125)r--;else if(s===43&&r===0)t.push(e.slice(i,n)),i=n+1;n++}return t.push(e.slice(i)),t}function ac(e){return e.slice(1,-1).replace(/\\(.)/g,(t,r)=>{if(r==="n")return`
|
|
9
|
+
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function lc(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function cc(e){if(e==="")return!1;let t=!1,r=!1;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);if(n>=48&&n<=57){t=!0;continue}if(n===43||n===45||n===42||n===47||n===37){r=!0;continue}if(n===46||n===40||n===41||n<=32)continue;return!1}return t&&r}function fc(e){let t=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i===34||i===39||i===96){r=Tt(e,r,i)-1;continue}if(i===40||i===91||i===123){t++;continue}if(i===41||i===93||i===125){t--;continue}if(t!==0)continue;if(e.startsWith("===",r)||e.startsWith("!==",r)||e.startsWith("==",r)||e.startsWith("!=",r)||e.startsWith(">=",r)||e.startsWith("<=",r))return!0;if((i===62||i===60)&&e.charCodeAt(r-1)!==61&&e.charCodeAt(r+1)!==61)return!0}return!1}function uc(e,t=!1,r=0){return xe(e,t,!0,r)}function ur(e,t=!1,r=""){let i=Rs(r),n=[],s=!1,o=0;while(o<e.length){let c=e.charCodeAt(o);if(c===34||c===39||c===96){o=Tt(e,o,c);continue}if(c===47&&e.charCodeAt(o+1)===47){o+=2;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(c===47&&e.charCodeAt(o+1)===42){let f=e.indexOf("*/",o+2);o=f===-1?e.length:f+2;continue}if(e.startsWith("function",o)&&Es(e,o,8)||e.startsWith("class",o)&&Es(e,o,5)){let f=mc(e,o);if(f!==-1){o=Os(e,f);continue}}if(c===61&&e.charCodeAt(o+1)===62){let f=o+2;while(f<e.length&&e.charCodeAt(f)<=32)f++;if(e.charCodeAt(f)===123){o=Os(e,f);continue}}if(e.startsWith("return",o)&&(o===0||!nt(e.charCodeAt(o-1)))&&!nt(e.charCodeAt(o+6))){o+=6;let f=!1;while(o<e.length&&e.charCodeAt(o)<=32){let $=e.charCodeAt(o);if($===10||$===13)f=!0;o++}if(f||o>=e.length||e.charCodeAt(o)===59||e.charCodeAt(o)===125){s=!0;continue}let u=o,l=0,p=0,h=0;while(o<e.length){let $=e.charCodeAt(o);if($===34||$===39||$===96){o=Tt(e,o,$);continue}if($===47&&e.charCodeAt(o+1)===47)break;if($===47&&e.charCodeAt(o+1)===42){let x=e.indexOf("*/",o+2);o=x===-1?e.length:x+2;continue}if($===40)l++;else if($===41)l--;else if($===91)p++;else if($===93)p--;else if($===123)h++;else if($===125){if(h===0&&l===0&&p===0)break;h--}else if($===59&&l===0&&p===0&&h===0)break;o++}let w=e.slice(u,o).trim(),A=St(w,i);if(!n.includes(A))n.push(A);continue}o++}if(s&&!n.includes("undefined"))n.push("undefined");let a=n.includes("unknown")?"unknown":n.length===0?"void":n.join(" | ");return t&&!a.startsWith("Promise<")?`Promise<${a}>`:a}function Rs(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,i=0,n=0,s=0;for(let o=0;o<=r.length;o++){let a=r.charCodeAt(o);if(a===40||a===91||a===123)n++;else if(a===41||a===93||a===125)n--;else if(a===60)s++;else if(a===62&&r.charCodeAt(o-1)!==61&&s>0)s--;if(o!==r.length&&(a!==44||n!==0||s!==0))continue;let c=r.slice(i,o).trim(),f=c.indexOf(":");if(f!==-1){let u=c.slice(0,f).trim().replace(/^\.\.\./,"").replace(/\?$/,""),l=c.slice(f+1).trim(),p=l.indexOf("=");if(p!==-1)l=l.slice(0,p).trim();if(hr(u)&&l)t.set(u,l)}i=o+1}return t}function St(e,t){let r=e.trim();while(hc(r))r=r.slice(1,-1).trim();if(r.startsWith("await ")){let s=St(r.slice(6),t);return s.startsWith("Promise<")&&s.endsWith(">")?s.slice(8,-1):s}if(t.has(r))return t.get(r);if(r.startsWith("!"))return"boolean";if(r.startsWith("fetch("))return"Promise<Response>";let i=dc(r);if(i){let s=St(i.whenTrue,t),o=St(i.whenFalse,t);return s===o?s:`${s} | ${o}`}if(["===","!==","==","!=",">=","<="].some((s)=>r.includes(s))||r.includes(" > ")||r.includes(" < "))return"boolean";let n=0;for(let s=r.length-1;s>=0;s--){let o=r.charCodeAt(s);if(o===41||o===93||o===125)n++;else if(o===40||o===91||o===123)n--;else if(n===0&&(o===43||o===45||o===42||o===47||o===37)){let a=St(r.slice(0,s),t),c=St(r.slice(s+1),t);if(o===43&&(a==="string"||c==="string"))return"string";if(a==="number"&&c==="number")return"number";break}}return xe(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(s)=>{let o=s.slice(7);return t.get(o)??"unknown"})}function hc(e){if(!e.startsWith("(")||!e.endsWith(")"))return!1;let t=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i===40)t++;else if(i===41&&--t===0)return r===e.length-1}return!1}function dc(e){let t=0,r=-1;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);if(n===40||n===91||n===123)t++;else if(n===41||n===93||n===125)t--;else if(n===63&&t===0&&e.charCodeAt(i+1)!==63)r=i;else if(n===58&&t===0&&r!==-1)return{whenTrue:e.slice(r+1,i),whenFalse:e.slice(i+1)}}return null}function Es(e,t,r){return(t===0||!nt(e.charCodeAt(t-1)))&&!nt(e.charCodeAt(t+r))}function mc(e,t){for(let r=t;r<e.length;r++){let i=e.charCodeAt(r);if(i===34||i===39||i===96){r=Tt(e,r,i)-1;continue}if(i===123)return r;if(i===59)return-1}return-1}function Os(e,t){let r=1,i=t+1;while(i<e.length&&r>0){let n=e.charCodeAt(i);if(n===34||n===39||n===96){i=Tt(e,i,n);continue}if(n===47&&e.charCodeAt(i+1)===47){i+=2;while(i<e.length&&e.charCodeAt(i)!==10&&e.charCodeAt(i)!==13)i++;continue}if(n===47&&e.charCodeAt(i+1)===42){let s=e.indexOf("*/",i+2);i=s===-1?e.length:s+2;continue}if(n===123)r++;else if(n===125)r--;i++}return i}function Tt(e,t,r){let i=t+1;while(i<e.length){let n=e.charCodeAt(i);if(n===92){i+=2;continue}if(i++,n===r)break}return i}function gc(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
|
|
10
|
+
`)||e.includes("\r"))return"string";return e}function pc(e){let t=4;while(t<e.length&&e.charCodeAt(t)<=32)t++;let r=t,i=e.charCodeAt(t);if(i<65||i>90)return"unknown";while(t<e.length&&(nt(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let n=e.slice(r,t);{let s=e.slice(t),o=s;if(s.startsWith("<")){let c=0,f=-1;for(let u=0;u<s.length;u++)if(s[u]==="<")c++;else if(s[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=s.slice(0,f+1);o=s.slice(f+1);let l=o.indexOf("(");if(l!==-1){let p=0,h=-1;for(let w=l;w<o.length;w++)if(o[w]==="(")p++;else if(o[w]===")"){if(p--,p===0){h=w;break}}if(h!==-1){if(o.slice(h+1).trimStart().startsWith("."))return"unknown"}}return`${n}${u}`}}let a=o.indexOf("(");if(a!==-1){let c=0,f=-1;for(let u=a;u<o.length;u++)if(o[u]==="(")c++;else if(o[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(o.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(n){case"Date":return"Date";case"Map":return"Map<any, any>";case"Set":return"Set<any>";case"WeakMap":return"WeakMap<any, any>";case"WeakSet":return"WeakSet<any>";case"RegExp":return"RegExp";case"Error":return"Error";case"Array":return"any[]";case"Object":return"object";case"Function":return"Function";case"Promise":return"Promise<any>";default:return n}}return"unknown"}function yc(e){let t=e.trimStart(),r=5;while(r<t.length&&t.charCodeAt(r)<=32)r++;let i=r;if(r<t.length&&nt(t.charCodeAt(r))){while(r<t.length&&nt(t.charCodeAt(r)))r++;return`typeof ${t.slice(i,r)}`}return"{ new (...args: any[]): any }"}function Ns(e,t,r=0){if(e.startsWith("Promise.resolve(")){let i=e.indexOf(")",16);if(i!==-1){let n=e.slice(16,i).trim();if(n)return`Promise<${xe(n,t,!1,r+1)}>`}return"Promise<unknown>"}if(e.startsWith("Promise.reject("))return"Promise<never>";if(e.startsWith("Promise.all(")){let i=e.indexOf("[",12),n=e.lastIndexOf("]");if(i!==-1&&n>i){let s=e.slice(i+1,n).trim(),o=Nr(s),a=[];for(let c=0;c<o.length;c++){let f=o[c].trim();if(f.startsWith("Promise.resolve(")){let u=Ns(f,t,r+1),l=u.indexOf("<"),p=u.lastIndexOf(">");a.push(l!==-1&&p>l?u.slice(l+1,p):"unknown")}else a.push(xe(f,t,!1,r+1))}return`Promise<[${a.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function Yi(e,t,r=0){let i=e.slice(1,-1).trim();if(!i)return"never[]";if(r>=20)return"unknown[]";let n=Nr(i),s=!1;for(let p=0;p<n.length;p++){let h=n[p],w=h.length;while(w>0&&h.charCodeAt(w-1)<=32)w--;if(w>=8&&h.slice(w-8,w)==="as const"){s=!0;break}}if(s){let p=[];for(let h=0;h<n.length;h++){let w=n[h].trim();if(w.endsWith("as const")){let A=w.slice(0,-8).trim();if(A.startsWith("[")&&A.endsWith("]")){let $=A.slice(1,-1).trim(),x=Nr($),S=[];for(let k=0;k<x.length;k++)S.push(xe(x[k].trim(),!0,!1,r+1));p.push(`readonly [${S.join(", ")}]`)}else p.push(xe(A,!0,!1,r+1))}else if(w.startsWith("[")&&w.endsWith("]"))p.push(Yi(w,!0,r+1));else p.push(xe(w,!0,!1,r+1))}return`readonly [
|
|
10
11
|
${p.join(` |
|
|
11
12
|
`)}
|
|
12
|
-
]`}let
|
|
13
|
-
`:""
|
|
14
|
-
${
|
|
15
|
-
${
|
|
16
|
-
${
|
|
17
|
-
${
|
|
13
|
+
]`}let o=Wr&&!t,a=[],c=[];for(let p of n){let h=p.trim(),w=Le;if(Le=null,h.startsWith("...")){let A=h.slice(3).trim(),$=xe(A,!1,!1,r+1);if($.endsWith("[]"))a.push($.slice(0,-2));else if($.startsWith("readonly [")&&$.endsWith("]"))a.push($.slice(10,-1));else if(Ui(A))a.push(`(typeof ${A})[number]`);else a.push("unknown")}else if(h.startsWith("[")&&h.endsWith("]"))a.push(Yi(h,t,r+1));else a.push(uc(h,t,r+1));if(o)c.push(Le);Le=w}if(o)if(Gi(e))Le=fr(e);else{let p=[];for(let h=0;h<n.length;h++){let w=n[h].trim();if(w.endsWith("as const"))continue;if(Ki(w)||w==="null"||w==="undefined")p.push(w);else if(w.startsWith("[")&&Gi(w))p.push(fr(w));else if(w.startsWith("{")){if(c[h])p.push(c[h])}else{let A=xe(w,!1,!1,0);if(A!=="unknown")p.push(A)}}if(p.length>0)Le=`[${p.join(", ")}]`}if(t)return`readonly [${a.join(", ")}]`;let f=new Set,u=[],l=!0;for(let p of a){if(!f.has(p))f.add(p),u.push(p);if(l){if(!(zi(p)||p==="true"||p==="false"||p.charCodeAt(0)===34&&p.charCodeAt(p.length-1)===34||p.charCodeAt(0)===39&&p.charCodeAt(p.length-1)===39))l=!1}}if(l&&a.length<=10)return`readonly [${a.join(", ")}]`;if(u.length===1)return`${u[0]}[]`;return`(${u.join(" | ")})[]`}function Nr(e){let t=[],r=0,i=0,n=!1,s=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(!n&&(c===34||c===39||c===96))n=!0,s=c;else if(n&&c===s&&(a===0||e.charCodeAt(a-1)!==92))n=!1;if(!n){if(c===91||c===123||c===40)i++;else if(c===93||c===125||c===41)i--;else if(c===44&&i===0){let f=e.substring(r,a).trim();if(f)t.push(f);r=a+1;continue}}}let o=e.substring(r).trim();if(o)t.push(o);return t}function Ki(e){if(zi(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function $c(e){return e==="number"||e==="string"||e==="boolean"}function Gi(e){let t=!1,r=0,i=e.length;for(let n=0;n<i;n++){let s=e.charCodeAt(n);if(t){if(s===92){n++;continue}if(s===r)t=!1;continue}if(s===34||s===39||s===96){t=!0,r=s;continue}if(s===61&&n+1<i&&e.charCodeAt(n+1)===62)return!1;if(s>=97&&s<=122){let o=n;while(n<i&&(e.charCodeAt(n)>=97&&e.charCodeAt(n)<=122||e.charCodeAt(n)>=65&&e.charCodeAt(n)<=90||e.charCodeAt(n)>=48&&e.charCodeAt(n)<=57||e.charCodeAt(n)===95||e.charCodeAt(n)===36))n++;let a=e.slice(o,n);if(a==="new"||a==="async"||a==="await"||a==="function"||a==="yield"||a==="console"||a==="process")return!1;let c=n;while(c<i&&e.charCodeAt(c)<=32)c++;if(c<i&&e.charCodeAt(c)===40)return!1;n--}}return!0}function wc(e,t,r=0){let i=e.slice(1,-1).trim();if(!i)return"{}";if(r>=20)return"Record<string, unknown>";let n=xc(i),s=[],o=[],a=Wr&&!t,c=[];for(let[l,p]of n){let{comments:h,key:w}=vc(l),A=h?`${h}
|
|
14
|
+
`:"",$=w,x=!1;if(w==="..."){let P=p.trim(),Z=Ui(P)?`typeof ${P}`:xe(P,t,!1,r+1);if(Z!=="unknown")o.push(Z);if(a&&(Ui(P)||P.startsWith("{")))c.push(`...${fr(P)}`);continue}let S=Le;Le=null;let k,R=p.trim();if(R===w&&hr(R))k=`typeof ${R}`;else if(kc(R)){x=!0;let P=Sc(w);if(P){$=P.name;let Z="";if(R.startsWith("async "))Z="async ";if(R.charCodeAt(Z.length)===42)Z+="*";k=ks(P.name,Z+P.typeParams+R.slice(Z.length))}else k=ks(w,R)}else if(k=xe(p,t,!1,r+1),k.includes("=>")||k.includes("function")||k.includes("async"))k=Cc(k);let b=Le;Le=S;let L=p.trim(),re=Ec(w);if(re){let P=Oc(re.kind,re.name,k);if(P){s.push(`${A}${P}`);continue}}if(!t&&$c(k)&&Ki(L))s.push(`${A}/** @defaultValue ${L} */
|
|
15
|
+
${$}: ${k}`);else s.push(`${A}${$}: ${k}`);if(a){let P=ic($);if(L.endsWith("as const"));else if(Ki(L))c.push(`${P}: ${L}`);else if(L.startsWith("[")&&Gi(L))c.push(`${P}: ${fr(L)}`);else if(L.startsWith("{")){if(b)c.push(`${P}: ${b}`)}else if(x)c.push(`${P}: ${fr(k)}`);else if(!L.startsWith("[")&&(L.includes("=>")||L.startsWith("function")||L.startsWith("async"))){let Z=Ps(L,!1,0,!0);c.push(`${P}: ${Z}`)}}}if(a&&c.length>0){let l=r>0?(r-1)/2:0,p=`{ ${c.join(", ")} }`;if(p.length<=80)Le=p;else{let h=" ".repeat((l+1)*2),w=" ".repeat(l*2);Le=`{
|
|
16
|
+
${h}${c.join(`,
|
|
17
|
+
${h}`)}
|
|
18
|
+
${w}}`}}let f=s.length>0?`{
|
|
18
19
|
${s.join(`;
|
|
19
20
|
`)}
|
|
20
|
-
}`:"{}";if(
|
|
21
|
-
`).map((f)
|
|
22
|
-
`),r=t.indexOf("async");if(r!==-1){let f=r>0?t.charCodeAt(r-1):32,u=r+5<t.length?t.charCodeAt(r+5):32;if(!
|
|
23
|
-
`),key:e.slice(r).trim()}}function
|
|
24
|
-
`))
|
|
25
|
-
`,l+2);l=y===-1?
|
|
26
|
-
`,l+2);l=y===-1?
|
|
27
|
-
`,l+2);return l=g===-1?
|
|
28
|
-
`,l+2);l=
|
|
29
|
-
`,l+2);l
|
|
30
|
-
`));continue}break}if(g.length===0)return;return g.reverse(),g}function
|
|
31
|
-
`),y=[]
|
|
32
|
-
`);let E=F-2,O=Array(y.length);for(let
|
|
33
|
-
`)}function
|
|
34
|
-
`)){let g="",y=!1;for(let
|
|
35
|
-
`)===-1&&
|
|
36
|
-
`,
|
|
37
|
-
`))
|
|
21
|
+
}`:"{}";if(o.length===0)return f;let u=o[0];for(let l=1;l<o.length;l++)u=`Omit<${u}, keyof ${o[l]}> & ${o[l]}`;return s.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function hr(e){if(!e)return!1;let t=e.charCodeAt(0);if(!(t>=65&&t<=90||t>=97&&t<=122||t===95||t===36||t>127))return!1;for(let r=1;r<e.length;r++)if(!nt(e.charCodeAt(r)))return!1;return!0}function Ui(e){let t=e.split(".");return t.length>0&&t.every(hr)}function Cc(e){let t=e.split(`
|
|
22
|
+
`).map((f)=>Ws(f)).join(`
|
|
23
|
+
`),r=t.indexOf("async");if(r!==-1){let f=r>0?t.charCodeAt(r-1):32,u=r+5<t.length?t.charCodeAt(r+5):32;if(!nt(f)&&!nt(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let i=t.indexOf("(");if(i!==-1){let f=At(t,i,"(",")");if(f!==-1){let u=t.slice(i,f+1),l=Mt(u);t=t.slice(0,i)+l+t.slice(f+1)}}let n=t.length,s="",o=[],a=!1,c=!1;for(let f=0;f<n;f++){let u=t.charCodeAt(f);if(u===123||u===40)o.push(u);else if(u===125||u===41)o.pop();if(u<=32){if(a=!0,u===10||u===13)c=!0;continue}if(a&&s.length>0){let l=(o.length>0?o[o.length-1]:0)===123;if(c&&l){let p=s.charCodeAt(s.length-1),h=p===59||p===44||p===123||u===125,w=s.length>=2&&s.charCodeAt(s.length-1)===47&&s.charCodeAt(s.length-2)===42;if(!h&&!w)s+="; ";else s+=" "}else s+=" "}a=!1,c=!1,s+=t[f]}return s.trim()}function nt(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Mt(e){let t=e.trim(),r,i=!1;if(t.startsWith("(")&&t.endsWith(")"))r=t.slice(1,-1),i=!0;else r=t;let n=r.trim();if(!n)return i?"()":"";let s=!1;{let w=0;for(let A=0;A<n.length;A++){let $=n.charCodeAt(A);if($===40||$===60||$===91||$===123)w++;else if($===41||$===62||$===93||$===125)w--;else if(w===0&&$===61){let x=A>0?n.charCodeAt(A-1):0,S=A+1<n.length?n.charCodeAt(A+1):0;if(x!==61&&x!==33&&x!==60&&x!==62&&S!==61&&S!==62){s=!0;break}}}}if(!s)return t;let o=[],a=[],c=0,f=0,u=!1,l=0;for(let w=0;w<=n.length;w++){if(w===n.length){o.push(n.slice(c));break}let A=n.charCodeAt(w);if(u){if(A===92){w++;continue}if(A===l)u=!1;continue}if(A===47&&w+1<n.length){let $=n.charCodeAt(w+1);if($===42){w+=2;while(w+1<n.length&&!(n.charCodeAt(w)===42&&n.charCodeAt(w+1)===47))w++;w++;continue}if($===47){while(w<n.length&&n.charCodeAt(w)!==10)w++;continue}}if(A===39||A===34||A===96){u=!0,l=A;continue}if(A===40||A===60||A===91||A===123)f++;else if(A===41||A===62||A===93||A===125)f--;else if(A===44&&f===0){o.push(n.slice(c,w));let $=",",x=w+1;while(x<n.length&&n.charCodeAt(x)<=32)$+=n[x],x++;a.push($),c=x}}let p=[];for(let w of o){let A=w.trim();if(!A){p.push(w);continue}if(A.startsWith("//"))continue;let $=Ws(A),x=w.slice(0,w.length-w.trimStart().length);p.push(x+bc($))}let h=p[0]||"";for(let w=1;w<p.length;w++)h+=(a[w-1]||", ")+p[w];return i?`(${h})`:h}function Ws(e){let t=!1,r=0;for(let i=0;i<e.length-1;i++){let n=e.charCodeAt(i);if(t){if(n===92){i++;continue}if(n===r)t=!1;continue}if(n===39||n===34||n===96){t=!0,r=n;continue}if(n===47&&e.charCodeAt(i+1)===47)return e.slice(0,i).trimEnd()}return e}function bc(e){if(e.startsWith("..."))return e;let t=-1,r=-1,i=0,n=!1,s=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(n){if(c===92){a++;continue}if(c===s)n=!1;continue}if(c===47&&a+1<e.length){let f=e.charCodeAt(a+1);if(f===42){a+=2;while(a+1<e.length&&!(e.charCodeAt(a)===42&&e.charCodeAt(a+1)===47))a++;a++;continue}if(f===47){while(a<e.length&&e.charCodeAt(a)!==10)a++;continue}}if(c===39||c===34||c===96){n=!0,s=c;continue}if(c===40||c===60||c===91||c===123)i++;else if(c===41||c===62||c===93||c===125)i--;else if(i===0){if(c===58&&t===-1)t=a;else if(c===61&&r===-1&&(a===0||e.charCodeAt(a-1)!==61)&&(a+1>=e.length||e.charCodeAt(a+1)!==61&&e.charCodeAt(a+1)!==62))r=a}}let o=r!==-1;if(t!==-1&&(r===-1||t<r)){let a=e.slice(0,t).trim(),c=r!==-1?e.slice(t+1,r).trim():e.slice(t+1).trim(),f=o&&!a.endsWith("?")?"?":"";return`${a}${f}: ${c}`}else if(r!==-1){let a=e.slice(0,r).trim(),c=!a.endsWith("?")?"?":"",f=e.slice(r+1).trim(),u="unknown";if(f==="true"||f==="false")u="boolean";else if(/^-?\d+(\.\d+)?$/.test(f))u="number";else if(f.startsWith("'")&&f.endsWith("'")||f.startsWith('"')&&f.endsWith('"'))u="string";else if(f.startsWith("["))u="unknown[]";else if(f.startsWith("{"))u="Record<string, unknown>";return`${a}${c}: ${u}`}return e}function Ac(e){let t=0,r=e.length;while(t<r){while(t<r&&(e.charCodeAt(t)===32||e.charCodeAt(t)===9||e.charCodeAt(t)===10||e.charCodeAt(t)===13))t++;if(t+1<r&&e.charCodeAt(t)===47&&e.charCodeAt(t+1)===42){t+=2;while(t+1<r&&!(e.charCodeAt(t)===42&&e.charCodeAt(t+1)===47))t++;t+=2;continue}break}return t}function vc(e){let t=[],r=0,i=e.length;while(r<i){while(r<i&&e.charCodeAt(r)<=32)r++;if(r+1>=i||e.charCodeAt(r)!==47||e.charCodeAt(r+1)!==42)break;let n=r;r+=2;while(r+1<i&&!(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47))r++;r=Math.min(r+2,i),t.push(e.slice(n,r).trim())}return{comments:t.join(`
|
|
24
|
+
`),key:e.slice(r).trim()}}function xc(e){let t=[],r="",i="",n=0,s=!1,o="",a=!0,c=!1,f=0,u=!1,l=!1,p=0,h=!1,w=!1;for(let A=0;A<e.length;A++){let $=e.charCodeAt(A),x=A>0?e.charCodeAt(A-1):0,S=A<e.length-1?e.charCodeAt(A+1):0;if(!s&&!c&&$===47&&S===47){A+=2;while(A<e.length&&e.charCodeAt(A)!==10)A++;continue}if(!s&&!c&&$===47&&S===42){c=!0,f=1,r+="/*",A++;continue}else if(c&&$===42&&S===47){if(f--,r+="*/",A++,f===0)c=!1;continue}else if(c&&$===47&&S===42){f++,r+="/*",A++;continue}let k=e[A];if(!s&&($===34||$===39||$===96))s=!0,o=k,r+=k;else if(s&&k===o&&x!==92)s=!1,r+=k;else if(!s&&!c)if($===40&&n===0&&a&&p===0){i=r.trim();let R=Ac(i),b=R>0?i.slice(0,R):"",L=i.slice(R),re="";if(L.startsWith("async ")||L.startsWith("async\t")||L.startsWith(`async
|
|
25
|
+
`))L=L.slice(6).trimStart(),re="async ";if(L.startsWith("*"))L=L.slice(1).trimStart(),re+="*";i=b+L,r=re+k,a=!1,h=!0,w=!1,n=1}else if($===123||$===91||$===40){if(n++,r+=k,w&&$===123)w=!1}else if($===125||$===93||$===41){if(n--,r+=k,$===41&&n===0&&!a&&!h)u=!0;if(h){if($===41&&n===0&&!w)w=!0;else if($===125&&n===0)h=!1,w=!1}}else if($===58&&n===0&&a&&p===0)i=r.trim(),r="",a=!1;else if($===58&&n===0&&u)l=!0,r+=k;else if($===60&&l)p++,r+=k;else if($===60&&a&&n===0)p++,r+=k;else if($===62&&p>0&&x!==61)p--,r+=k;else if($===61&&S===62&&l&&p===0)l=!1,u=!1,r+=k;else if($===44&&n===0&&p===0&&!w){if(i&&r.trim()){let R=r.trim();t.push([i,R])}else if(a&&r.trim()){let R=r.trim();if(hr(R))t.push([R,R]);else if(R.startsWith("...")&&R.length>3)t.push(["...",R.slice(3).trim()])}r="",i="",a=!0,u=!1,l=!1,p=0}else r+=k;else r+=k}if(i&&r.trim()){let A=r.trim();t.push([i,A])}else if(a&&r.trim()){let A=r.trim();if(hr(A))t.push([A,A]);else if(A.startsWith("...")&&A.length>3)t.push(["...",A.slice(3).trim()])}return t}function Ec(e){let t=e.trim();if(t.startsWith("get ")&&t.length>4){let r=t.slice(4).trim();if(r)return{kind:"get",name:r}}if(t.startsWith("set ")&&t.length>4){let r=t.slice(4).trim();if(r)return{kind:"set",name:r}}return null}function Oc(e,t,r){let i=r.trim();if(i.charCodeAt(0)!==40)return null;let n=At(i,0,"(",")");if(n===-1)return null;let s=i.slice(1,n).trim(),o=i.slice(n+1).trimStart();if(!o.startsWith("=>"))return null;let a=o.slice(2).trim();if(e==="get")return`get ${t}(): ${a||"unknown"}`;return`set ${t}(${s})`}function kc(e){let t=e;if(t.startsWith("async ")||t.startsWith("async\t"))t=t.slice(5).trimStart();if(t.startsWith("*"))t=t.slice(1).trimStart();if(!t.startsWith("("))return!1;let r=0;for(let i=0;i<t.length;i++){let n=t.charCodeAt(i);if(n===40)r++;else if(n===41){if(r--,r===0){let s=t.slice(i+1).trimStart();if(s.startsWith("{"))return!0;if(s.startsWith(":")){let o=Fs(s,1);if(o?.kind==="arrow")return!1;if(o?.kind==="body")return!0}return!1}}}return!1}function Sc(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let r=0,i=-1;for(let s=t.length-1;s>=0;s--){let o=t.charCodeAt(s);if(o===62){if(s>0&&t.charCodeAt(s-1)===61)continue;r++}else if(o===60){if(r--,r===0){i=s;break}}}if(i===-1)return null;let n=t.slice(0,i).trimEnd();if(!n)return null;return{name:n,typeParams:t.slice(i)}}function ks(e,t){let r=t.trimStart(),i=!1,n=!1;if(r.startsWith("async ")||r.startsWith("async\t"))i=!0,r=r.slice(5).trimStart();if(r.startsWith("*"))n=!0,r=r.slice(1).trimStart();let s="";if(r.charCodeAt(0)===60){let p=0,h=-1;for(let w=0;w<r.length;w++)if(r.charCodeAt(w)===60)p++;else if(r.charCodeAt(w)===62&&!(w>0&&r.charCodeAt(w-1)===61)){if(p--,p===0){h=w;break}}if(h!==-1)s=r.slice(0,h+1),r=r.slice(h+1).trimStart()}let o=r.indexOf("("),a=At(r,o,"(",")");if(o===-1||a===-1)return"() => unknown";let c=r.slice(o,a+1),f="unknown",u=r.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let p=u.slice(1),h=Fs(p,0);if(h)f=p.slice(0,h.index).trim();else f=p.trim()}if(f==="unknown"){if(i&&n)f="AsyncGenerator<unknown, void, unknown>";else if(n)f="Generator<unknown, void, unknown>";else if(i)f="Promise<void>"}else if(i&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let l=Mt(c);return`${s}${l} => ${f}`}function Fs(e,t){let r=0,i=0,n=0,s=0,o=!1,a=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(o){if(f===92)c++;else if(f===a)o=!1;continue}if(f===34||f===39||f===96){o=!0,a=f;continue}if(f===40)r++;else if(f===41&&r>0)r--;else if(f===91)i++;else if(f===93&&i>0)i--;else if(f===60)n++;else if(f===62&&n>0&&e.charCodeAt(c-1)!==61)n--;else if(f===125&&s>0)s--;else if(f===123){let u=r>0||i>0||n>0||s>0,l=e.slice(t,c).trimEnd(),p=l.charCodeAt(l.length-1),h=l.length===0||p===38||p===124||p===40||p===44||p===58||p===61||p===91;if(u||h)s++;else return{index:c,kind:"body"}}else if(f===61&&c+1<e.length&&e.charCodeAt(c+1)===62&&r===0&&i===0&&n===0&&s===0)return{index:c,kind:"arrow"}}return null}function At(e,t,r,i){let n=0;for(let s=t;s<e.length;s++)if(e[s]===r)n++;else if(e[s]===i){if(i===">"&&s>0&&e[s-1]==="=")continue;if(n--,n===0)return s}return-1}function Ss(e){let t=0,r=0,i=!1,n="";for(let s=0;s<e.length-1;s++){let o=e[s],a=e[s+1],c=s>0?e[s-1]:"";if(!i&&(o==='"'||o==="'"||o==="`"))i=!0,n=o;else if(i&&o===n&&c!=="\\")i=!1;if(!i){if(o==="(")t++;else if(o===")")t--;else if(o==="[")r++;else if(o==="]")r--;if(o==="="&&a===">"&&t===0&&r===0)return s}}return-1}function Ps(e,t=!1,r=0,i=!0){let n=e.trim();if(n.length>200&&Vi(n,"=>")>2&&Vi(n,"<")>5&&!n.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(n.startsWith("async ")&&n.includes("=>")){let o=n.slice(5).trim(),a=Ss(o);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=o.substring(0,a).trim(),f=o.substring(a+2).trim(),u=Ts(c),l=u.params,p=u.returnType;if(l=Mt(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let h=p;if(h);else if(f.startsWith("{"))h=ur(f.slice(1,f.endsWith("}")?-1:void 0),!0,l);else h=xe(f,i,!1,r+1);let w=`${l} => ${p||h.startsWith("Promise<")?h:`Promise<${h}>`}`;return t?`(${w})`:w}if(n.includes("=>")){let o="",a=n;if(n.startsWith("<")){let $=At(n,0,"<",">");if($!==-1)o=n.substring(0,$+1),a=n.substring($+1).trim()}let c=Ss(a);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,c).trim(),u=a.substring(c+2).trim(),l=Ts(f),p=l.params,h=l.returnType;if(p=Mt(p),p==="()"||p==="")p="()";else if(!p.startsWith("("))p=`(${p})`;let w="unknown";if(h)w=h;else if(u.startsWith("{"))w=ur(u.slice(1,u.endsWith("}")?-1:void 0),!1,p);else if(u.includes("=>")){let $=u.trimStart(),x=$.indexOf("("),S=x!==-1?At($,x,"(",")"):-1,k=S!==-1?$.indexOf("=>",S):-1;if(x===0&&S!==-1&&k!==-1){let R=$.substring(x+1,S).trim(),b=Mt(R);if(o.includes("T")&&b.includes("T"))w=`(${b}) => T`;else w=`(${b}) => any`}else w="any"}else if(t)w="unknown";else w=St(u,Rs(p));let A=`${o}${p} => ${w}`;return t?`(${A})`:A}if(n.startsWith("function")){let o=8,a=n.length;while(o<a&&n.charCodeAt(o)<=32)o++;let c=!1;if(o<a&&n.charCodeAt(o)===42){c=!0,o++;while(o<a&&n.charCodeAt(o)<=32)o++}let f="";if(o<a&&n.charCodeAt(o)===60){let p=o,h=1;o++;while(o<a&&h>0){let w=n.charCodeAt(o);if(w===60)h++;else if(w===62&&n.charCodeAt(o-1)!==61)h--;o++}f=n.substring(p,o);while(o<a&&n.charCodeAt(o)<=32)o++}let u=n.indexOf("(",o);if(u!==-1){let p=1,h=u+1;while(h<a&&p>0){let x=n.charCodeAt(h);if(x===40)p++;else if(x===41)p--;h++}let w=n.substring(u+1,h-1).trim(),A=w?`(${w})`:"()";if(c){let x=n.substring(h).trim(),S=x.indexOf("Generator<");if(S!==-1){let R=S+10,b=x.indexOf(">",R);if(b!==-1){let L=x.substring(R,b),re=`${f}${A} => Generator<${L}>`;return t?`(${re})`:re}}let k=`${f}${A} => Generator<any, any, any>`;return t?`(${k})`:k}let $=`${f}${A} => unknown`;return t?`(${$})`:$}let l="(...args: any[]) => unknown";return t?`(${l})`:l}if(n.includes("=>")&&n.includes("(")&&n.includes(")")){if(n.length>100||Vi(n,"=>")>2){let o="";if(n.charCodeAt(0)===60){let l=At(n,0,"<",">");if(l!==-1)o=n.substring(0,l+1)}let a=n.indexOf("("),c=a!==-1?At(n,a,"(",")"):-1,f=a!==-1&&c!==-1?n.substring(a,c+1):"(...args: any[])";f=Mt(f);let u=`${o}${f} => any`;return t?`(${u})`:u}return t?`(${n})`:n}let s="() => unknown";return t?`(${s})`:s}function Ts(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=At(t,0,"(",")");if(r===-1)return{params:t,returnType:""};let i=t.slice(r+1).trim();return{params:t.slice(0,r+1),returnType:i.startsWith(":")?i.slice(1).trim():""}}function Ds(e){let t=e.trim();if(t==="any"||t==="object"||t==="unknown")return!0;if(t.startsWith("Record<")&&t.endsWith(">"))return!0;if(t.startsWith("Array<")&&t.endsWith(">"))return!0;if(/^\{\s*\[[^\]]*\]:\s*(any|string|number|unknown)\s*\}$/.test(t))return!0;return!1}function Ms(e){let t=e.lastIndexOf(" satisfies ");if(t===-1)return null;let r=e.slice(t+11).trim();if(r.endsWith(";"))r=r.slice(0,-1).trim();return r||null}var Wr=!1,Le=null;var Xi=()=>{};function ke(e){return e===We||e===Fe||e===ye||e===be}function It(e){return e>=65&&e<=90||e>=97&&e<=122||e===Rc||e===Ls||e>127}function Je(e){return It(e)||e>=48&&e<=57}function Nc(e){let t=!0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i===at){if(t)return!1;t=!0}else if(t){if(!It(i))return!1;t=!1}else if(!Je(i))return!1}return e.length>0&&!t}function Dr(e,t,r){let i=t+1;while(i<e.length){let n=e.charCodeAt(i);if(n===Ue){i+=2;continue}if(i++,n===r)break}return i}function Wc(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===j&&e.includes("[")&&e.includes("]:")}function js(e,t,r=!0){return Zs(e,t,r,!0)}function _s(e,t,r=!0){return Zs(e,t,r,!1)}function Zs(e,t,r,i){let n=e,s=r,o=i,a=n.length,c=[],f=new Map,u=new Set,l=0;if(l<a&&n.charCodeAt(l)===65279)l++;function p(m,d){if(m<d){let g=n.charCodeAt(m),y=n.charCodeAt(d-1);if(g!==We&&g!==Fe&&g!==ye&&g!==be&&y!==We&&y!==Fe&&y!==ye&&y!==be)return n.slice(m,d)}while(m<d&&ke(n.charCodeAt(m)))m++;while(d>m&&ke(n.charCodeAt(d-1)))d--;return n.slice(m,d)}function h(){if(l>=a)return;let m=n.charCodeAt(l);if(m!==We&&m!==Fe&&m!==ye&&m!==be&&m!==z)return;while(l<a){let d=n.charCodeAt(l);if(d===We||d===Fe||d===ye||d===be){l++;continue}if(d===z&&l+1<a){let g=n.charCodeAt(l+1);if(g===z){let y=n.indexOf(`
|
|
26
|
+
`,l+2);l=y===-1?a:y+1;continue}if(g===Oe){let y=n.indexOf("*/",l+2);l=y===-1?a:y+2;continue}}break}}function w(m){let d=m.length,g=0,y=d;for(let C=0;C<d;C++){let v=m.charCodeAt(C);if(g){if(v===Ue){C++;continue}if(v===g)g=0;continue}if(v===fe||v===de||v===De){g=v;continue}if(v===z&&C+1<d){let T=m.charCodeAt(C+1);if(T===z){y=C;while(y>0&&(m.charCodeAt(y-1)===We||m.charCodeAt(y-1)===Fe))y--;return m.slice(0,y)}if(T===Oe){let F=m.indexOf("*/",C+2);if(F!==-1){m=`${m.slice(0,C)} ${m.slice(F+2)}`,C--;continue}}}}y=d;while(y>0&&(m.charCodeAt(y-1)===We||m.charCodeAt(y-1)===Fe||m.charCodeAt(y-1)===be))y--;return y<d?m.slice(0,y):m}function A(m){l++;let d=m===fe?"'":'"';while(l<a){let g=n.indexOf(d,l);if(g===-1){l=a;return}let y=0,C=g-1;while(C>=0&&n.charCodeAt(C)===Ue)y++,C--;if(y%2===0){l=g+1;return}l=g+1}}function $(){l++;let m=[];while(l<a){let d=n.charCodeAt(l);if(m.length===0){if(d===Ue){l+=2;continue}if(d===De){l++;return}if(d===Ls&&l+1<a&&n.charCodeAt(l+1)===j){l+=2,m.push(0);continue}l++;continue}if(d===fe||d===de){A(d);continue}if(d===De){$();continue}if(d===z&&l+1<a){let g=n.charCodeAt(l+1);if(g===z){let y=n.indexOf(`
|
|
27
|
+
`,l+2);l=y===-1?a:y+1;continue}if(g===Oe){let y=n.indexOf("*/",l+2);l=y===-1?a:y+2;continue}if(S()){k();continue}l++;continue}if(d===j){m[m.length-1]++,l++;continue}if(d===K){let g=m[m.length-1];if(g===0){m.pop(),l++;continue}m[m.length-1]=g-1,l++;continue}l++}}function x(){let m=n.charCodeAt(l);if(m===fe||m===de)return A(m),!0;if(m===De)return $(),!0;if(m===z&&l+1<a){let d=n.charCodeAt(l+1);if(d===z){let g=n.indexOf(`
|
|
28
|
+
`,l+2);return l=g===-1?a:g+1,!0}if(d===Oe){let g=n.indexOf("*/",l+2);return l=g===-1?a:g+2,!0}if(S())return k(),!0}return!1}function S(){let m=l-1;while(m>=0&&(n.charCodeAt(m)===We||n.charCodeAt(m)===Fe||n.charCodeAt(m)===ye||n.charCodeAt(m)===be))m--;if(m<0)return!0;let d=n.charCodeAt(m);if(d===we||d===X||d===ce||d===33||d===38||d===124||d===Fr||d===Ke||d===Ge||d===U||d===j||d===K||d===94||d===126||d===43||d===45||d===Oe||d===37||d===pe||d===he)return!0;if(Je(d)){let g=m;while(g>=0&&Je(n.charCodeAt(g)))g--;let y=n.slice(g+1,m+1);if(y==="return"||y==="typeof"||y==="void"||y==="delete"||y==="throw"||y==="new"||y==="in"||y==="of"||y==="case"||y==="instanceof"||y==="yield"||y==="await")return!0}return!1}function k(){l++;let m=!1;while(l<a){let d=n.charCodeAt(l);if(d===Ue){l+=2;continue}if(m){if(d===Ee)m=!1;l++;continue}if(d===ce){m=!0,l++;continue}if(d===z){l++;break}if(d===ye||d===be)break;l++}while(l<a&&Je(n.charCodeAt(l)))l++}function R(){let m=l;while(l<a&&Je(n.charCodeAt(l)))l++;return n.slice(m,l)}function b(m){if(l+m.length>a)return!1;for(let d=0;d<m.length;d++)if(n.charCodeAt(l+d)!==m.charCodeAt(d))return!1;if(l+m.length<a&&Je(n.charCodeAt(l+m.length)))return!1;return!0}function L(m){let d=l+m;while(d<a){let g=n.charCodeAt(d);if(g===We||g===Fe||g===ye||g===be){d++;continue}return g!==at&&g!==we}return!1}function re(){if(l>=a)return!1;switch(n.charCodeAt(l)){case 101:return b("export")||b("enum");case 105:return b("import")||b("interface");case 102:return b("function");case 99:return b("class")||b("const");case 116:return b("type");case 108:return b("let");case 118:return b("var");case 100:return b("declare")||b("default");case 109:return b("module");case 110:return b("namespace");case 97:return b("abstract")||b("async");default:return!1}}function P(){let m=n.charCodeAt(l);if(m!==ye&&m!==be)return!1;let d=l;if(l++,m===be&&l<a&&n.charCodeAt(l)===ye)l++;while(l<a){let y=n.charCodeAt(l);if(y===We||y===Fe||y===be||y===ye){l++;continue}if(y===z&&l+1<a){let C=n.charCodeAt(l+1);if(C===z){let v=n.indexOf(`
|
|
29
|
+
`,l+2);l=v===-1?a:v+1;continue}if(C===Oe){let v=n.indexOf("*/",l+2);l=v===-1?a:v+2;continue}}break}let g=l>=a||re()||n.charCodeAt(l)===K;return l=d,g}function Z(){let m=n.charCodeAt(l);if(m!==ye&&m!==be)return!1;let d=l;if(l++,m===be&&l<a&&n.charCodeAt(l)===ye)l++;while(l<a){let y=n.charCodeAt(l);if(y===We||y===Fe||y===be||y===ye){l++;continue}if(y===z&&l+1<a&&n.charCodeAt(l+1)===z){let C=n.indexOf(`
|
|
30
|
+
`,l+2);l=C===-1?a:C+1;continue}break}if(l>=a)return l=d,!0;let g=n.charCodeAt(l);if(g===124||g===38||g===at||g===Fr||g===Ke)return l=d,!1;if(b("extends")||b("keyof")||b("typeof")||b("infer")||b("is")||b("as")||b("in"))return l=d,!1;return l=d,!0}let q=/[{}'"`\/]/g,ne=/[()'"`\/]/g,V=/[[\]'"`\/]/g,H=/[<>'"`\/]/g;function G(m,d){let g=1;l++;let y=m===j?q:m===X?ne:m===ce?V:H;y.lastIndex=l;let C;while((C=y.exec(n))!==null){let v=C.index,T=n.charCodeAt(v);if(T===fe||T===de){l=v,A(T),y.lastIndex=l;continue}if(T===De){l=v,$(),y.lastIndex=l;continue}if(T===z){if(l=v,x()){y.lastIndex=l;continue}y.lastIndex=v+1;continue}if(T===m)g++;else if(T===d){if(d===he&&v>0&&n.charCodeAt(v-1)===we){y.lastIndex=v+1;continue}if(g--,g===0)return l=v+1,l}y.lastIndex=v+1}return l=a,l}function Y(){return l>0&&n.charCodeAt(l-1)===we}function Ce(){return l+1<a&&n.charCodeAt(l+1)===he}let Q=/[{};'"`\/\n\r()[\]]/g;function ie(){let m=0,d=0,g=0;Q.lastIndex=l;let y;while((y=Q.exec(n))!==null){let C=y.index,v=n.charCodeAt(C);if(v===fe||v===de){l=C,A(v),Q.lastIndex=l;continue}if(v===De){l=C,$(),Q.lastIndex=l;continue}if(v===z){if(l=C,x()){Q.lastIndex=l;continue}Q.lastIndex=C+1;continue}if(v===X){d++,Q.lastIndex=C+1;continue}if(v===ge){d--,Q.lastIndex=C+1;continue}if(v===ce){g++,Q.lastIndex=C+1;continue}if(v===Ee){g--,Q.lastIndex=C+1;continue}if(v===j){m++,Q.lastIndex=C+1;continue}if(v===K){if(m--,m<=0&&d<=0&&g<=0){l=C+1;return}Q.lastIndex=C+1;continue}if(v===U&&m===0&&d===0&&g===0){l=C+1;return}if((v===ye||v===be)&&m===0&&d===0&&g===0){if(l=C,P())return}Q.lastIndex=C+1}l=a}function sr(){G(j,K);while(l<a&&ke(n.charCodeAt(l)))l++;if(b("from")){l+=4;while(l<a&&ke(n.charCodeAt(l)))l++;if(l<a){let m=n.charCodeAt(l);if(m===fe||m===de)A(m)}}while(l<a&&(n.charCodeAt(l)===We||n.charCodeAt(l)===Fe))l++;if(l<a&&n.charCodeAt(l)===U)l++}function kt(){l++;while(l<a&&ke(n.charCodeAt(l)))l++;if(b("as")){l+=2;while(l<a&&ke(n.charCodeAt(l)))l++;R();while(l<a&&ke(n.charCodeAt(l)))l++}if(b("from")){l+=4;while(l<a&&ke(n.charCodeAt(l)))l++;if(l<a){let m=n.charCodeAt(l);if(m===fe||m===de)A(m)}}while(l<a&&(n.charCodeAt(l)===We||n.charCodeAt(l)===Fe))l++;if(l<a&&n.charCodeAt(l)===U)l++}function rt(m){let d=m.indexOf("from ");if(d===-1)return;let g=d+5;while(g<m.length&&(m.charCodeAt(g)===32||m.charCodeAt(g)===9))g++;if(g>=m.length)return;let y=m.charCodeAt(g);if(y!==39&&y!==34)return;let C=m.indexOf(m[g],g+1);if(C===-1)return;return m.slice(g+1,C)}function le(m){if(!s)return;let d=m-1;while(d>=0&&ke(n.charCodeAt(d)))d--;if(d<0)return;let g=[],y=!1;while(d>=0){if(d>=1&&n.charCodeAt(d)===z&&n.charCodeAt(d-1)===Oe){let T=n.lastIndexOf("/*",d-2);if(T>=0){g.push(n.slice(T,d+1)),y=!0,d=T-1;while(d>=0&&ke(n.charCodeAt(d)))d--;continue}break}let C=d;while(C>0&&n.charCodeAt(C-1)!==ye)C--;let v=p(C,d+1);if(v.startsWith("//")){if(y)break;let T=[v];d=C-1;while(d>=0&&(n.charCodeAt(d)===ye||n.charCodeAt(d)===be))d--;while(d>=0){let F=d;while(F>0&&n.charCodeAt(F-1)!==ye)F--;let E=p(F,d+1);if(E.startsWith("//")){T.push(E),d=F-1;while(d>=0&&(n.charCodeAt(d)===ye||n.charCodeAt(d)===be))d--}else if(E===""){d=F-1;while(d>=0&&(n.charCodeAt(d)===ye||n.charCodeAt(d)===be))d--}else break}T.reverse(),g.push(T.join(`
|
|
31
|
+
`));continue}break}if(g.length===0)return;return g.reverse(),g}function st(m){let d=m,g=!1;while(l<a){let E=n.charCodeAt(l);if(E===U){l++;break}if(E===fe||E===de){A(E),g=!0;while(l<a&&(n.charCodeAt(l)===We||n.charCodeAt(l)===Fe))l++;if(l<a&&n.charCodeAt(l)===U)l++;break}if(E===ye&&g)break;l++}let y=p(d,l),C=y.charCodeAt(7)===116&&(y.startsWith("import type ")||y.startsWith("import type{")),v=!1;{let E=6;while(E<y.length&&(y.charCodeAt(E)===We||y.charCodeAt(E)===Fe))E++;if(E<y.length&&y.charCodeAt(E)===116&&y.startsWith("type",E)){E+=4;while(E<y.length&&(y.charCodeAt(E)===We||y.charCodeAt(E)===Fe))E++}if(E<y.length){let O=y.charCodeAt(E);v=O===fe||O===de}}let T="";{let E=y.indexOf("from ");if(E!==-1){let O=E+5;while(O<y.length&&(y.charCodeAt(O)===We||y.charCodeAt(O)===Fe))O++;if(O<y.length){let N=y.charCodeAt(O);if(N===fe||N===de){let D=y.indexOf(String.fromCharCode(N),O+1);if(D!==-1)T=y.slice(O+1,D)}}}else if(v){let O=6;while(O<y.length&&y.charCodeAt(O)!==fe&&y.charCodeAt(O)!==de)O++;if(O<y.length){let N=y.charCodeAt(O),D=y.indexOf(String.fromCharCode(N),O+1);if(D!==-1)T=y.slice(O+1,D)}}}let F=le(d);return{kind:"import",name:"",text:y,isExported:!1,isTypeOnly:C,isSideEffect:v,source:T,leadingComments:F,start:d,end:l}}function yt(){let m=l;return G(j,K),n.slice(m,l)}function or(m){let d=m.indexOf("(");if(d===-1)return m;let g=m.slice(d);if(g.indexOf("=")===-1)return m;let y=!1;for(let E=0;E<g.length;E++)if(g.charCodeAt(E)===61){let O=E>0?g.charCodeAt(E-1):0,N=E+1<g.length?g.charCodeAt(E+1):0;if(O!==61&&O!==33&&O!==60&&O!==62&&N!==61&&N!==62){y=!0;break}}if(!y)return m;let C=0,v=-1;for(let E=d;E<m.length;E++){let O=m.charCodeAt(E);if(O===40)C++;else if(O===41){if(C--,C===0){v=E;break}}}if(v===-1)return m;let T=m.slice(d,v+1),F=Wt(T);return m.slice(0,d)+F+m.slice(v+1)}function is(m){let d=m.indexOf("//")!==-1||m.indexOf("/*")!==-1,g=m.split(`
|
|
32
|
+
`),y=[],C=[],v=[],T=!1,F=1/0;for(let N=0;N<g.length;N++){let D=g[N];if(d){if(T){if(D.includes("*/"))T=!1;continue}let B=D.trim();if(B.length===0)continue;let I=B.charCodeAt(0);if(I===z){let ve=B.charCodeAt(1);if(ve===z)continue;if(ve===Oe){if(!B.includes("*/"))T=!0;continue}}if(I===Oe)continue;let W=w(D);if(W.charCodeAt(W.length-1)===U)W=W.slice(0,-1);W=or(W);let M=W.trim();if(!M)continue;y.push(W),C.push(M);let _=0;while(_<W.length&&ke(W.charCodeAt(_)))_++;if(M!=="{"&&M!=="}"){if(_<F)F=_}v.push(_)}else{let B=D.length;while(B>0&&(D.charCodeAt(B-1)===We||D.charCodeAt(B-1)===Fe||D.charCodeAt(B-1)===be))B--;if(B===0)continue;let I=B<D.length?D.slice(0,B):D;if(I.charCodeAt(I.length-1)===U)I=I.slice(0,-1);I=or(I);let W=I.trim();if(!W)continue;y.push(I),C.push(W);let M=0;while(M<I.length&&ke(I.charCodeAt(M)))M++;if(W!=="{"&&W!=="}"){if(M<F)F=M}v.push(M)}}if(y.length===0)return"{}";if(F===1/0||F<=2)return y.join(`
|
|
33
|
+
`);let E=F-2,O=Array(y.length);for(let N=0;N<y.length;N++){let D=C[N];if(D==="{"){O[N]=D;continue}let B=v[N];if(B>F)O[N]=y[N];else if(B===F&&(D.charCodeAt(0)===K||D.charCodeAt(0)===Ee||D.charCodeAt(0)===ge))O[N]=y[N];else{let I=Math.max(0,B-E);O[N]=" ".repeat(I)+D}}return O.join(`
|
|
34
|
+
`)}function it(){if(l>=a||n.charCodeAt(l)!==pe)return"";let m=l;G(pe,he);let d=n.slice(m,l);if(d.includes(`
|
|
35
|
+
`)){let g="",y=!1;for(let C=0;C<d.length;C++){let v=d.charCodeAt(C);if(v===32||v===9||v===10||v===13){if(!y&&g.length>0)g+=" ",y=!0}else g+=d[C],y=!1}if(g.charCodeAt(1)===32)g=`<${g.slice(2)}`;if(g.charCodeAt(g.length-2)===32)g=`${g.slice(0,-2)}>`;return g}return d}function $t(){if(l>=a||n.charCodeAt(l)!==X)return"()";let m=l;return G(X,ge),n.slice(m,l)}function Wt(m){let d=m.slice(1,-1).trim();if(!d)return"()";if(m.indexOf(`
|
|
36
|
+
`)===-1&&d.indexOf(":")!==-1&&d.indexOf("{")===-1&&d.indexOf("[")===-1&&d.indexOf("=")===-1&&d.indexOf("@")===-1&&d.indexOf("...")===-1){let E=0,O=0,N=0;for(let D=0;D<d.length;D++){let B=d.charCodeAt(D);if(B===X||B===pe||B===j)N++;else if(B===ge||B===he||B===K)N--;else if(N===0){if(B===Ke)E++;else if(B===Ge)O++}}if(E>=O+1){let D=!1;for(let B=0;B<Qi.length;B++){let I=Qi[B],W=d.indexOf(I);if(W!==-1){let M=W+I.length;if((W===0||!Je(d.charCodeAt(W-1)))&&(M>=d.length||!Je(d.charCodeAt(M)))){D=!0;break}}}if(!D)return m}}let g=[],y=0,C=0,v=!1,T=0;for(let E=0;E<=d.length;E++){if(E===d.length){g.push(d.slice(y).trim());break}let O=d.charCodeAt(E);if(v){if(O===Ue){E++;continue}if(O===T)v=!1;continue}if(O===z&&E+1<d.length){let N=d.charCodeAt(E+1);if(N===Oe){E+=2;while(E+1<d.length&&!(d.charCodeAt(E)===Oe&&d.charCodeAt(E+1)===z))E++;E++;continue}if(N===z){while(E<d.length&&d.charCodeAt(E)!==10)E++;continue}}if(O===fe||O===de||O===De){v=!0,T=O;continue}if(O===X||O===j||O===ce||O===pe)C++;else if(O===ge||O===K||O===Ee||O===he&&!(E>0&&d.charCodeAt(E-1)===we))C--;else if(O===Ge&&C===0)g.push(d.slice(y,E).trim()),y=E+1}let F=[];for(let E of g){if(!E)continue;let O=E.trim();if(O.startsWith("//")||O.startsWith("/*"))continue;let N=E;{let D=!1,B=0,I=0,W=0;for(let M=0;M<N.length-1;M++){let _=N.charCodeAt(M);if(_===ye){W=M+1;continue}if(D){if(_===Ue){M++;continue}if(_===B)D=!1;continue}if(_===fe||_===de||_===De){D=!0,B=_;continue}if(_===j||_===ce||_===X||_===pe){I++;continue}if(_===K||_===Ee||_===ge||_===he){if(I>0)I--;continue}if(_===z&&N.charCodeAt(M+1)===z){if(I===0){N=N.slice(0,M).trimEnd();break}let ve=N.indexOf(`
|
|
37
|
+
`,M);if(ve===-1){N=N.slice(0,W).trimEnd();break}let bt=N.slice(0,W),Bl=N.slice(ve+1);N=`${bt}${Bl}`,M=W-1}}}if(!N.trim())continue;F.push(ns(N))}return`(${F.join(", ")})`}function Nl(m){if(!m.startsWith("{")&&!m.startsWith("["))return m;let d="",g=0,y=0,C=!1,v=0;while(g<m.length){let T=m.charCodeAt(g);if(C){if(T===Ue&&g+1<m.length){d+=m[g]+m[g+1],g+=2;continue}if(T===v)C=!1;d+=m[g],g++;continue}if(T===z&&g+1<m.length){let F=m.charCodeAt(g+1);if(F===Oe){let E=g;g+=2;while(g+1<m.length&&!(m.charCodeAt(g)===Oe&&m.charCodeAt(g+1)===z))g++;g=Math.min(g+2,m.length),d+=m.slice(E,g);continue}if(F===z){let E=g;while(g<m.length&&m.charCodeAt(g)!==10)g++;d+=m.slice(E,g);continue}}if(T===fe||T===de||T===De){C=!0,v=T,d+=m[g],g++;continue}if(T===j||T===ce||T===X)y++;else if(T===K||T===Ee||T===ge)y--;if(y>=1&&T===we&&(g+1>=m.length||m.charCodeAt(g+1)!==we&&m.charCodeAt(g+1)!==he)){while(d.length>0&&(d[d.length-1]===" "||d[d.length-1]==="\t"||d[d.length-1]===`
|
|
38
|
+
`))d=d.slice(0,-1);g++;let F=0;while(g<m.length){let E=m.charCodeAt(g);if(E===fe||E===de||E===De){let O=E;g++;while(g<m.length){if(m.charCodeAt(g)===Ue){g+=2;continue}if(m.charCodeAt(g)===O){g++;break}g++}continue}if(E===j||E===ce||E===X)F++;else if(E===K||E===Ee||E===ge){if(F===0)break;F--}else if(E===Ge&&F===0)break;g++}continue}if(y===1&&T===at&&g+2<m.length&&m.charCodeAt(g+1)===at&&m.charCodeAt(g+2)===at){g+=3;continue}d+=m[g],g++}return d}function ns(m){let d=m.trim(),g=d.startsWith("...");if(g)d=d.slice(3).trim();while(d.startsWith("@")){let W=1;while(W<d.length&&Je(d.charCodeAt(W)))W++;if(W<d.length&&d.charCodeAt(W)===X){let M=1;W++;while(W<d.length&&M>0){if(d.charCodeAt(W)===X)M++;else if(d.charCodeAt(W)===ge)M--;W++}}d=d.slice(W).trim()}let y=!0;while(y){y=!1;for(let W of Qi)if(d.startsWith(W)&&d.length>W.length&&!Je(d.charCodeAt(W.length))){let M=d.slice(W.length).trim();if(M.charCodeAt(0)===Ke||M.charCodeAt(0)===Fr&&M.length>1&&M.charCodeAt(1)===Ke)break;d=M,y=!0;break}}let C=-1,v=-1,T=0,F=!1,E=0;for(let W=0;W<d.length;W++){let M=d.charCodeAt(W);if(F){if(M===Ue){W++;continue}if(M===E)F=!1;continue}if(M===z&&W+1<d.length){let _=d.charCodeAt(W+1);if(_===Oe){W+=2;while(W+1<d.length&&!(d.charCodeAt(W)===Oe&&d.charCodeAt(W+1)===z))W++;W++;continue}if(_===z){while(W<d.length&&d.charCodeAt(W)!==10)W++;continue}}if(M===fe||M===de||M===De){F=!0,E=M;continue}if(M===X||M===j||M===ce||M===pe)T++;else if(M===ge||M===K||M===Ee||M===he&&!(W>0&&d.charCodeAt(W-1)===we))T--;else if(T===0){if(M===Ke&&C===-1)C=W;else if(M===we&&v===-1&&(W===0||d.charCodeAt(W-1)!==we)&&(W+1>=d.length||d.charCodeAt(W+1)!==we&&d.charCodeAt(W+1)!==he))v=W}}let O,N,D=v!==-1;if(C!==-1&&(v===-1||C<v))if(O=d.slice(0,C).trim(),v!==-1)N=d.slice(C+1,v).trim();else N=d.slice(C+1).trim();else if(v!==-1)O=d.slice(0,v).trim(),N=Si(d.slice(v+1).trim());else O=d,N="unknown";if(O=Nl(O),(O.startsWith("{")||O.startsWith("["))&&O.includes(`
|
|
38
39
|
`)){let W=O.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(W.length<=40)O=W;else O=O.split(`
|
|
39
|
-
`).map((
|
|
40
|
-
`)}let
|
|
40
|
+
`).map((M)=>{let _=M.trim();if(!_)return"";if(_==="{"||_==="}"||_==="["||_==="]"||_.startsWith("}")||_.startsWith("]"))return _;return` ${_}`}).join(`
|
|
41
|
+
`)}let B=O.endsWith("?")||D;if(O.endsWith("?"))O=O.slice(0,-1).trim();let I=B&&!g?"?":"";if(g)return`...${O}: ${N}`;return`${O}${I}: ${N}`}function ss(m){let d=0;if(d<m.length&&m.charCodeAt(d)===45)d++;if(d>=m.length)return!1;let g=m.charCodeAt(d);if(g<48||g>57)return!1;while(d<m.length&&m.charCodeAt(d)>=48&&m.charCodeAt(d)<=57)d++;if(d<m.length&&m.charCodeAt(d)===46){if(d++,d>=m.length||m.charCodeAt(d)<48||m.charCodeAt(d)>57)return!1;while(d<m.length&&m.charCodeAt(d)>=48&&m.charCodeAt(d)<=57)d++}return d===m.length}function Si(m){let d=m.trim();if(d==="true"||d==="false")return"boolean";if(ss(d))return"number";if(d.startsWith("'")&&d.endsWith("'")||d.startsWith('"')&&d.endsWith('"'))return"string";if(d.startsWith("["))return"unknown[]";if(d.startsWith("{"))return"Record<string, unknown>";return"unknown"}function Ti(m){let d=m.trim();if(d.endsWith("as const"))d=d.slice(0,-8).trim();if(d==="true"||d==="false")return d;if(ss(d))return d;let g=Wl(d);if(g!==null)return g;return"unknown"}function Wl(m){if(m==="")return null;if(m.charCodeAt(0)===fe||m.charCodeAt(0)===de){if(Dr(m,0,m.charCodeAt(0))===m.length)return m}let d=Fl(m,"+");if(d.length>1){let g=!1,y=!0,C=[];for(let v of d){let T=v.trim(),F=T.charCodeAt(0);if((F===fe||F===de)&&Dr(T,0,F)===T.length)g=!0,C.push(Pl(T));else y=!1}if(y)return Dl(C.join(""));if(g)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(m)&&/\d/.test(m)&&/[+*/%\-\s]/.test(m))return"number";return null}function Fl(m,d){let g=[],y=0,C="",v=0;while(v<m.length){let T=m.charCodeAt(v);if(T===fe||T===de||T===De){let F=Dr(m,v,T);C+=m.slice(v,F),v=F;continue}if(T===z&&(m.charCodeAt(v+1)===z||m.charCodeAt(v+1)===42)){if(m.charCodeAt(v+1)===z){let O=m.indexOf(`
|
|
42
|
+
`,v+2),N=O===-1?m.length:O;C+=m.slice(v,N),v=N;continue}let F=m.indexOf("*/",v+2),E=F===-1?m.length:F+2;C+=m.slice(v,E),v=E;continue}if(T===X||T===ce||T===j)y++;else if(T===ge||T===Ee||T===K)y--;if(m[v]===d&&y===0){g.push(C),C="",v++;continue}C+=m[v],v++}return g.push(C),g}function Pl(m){return m.slice(1,-1).replace(/\\(.)/g,(d,g)=>{if(g==="n")return`
|
|
43
|
+
`;if(g==="t")return"\t";if(g==="r")return"\r";if(g==="0")return"\x00";return g})}function Dl(m){return`'${m.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Ri(m){if(m.endsWith("as const"))return null;let d=0,g=-1;for(let y=0;y<m.length;y++){let C=m.charCodeAt(y);if(C===fe||C===de||C===De)y=Dr(m,y,C)-1;else if(C===123||C===91||C===40)d++;else if(C===125||C===93||C===41)d--;else if(d===0&&C===32&&y+4<=m.length&&m.substring(y,y+4)===" as ")g=y}if(g===-1)return null;return m.slice(g+4).trim()||null}function ar(){if(h(),l<a&&n.charCodeAt(l)===Ke){l++,h();let m=l,d=0;while(l<a){if(x())continue;let g=n.charCodeAt(l);if(g===X||g===ce||g===pe)d++;else if(g===ge||g===Ee||g===he&&!Y())d--;else if(g===j)if(d>0)d++;else{let y=p(m,l),C=(v)=>{let T=y.length-v.length;return T>=0&&y.endsWith(v)&&(T===0||!Je(y.charCodeAt(T-1)))};if(y.length===0||y.endsWith("|")||y.endsWith("&")||C("is")||C("extends"))d++;else break}else if(g===K){if(d===0)break;d--}else if(d===0&&g===U)break;if(d===0&&Z())break;l++}return p(m,l)}return""}function wt(m,d,g,y){l+=8,h();let C=l<a&&n.charCodeAt(l)===Oe;if(C)l++,h();let v=R();if(!v&&!y)return null;h();let T=it();h();let F=$t();h();let E=ar(),O=E.length>0;if(!E)if(g&&C)E="AsyncGenerator<unknown, void, unknown>";else if(C)E="Generator<unknown, void, unknown>";else if(g)E="Promise<void>";else E="void";h();let N=!1;if(l<a&&n.charCodeAt(l)===j){N=!0;let W=l+1;if(G(j,K),!o&&!O&&!C)E=ur(n.slice(W,l-1),g,F)}else if(l<a&&n.charCodeAt(l)===U)l++;let D=Wt(F),B=`${d?y?"export default function ":"export declare function ":"declare function "}${v||"default"}${T}${D}: ${E};`,I=le(m);if(N)u.add(c.length);return{kind:"function",name:v||"default",text:B,isExported:d,isDefault:y,isAsync:g,isGenerator:C,returnType:E,generics:T||void 0,leadingComments:I,start:m,end:l}}function Ft(m,d,g){l+=d.length,h();let y=[];do{if(h(),l>=a)break;let C=n.charCodeAt(l);if(C===j||C===ce)return ie(),y;let v=R();if(!v)return ie(),y;h();let T,F,E=!1;if(l<a&&n.charCodeAt(l)===Ke){l++,h();let D=l,B=0;while(l<a){if(x())continue;let I=n.charCodeAt(l);if(I===X||I===j||I===ce||I===pe)B++;else if(I===ge||I===K||I===Ee||I===he&&!Y())B--;else if(B===0&&(I===U||I===Ge))break;else if(B===0&&I===we&&!Ce())break;if(B===0&&P())break;l++}T=p(D,l)}if(l<a&&n.charCodeAt(l)===we)if(o&&T&&(!s||!Wc(T)))ie();else{l++,h();let D=l,B=0,I=0;while(l<a){if(x())continue;let W=n.charCodeAt(l);if(W===X||W===j||W===ce)B++;else if(W===ge||W===K||W===Ee)B--;else if(W===pe&&B===0){if(l+1>=a||n.charCodeAt(l+1)!==we)I++}else if(W===he&&B===0&&!Y()){if(I>0&&(l+1>=a||n.charCodeAt(l+1)!==we))I--}else if(B===0&&I===0&&(W===U||W===Ge))break;if(B===0&&I===0&&P())break;l++}if(F=p(D,l),F.endsWith(" as const")||F==="const"){if(E=!0,!T){let W=F.endsWith(" as const")?F.slice(0,-9).trim():F,M=Ti(W);T=M!=="unknown"?M:void 0}}else if(!T){let W=Ri(F);if(W)T=W}}if(l<a){let D=n.charCodeAt(l);if(D===Ge){l++;continue}if(D===U)l++}let O=le(m),N=`${g?"export ":""}declare ${d} ${v}: ${T||"unknown"};`;y.push({kind:"variable",name:v,text:N,isExported:g,typeAnnotation:T,value:F,modifiers:E?[d,"const assertion"]:[d],leadingComments:O,start:m,end:l});break}while(l<a);return y}function Ni(m,d){l+=9,h();let g=R();h();let y=it();h();let C="";if(b("extends")){l+=7,h();let O=l,N=0;while(l<a){if(x())continue;let D=n.charCodeAt(l);if(D===pe)N++;else if(D===he&&!Y())N--;else if(D===j&&N===0)break;l++}C=p(O,l)}h();let v=l<a&&n.charCodeAt(l)===j?yt():"{}",T=is(v),F=`${d?"export ":""}declare interface ${g}${y}${C?` extends ${C}`:""} ${T}`,E=le(m);return{kind:"interface",name:g,text:F,isExported:d,extends:C||void 0,generics:y||void 0,leadingComments:E,start:m,end:l}}function Wi(m,d){l+=4,h();let g=R();h();let y=it();if(h(),l<a&&n.charCodeAt(l)===we)l++;h();let C=l,v=0;while(l<a){if(x())continue;let O=n.charCodeAt(l);if(O===X||O===j||O===ce||O===pe)v++;else if(O===ge||O===K||O===Ee||O===he&&!Y())v--;else if(v===0&&O===U)break;if(v===0&&P())break;l++}let T=p(C,l);if(l<a&&n.charCodeAt(l)===U)l++;let F=`${d?"export ":""}type ${g}${y} = ${T}`,E=le(m);return{kind:"type",name:g,text:F,isExported:d,generics:y||void 0,leadingComments:E,start:m,end:l}}function Pt(m,d,g){l+=4,h();let y=R();h();let C=l;if(l<a&&n.charCodeAt(l)===j)G(j,K);let v=p(m,l),T=le(m);return{kind:"enum",name:y,text:v,isExported:d,modifiers:g?["const"]:void 0,leadingComments:T,start:m,end:l}}function Ct(m,d,g,y=!1){l+=5,h();let C=R()||"AnonymousClass";h();let v=it();h();let T="";if(b("extends")){l+=7,h();let D=l,B=0;while(l<a){if(x())continue;let I=n.charCodeAt(l);if(I===pe)B++;else if(I===he&&!Y())B--;else if(B===0&&(I===j||b("implements")))break;l++}T=p(D,l)}let F;if(b("implements")){l+=10,h();let D=l,B=0;while(l<a){if(x())continue;let W=n.charCodeAt(l);if(W===pe)B++;else if(W===he&&!Y())B--;else if(B===0&&W===j)break;l++}let I=p(D,l);if(I)F=I.split(",").map((W)=>W.trim())}h();let E=Fi(),O=`${d?y?"export default ":"export declare ":"declare "}${g?"abstract ":""}class ${C}${v}${T?` extends ${T}`:""}${F&&F.length>0?` implements ${F.join(", ")}`:""} ${E}`,N=le(m);return{kind:"class",name:C,text:O,isExported:d,isDefault:y,extends:T||void 0,implements:F,generics:v||void 0,modifiers:g?["abstract"]:void 0,leadingComments:N,start:m,end:l}}function Fi(){if(l>=a||n.charCodeAt(l)!==j)return"{}";l++;let m=[];while(l<a){if(h(),l>=a)break;if(n.charCodeAt(l)===K){l++;break}if(n.charCodeAt(l)===U){l++;continue}if(b("static")&&os("static")===j){l+=6,h(),G(j,K);continue}let d=!1,g=!1,y=!1,C=!1,v=!1,T=!1,F=!1,E=!1,O=!0;while(O){if(h(),b("private")){d=!0,l+=7;continue}if(b("protected")){g=!0,l+=9;continue}if(b("public")){l+=6;continue}if(b("static")){y=!0,l+=6;continue}if(b("abstract")){C=!0,l+=8;continue}if(b("readonly")){v=!0,l+=8;continue}if(b("override")){T=!0,l+=8;continue}if(b("accessor")){F=!0,l+=8;continue}if(b("async")){E=!0,l+=5;continue}if(b("declare")){l+=7;continue}break}if(h(),l>=a||n.charCodeAt(l)===K)break;if(n.charCodeAt(l)===Pr)d=!0;if(d){Di();continue}let N=" ";if(g)N+="protected ";if(y)N+="static ";if(C)N+="abstract ";if(v)N+="readonly ";if(b("constructor")){l+=11,h();let D=$t();if(h(),Ml(D,m),l<a&&n.charCodeAt(l)===j)G(j,K);else if(l<a&&n.charCodeAt(l)===U)l++;let B=Wt(D);m.push(` constructor${B};`)}else if(b("get"))if(l+=3,h(),l<a&&(It(n.charCodeAt(l))||n.charCodeAt(l)===ce||n.charCodeAt(l)===Pr)){let D=Pi();if(D.startsWith("#")){if(h(),l<a&&n.charCodeAt(l)===X)$t();if(h(),ar(),h(),l<a&&n.charCodeAt(l)===j)G(j,K);else if(l<a&&n.charCodeAt(l)===U)l++;continue}h(),$t(),h();let B=ar()||"unknown";if(h(),l<a&&n.charCodeAt(l)===j)G(j,K);else if(l<a&&n.charCodeAt(l)===U)l++;m.push(`${N}get ${D}(): ${B};`)}else as("get",N,y,v,E,m);else if(b("set"))if(l+=3,h(),l<a&&(It(n.charCodeAt(l))||n.charCodeAt(l)===ce||n.charCodeAt(l)===Pr)){let D=Pi();if(D.startsWith("#")){if(h(),l<a&&n.charCodeAt(l)===X)$t();if(h(),l<a&&n.charCodeAt(l)===j)G(j,K);else if(l<a&&n.charCodeAt(l)===U)l++;continue}h();let B=$t();if(h(),l<a&&n.charCodeAt(l)===j)G(j,K);else if(l<a&&n.charCodeAt(l)===U)l++;let I=Wt(B);m.push(`${N}set ${D}${I};`)}else as("set",N,y,v,E,m);else{let D=n.charCodeAt(l)===Oe;if(D)l++,h();let B=Pi();if(!B){Di();continue}ls(B,N,y,v,D,C,E,m)}}return`{
|
|
41
44
|
${m.join(`
|
|
42
45
|
`)}
|
|
43
|
-
}`}function
|
|
44
|
-
${
|
|
46
|
+
}`}function Pi(){if(l>=a)return"";let m=n.charCodeAt(l);if(m===ce){let d=l;return G(ce,Ee),n.slice(d,l)}if(m===Pr)return l++,`#${R()}`;return R()}function os(m){let d=l+m.length;while(d<a&&ke(n.charCodeAt(d)))d++;return d<a?n.charCodeAt(d):0}function Di(){let m=0;while(l<a){if(x())continue;let d=n.charCodeAt(l);if(d===j||d===X)m++;else if(d===K||d===ge){if(m===0)return;m--}else if(d===U&&m===0){l++;return}if(m===0&&Z())return;l++}}function as(m,d,g,y,C,v){ls(m,d,g,y,!1,!1,C,v)}function ls(m,d,g,y,C,v,T,F){if(h(),l>=a)return;let E=n.charCodeAt(l),O=!1;if(E===Fr)O=!0,l++,h();if(l<a&&n.charCodeAt(l)===33)l++,h();let N=l<a?n.charCodeAt(l):0;if(N===X||N===pe){let D=N===pe?it():"";h();let B=$t();h();let I=ar(),W=I.length>0;if(!I)if(T&&C)I="AsyncGenerator<unknown, void, unknown>";else if(C)I="Generator<unknown, void, unknown>";else if(T)I="Promise<void>";else I="void";if(h(),l<a&&n.charCodeAt(l)===j){let bt=l+1;if(G(j,K),!o&&!W&&!C)I=ur(n.slice(bt,l-1),T,B)}else if(l<a&&n.charCodeAt(l)===U)l++;let M=Wt(B),_=O?"?":"",ve=C?"*":"";F.push(`${d}${ve}${m}${_}${D}${M}: ${I};`)}else if(N===Ke||N===we||N===U||N===K||N===ye||N===be){let D="";if(N===Ke){l++,h();let W=l,M=0;while(l<a){if(x())continue;let _=n.charCodeAt(l);if(_===X||_===j||_===ce||_===pe)M++;else if(_===ge||_===K||_===Ee||_===he&&!Y()){if(M===0)break;M--}else if(M===0&&(_===U||_===Ge))break;else if(M===0&&_===we&&!Ce())break;if(M===0&&Z())break;l++}D=p(W,l)}let B="";if(l<a&&n.charCodeAt(l)===we)if(o&&D){l++;let W=0;while(l<a){if(x())continue;let M=n.charCodeAt(l);if(M===X||M===j||M===ce)W++;else if(M===ge||M===K||M===Ee){if(W===0&&M===K)break;W--}else if(W===0&&M===U)break;if(W===0&&Z())break;l++}}else{l++,h();let W=l,M=0;while(l<a){if(x())continue;let _=n.charCodeAt(l);if(_===X||_===j||_===ce)M++;else if(_===ge||_===K||_===Ee){if(M===0&&_===K)break;M--}else if(M===0&&_===U)break;if(M===0&&Z())break;l++}B=p(W,l)}if(l<a&&n.charCodeAt(l)===U)l++;if(!D)if(B){let W=Ri(B);if(W)D=W;else D=B.endsWith("as const")||g&&y?Ti(B):Si(B)}else D="unknown";let I=O?"?":"";F.push(`${d}${m}${I}: ${D};`)}else Di()}function Ml(m,d){let g=m.slice(1,-1).trim();if(!g)return;let y=[],C=0,v=0,T=!1,F=0;for(let E=0;E<=g.length;E++){if(E===g.length){y.push(g.slice(C).trim());break}let O=g.charCodeAt(E);if(T){if(O===Ue){E++;continue}if(O===F)T=!1;continue}if(O===fe||O===de||O===De){T=!0,F=O;continue}if(O===X||O===j||O===ce||O===pe)v++;else if(O===ge||O===K||O===Ee||O===he&&!(E>0&&g.charCodeAt(E-1)===we))v--;else if(O===Ge&&v===0)y.push(g.slice(C,E).trim()),C=E+1}for(let E of y){let O=E.startsWith("public ")||E.startsWith("public\t"),N=E.startsWith("protected ")||E.startsWith("protected\t"),D=E.startsWith("private ")||E.startsWith("private\t"),B=E.includes("readonly ");if(!O&&!N&&!D&&!B)continue;if(D)continue;let I=E,W=[];if(O){let ve=6;while(ve<I.length&&ke(I.charCodeAt(ve)))ve++;I=I.slice(ve),W.push("public")}if(N){let ve=9;while(ve<I.length&&ke(I.charCodeAt(ve)))ve++;I=I.slice(ve),W.push("protected")}if(B){let ve=I.indexOf("readonly ");if(ve!==-1){let bt=ve+8;while(bt<I.length&&ke(I.charCodeAt(bt)))bt++;I=I.slice(0,ve)+I.slice(bt)}W.push("readonly")}let M=W.length>0?`${W.join(" ")} `:"",_=ns(I);d.push(` ${M}${_};`)}}function Mi(m=" "){if(l>=a||n.charCodeAt(l)!==j)return"{}";l++;let d=[];while(l<a){if(h(),l>=a)break;if(n.charCodeAt(l)===K){l++;break}if(n.charCodeAt(l)===U){l++;continue}let g=!1;if(b("export"))g=!0,l+=6,h();if(b("declare"))l+=7,h();let y=g?"export ":"";if(b("function")||b("async")&&Il("async","function")){let C=!1;if(b("async"))C=!0,l+=5,h();if(l+=8,h(),l<a&&n.charCodeAt(l)===Oe)l++,h();let v=R();h();let T=it();h();let F=$t();h();let E=ar();if(!E)E=C?"Promise<void>":"void";if(h(),l<a&&n.charCodeAt(l)===j)G(j,K);else if(l<a&&n.charCodeAt(l)===U)l++;let O=Wt(F);d.push(`${m}${y}function ${v}${T}${O}: ${E};`)}else if(b("const")||b("let")||b("var")){let C=b("const")?"const":b("let")?"let":"var";l+=C.length,h();let v=R();if(!v){ie();continue}h();let T="";if(l<a&&n.charCodeAt(l)===Ke){l++,h();let E=l,O=0;while(l<a){if(x())continue;let N=n.charCodeAt(l);if(N===X||N===j||N===ce||N===pe)O++;else if(N===ge||N===K||N===Ee||N===he&&!Y())O--;else if(O===0&&(N===U||N===Ge))break;else if(O===0&&N===we&&!Ce())break;if(O===0&&P())break;l++}T=p(E,l)}let F="";if(l<a&&n.charCodeAt(l)===we){l++,h();let E=l,O=0;while(l<a){if(x())continue;let N=n.charCodeAt(l);if(N===X||N===j||N===ce||N===pe)O++;else if(N===ge||N===K||N===Ee||N===he&&!Y())O--;else if(O===0&&(N===U||N===Ge))break;if(O===0&&P())break;l++}F=p(E,l)}if(l<a&&n.charCodeAt(l)===U)l++;if(!T&&F){let E=Ri(F);if(E)T=E;else if(C==="const")T=Ti(F);else T=Si(F)}if(!T)T="unknown";d.push(`${m}${y}${C} ${v}: ${T};`)}else if(b("interface")){l+=9,h();let C=R();h();let v=it();h();let T="";if(b("extends")){l+=7,h();let E=l,O=0;while(l<a){if(x())continue;let N=n.charCodeAt(l);if(N===pe)O++;else if(N===he&&!Y())O--;else if(N===j&&O===0)break;l++}T=p(E,l)}let F=is(yt());d.push(`${m}${y}interface ${C}${v}${T?` extends ${T}`:""} ${F}`)}else if(b("type")){l+=4,h();let C=R();h();let v=it();if(h(),l<a&&n.charCodeAt(l)===we){l++,h();let T=l,F=0;while(l<a){if(x())continue;let O=n.charCodeAt(l);if(O===X||O===j||O===ce||O===pe)F++;else if(O===ge||O===K||O===Ee||O===he&&!Y())F--;else if(F===0&&O===U)break;if(F===0&&P())break;l++}let E=p(T,l);if(l<a&&n.charCodeAt(l)===U)l++;d.push(`${m}${y}type ${C}${v} = ${E}`)}}else if(b("class")){l+=5,h();let C=R();h();let v=it();h();let T=l,F=0;while(l<a){if(x())continue;let D=n.charCodeAt(l);if(D===pe)F++;else if(D===he&&!Y())F--;else if(D===j&&F===0)break;l++}let E=p(T,l),O=E?` ${E}`:"",N=Fi();d.push(`${m}${y}class ${C}${v}${O} ${N}`)}else if(b("enum")){l+=4,h();let C=R();h();let v=yt();d.push(`${m}${y}enum ${C} ${v}`)}else if(b("namespace")||b("module")){let C=b("namespace")?"namespace":"module";l+=C.length,h();let v=R();h();let T=Mi(m);d.push(`${m}${y}${C} ${v} ${T}`)}else if(b("abstract"))if(l+=8,h(),b("class")){l+=5,h();let C=R();h();let v=it();h();let T=l,F=0;while(l<a){if(x())continue;let D=n.charCodeAt(l);if(D===pe)F++;else if(D===he&&!Y())F--;else if(D===j&&F===0)break;l++}let E=p(T,l),O=E?` ${E}`:"",N=Fi();d.push(`${m}${y}abstract class ${C}${v}${O} ${N}`)}else ie();else if(g&&b("default")){l+=7,h();let C=l;ie();let v=p(C,l);if(v.charCodeAt(v.length-1)===U)v=v.slice(0,-1);if(v)d.push(`${m}export default ${v};`)}else if(!g&&(n.charCodeAt(l)===fe||n.charCodeAt(l)===de||n.charCodeAt(l)===De))ie();else ie()}if(d.length===0)return"{}";return`{
|
|
47
|
+
${d.join(`
|
|
45
48
|
`)}
|
|
46
|
-
}`}function ll(m,h){let g=l+m.length;while(g<o&&Se(n.charCodeAt(g)))g++;for(let y=0;y<h.length;y++)if(g+y>=o||n.charCodeAt(g+y)!==h.charCodeAt(y))return!1;return g+h.length>=o||!Ze(n.charCodeAt(g+h.length))}function Nt(m,h,g){l+=g.length,d();let y="",$=n.charCodeAt(l);if($===we||$===Ce){let O=l;v($),y=n.slice(O,l)}else{y=T();while(l<o&&n.charCodeAt(l)===at)l++,y+=`.${T()}`}d();let A=l<o&&n.charCodeAt(l)===_?Si():"{}",N=`${h?"export ":""}declare ${g} ${y} ${A}`,F=le(m),E=y.startsWith("'")||y.startsWith('"');return{kind:"module",name:y,text:N,isExported:h,source:E?y.slice(1,-1):void 0,leadingComments:F,start:m,end:l}}function zn(m,h){ie();let g=p(h,l);if(g.charCodeAt(g.length-1)===Y)g=g.slice(0,-1).trimEnd();if(!g)return;let y=Pt(g.charCodeAt(0));for(let O=1;y&&O<g.length;O++)y=Ze(g.charCodeAt(O));let $=le(m);if(y){c.push({kind:"export",name:"default",text:`export default ${g};`,isExported:!0,isTypeOnly:!1,leadingComments:$,start:m,end:l});return}let A="__dtsx_default_export__",N=1;while(n.includes(A))A=`__dtsx_default_export_${N++}__`;let F=xe(g,!1),E=F==="unknown"&&zl(g)?`typeof ${g}`:F;c.push({kind:"variable",name:A,text:`declare const ${A}: ${E};`,isExported:!1,typeAnnotation:E,modifiers:["const"],start:m,end:l}),c.push({kind:"export",name:"default",text:`export default ${A};`,isExported:!0,isTypeOnly:!1,leadingComments:$,start:m,end:l})}while(l<o){if(d(),l>=o)break;let m=l,h=n.charCodeAt(l);if(h===105&&b("import"))c.push(nt(m));else if(h===101&&b("export")){l+=6,d();let g=n.charCodeAt(l);if(g===100&&b("default")){l+=7,d();let y=l,$=n.charCodeAt(l);if($===102&&b("function")){let A=yt(m,!0,!1,!0);if(A)c.push(A)}else if($===97&&b("async")&&Yn("async")!==Y)if(l+=5,d(),b("function")){let A=yt(m,!0,!0,!0);if(A)c.push(A)}else zn(m,y);else if($===99&&b("class")){let A=wt(m,!0,!1,!0);c.push(A)}else if($===97&&b("abstract")){if(l+=8,d(),b("class")){let A=wt(m,!0,!0,!0);c.push(A)}}else zn(m,y)}else if(g===116&&b("type")){let y=l;if(l+=4,d(),l<o&&n.charCodeAt(l)===_){Xt();let $=p(m,l),A=le(m);c.push({kind:"export",name:"",text:$,isExported:!0,isTypeOnly:!0,source:tt($),leadingComments:A,start:m,end:l})}else if(l<o&&n.charCodeAt(l)===Ee){xt();let $=p(m,l);c.push({kind:"export",name:"",text:$,isExported:!0,isTypeOnly:!0,source:tt($),start:m,end:l})}else{l=y;let $=Ai(m,!0);c.push($)}}else if(g===105&&b("interface")){let y=vi(m,!0);c.push(y)}else if(g===102&&b("function")){let y=yt(m,!0,!1,!1);if(y)c.push(y)}else if(g===97&&b("async"))if(l+=5,d(),b("function")){let y=yt(m,!0,!0,!1);if(y)c.push(y)}else ie();else if(g===99)if(b("class")){let y=wt(m,!0,!1);c.push(y)}else if(b("const")){let y=l;if(l+=5,d(),b("enum")){l=y+5,d();let $=Rt(m,!0,!0);c.push($)}else{l=y;let $=Tt(m,"const",!0);for(let A=0;A<$.length;A++)c.push($[A])}}else ie();else if(g===97&&b("abstract")){if(l+=8,d(),b("class")){let y=wt(m,!0,!0);c.push(y)}}else if(g===108&&b("let")){let y=Tt(m,"let",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else if(g===118&&b("var")){let y=Tt(m,"var",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else if(g===101&&b("enum")){let y=Rt(m,!0,!1);c.push(y)}else if(g===100&&b("declare"))l+=7,d(),Xn(m,!0);else if(g===110&&b("namespace")&&B(9)){let y=Nt(m,!0,"namespace");c.push(y)}else if(g===109&&b("module")&&B(6)){let y=Nt(m,!0,"module");c.push(y)}else if(g===_){Xt();let y=p(m,l),$=y.includes("export type"),A=le(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:$,source:tt(y),leadingComments:A,start:m,end:l})}else if(g===Ee){xt();let y=p(m,l),$=le(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:!1,source:tt(y),leadingComments:$,start:m,end:l})}else{ie();let y=p(m,l);if(y)c.push({kind:"export",name:"",text:y,isExported:!0,start:m,end:l})}}else if(h===100&&b("declare"))l+=7,d(),Xn(m,!1);else if(h===105&&b("interface")){let g=vi(m,!1);f.set(g.name,g)}else if(h===116&&b("type")){let g=Ai(m,!1);f.set(g.name,g),c.push(g)}else if(h===102&&b("function")){let g=yt(m,!1,!1,!1);if(g)f.set(g.name,g);else ie()}else if(h===97)if(b("async")){let g=l;if(l+=5,d(),b("function")){let y=yt(m,!1,!0,!1);if(y)f.set(y.name,y);else l=g,ie()}else l=g,ie()}else if(b("abstract"))if(l+=8,d(),b("class")){let g=wt(m,!1,!1);f.set(g.name,g),c.push(g)}else ie();else l++,ie();else if(h===99)if(b("class")){let g=wt(m,!1,!1);f.set(g.name,g),c.push(g)}else if(b("const")){let g=l;if(l+=5,d(),b("enum")){l=g+5,d();let y=Rt(m,!1,!0);f.set(y.name,y),c.push(y)}else{l=g;let y=Tt(m,"const",!1);for(let $=0;$<y.length;$++)f.set(y[$].name,y[$])}}else l++,ie();else if(h===101&&b("enum")){let g=Rt(m,!1,!1);f.set(g.name,g),c.push(g)}else if(h===108&&b("let"))ie();else if(h===118&&b("var"))ie();else if(h===109&&b("module")&&B(6)){let g=Nt(m,!1,"module");c.push(g)}else if(h===110&&b("namespace")&&B(9)){let g=Nt(m,!1,"namespace");c.push(g)}else{let g=n.charCodeAt(l);if(g===we||g===Ce){if(v(g),l<o&&n.charCodeAt(l)===Y)l++}else if(g===je){if(w(),l<o&&n.charCodeAt(l)===Y)l++}else if(g===Hl){if(l++,T(),d(),l<o&&n.charCodeAt(l)===at)l++,T(),d();if(l<o&&n.charCodeAt(l)===Q)U(Q,pe)}else l++,ie()}}if(f.size>0)ec(c,f);if(u.size>0){let m=new Map;for(let g of c)if(g.kind==="function")m.set(g.name,(m.get(g.name)||0)+1);let h=new Set;for(let[g,y]of m)if(y>1)h.add(g);if(h.size>0){let g=new Set;for(let y of h)for(let $=c.length-1;$>=0;$--)if(c[$].kind==="function"&&c[$].name===y&&u.has($)){g.add($);break}if(g.size>0){let y=[...g].sort(($,A)=>A-$);for(let $ of y)c.splice($,1)}}}return c;function Xn(m,h){if(b("function")){let g=yt(m,h,!1,!1);if(g)c.push(g)}else if(b("async")){if(l+=5,d(),b("function")){let g=yt(m,h,!0,!1);if(g)c.push(g)}}else if(b("class")){let g=wt(m,h,!1);c.push(g)}else if(b("abstract")){if(l+=8,d(),b("class")){let g=wt(m,h,!0);c.push(g)}}else if(b("interface")){let g=vi(m,h);c.push(g)}else if(b("type")){let g=Ai(m,h);c.push(g)}else if(b("enum")){let g=Rt(m,h,!1);c.push(g)}else if(b("const")){let g=l;if(l+=5,d(),b("enum")){l=g+5,d();let y=Rt(m,h,!0);c.push(y)}else if(h){l=g;let y=Tt(m,"const",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else ie()}else if(b("let")||b("var"))if(h){let g=b("let")?"let":"var",y=Tt(m,g,!0);for(let $=0;$<y.length;$++)c.push(y[$])}else ie();else if(b("module")){let g=Nt(m,h,"module");c.push(g)}else if(b("namespace")){let g=Nt(m,h,"namespace");c.push(g)}else if(b("global")){l+=6,d();let g=`declare global ${l<o&&n.charCodeAt(l)===_?Si():"{}"}`,y=le(m);c.push({kind:"module",name:"global",text:g,isExported:!1,leadingComments:y,start:m,end:l})}else ie()}}function xs(e,t){let r=0,i=e.length;while(r<i){let n=e.charCodeAt(r);if(n>=65&&n<=90||n>=97&&n<=122||n===95||n===36||n>127){let s=r;r++;while(r<i){let a=e.charCodeAt(r);if(a>=65&&a<=90||a>=97&&a<=122||a>=48&&a<=57||a===95||a===36||a>127)r++;else break}t.add(e.substring(s,r))}else r++}}function Es(e,t){let r=0;while(r<e.length){let i=e.charCodeAt(r);if(i===we||i===Ce||i===je){let u=i;r++;while(r<e.length)if(e.charCodeAt(r)===Ge)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(i===z&&e.charCodeAt(r+1)===z){r+=2;while(r<e.length&&e.charCodeAt(r)!==me&&e.charCodeAt(r)!==be)r++;continue}if(i===z&&e.charCodeAt(r+1)===Ee){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!Pt(i)){r++;continue}let n=r++;while(r<e.length&&Ze(e.charCodeAt(r)))r++;let s=n-1,a=r;while(s>=0&&Se(e.charCodeAt(s)))s--;while(a<e.length&&Se(e.charCodeAt(a)))a++;let o=s>=0?e.charCodeAt(s):0,c=a<e.length?e.charCodeAt(a):0,f=n>=3&&e.slice(n-3,n)==="...";if(c===Ke||o===at&&!f)continue;if(c===Q&&(o===_||o===Ue))continue;t.add(e.slice(n,r))}}function ec(e,t){let r=new Set,i=new Set;for(let a of e)i.add(a.name);let n=new Set,s=[];for(let a=0;a<e.length;a++){let o=e[a];if(o.kind!=="import"){if(s.push(o.text),xs(o.text,n),typeof o.value==="string")Es(o.value,n)}}for(;;){let a=[];for(let[f,u]of t){if(r.has(f))continue;if(n.has(f)){if(!i.has(f))a.push(u),i.add(f);r.add(f)}}if(a.length===0)break;a.sort((f,u)=>(f.start??1/0)-(u.start??1/0));let o=[],c=0;for(let f=0;f<e.length;f++){let u=e[f].start??1/0;while(c<a.length&&(a[c].start??1/0)<=u)o.push(a[c++]);o.push(e[f])}while(c<a.length)o.push(a[c++]);e.length=0;for(let f=0;f<o.length;f++)e.push(o[f]);for(let f of a)if(f.kind!=="import"){if(s.push(f.text),xs(f.text,n),typeof f.value==="string")Es(f.value,n)}}}var We=32,Pe=9,me=10,be=13,z=47,Ee=42,we=39,Ce=34,je=96,Ge=92,_=123,G=125,Q=40,pe=41,ce=91,Oe=93,de=60,fe=62,Y=59,Ke=58,ye=61,Ue=44,at=46,Or=63,Sr=35,Hl=64,Os=36,ql=95,Ji;var Rs=he(()=>{Vi();Ji=["public","protected","private","readonly","override"]});function Ws(e,t,r=!0,i=!1){let n=tr(e),s=`${t}:${r?1:0}:${i?1:0}`,a=Ft.get(s);if(a&&a.contentHash===n)return a.lastAccess=++Ns,a.declarations;let o=i?Ss(e,t,r):ks(e,t,r);if(Ft.set(s,{declarations:o,contentHash:n,lastAccess:++Ns}),Ft.size>tc){let c=Math.max(1,Math.ceil(Ft.size*0.1)),f=[];for(let[u,l]of Ft)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)Ft.delete(f[u][0])}return o}var tc=100,Ns=0,Ft;var Ps=he(()=>{Rs();Ni();Ft=new Map});function kr(e,t,r=!0,i=!1){return Ws(e,t,r,i)}var Ki=he(()=>{Ps()});import{dirname as Od,relative as rc,resolve as Sd}from"path";async function Fs(e,t,r){let i=new Map,n=[],s=new Set,a=0,o=0,c=0,f=[];for(let k of e){let S=t.get(k);if(!S)continue;f.push({file:k,decls:kr(S,k,r.keepComments)})}for(let{file:k,decls:S}of f){a+=S.length;for(let T of S)if(T.kind==="import"){o++;let b=T.source||"";if(b.startsWith("."))continue;if(!i.has(b))i.set(b,{source:b,specifiers:new Map,isTypeOnly:T.isTypeOnly||!1,isSideEffect:T.isSideEffect||!1});let B=i.get(b);if(T.specifiers)for(let re of T.specifiers){let P=re.alias||re.name;if(!B.specifiers.has(P))B.specifiers.set(P,{name:re.name,alias:re.alias,isType:re.isType||!1})}if(!T.isTypeOnly)B.isTypeOnly=!1}else if(T.isExported||T.kind==="export"){if(c++,T.kind==="export"&&T.source&&(T.source.startsWith(".")||T.source.startsWith("/")))continue;if(T.name&&s.has(T.name))continue;if(T.name)s.add(T.name);n.push({declaration:T,file:k})}}let u=[];u.push("/**"),u.push(" * Bundled TypeScript declarations"),u.push(` * Generated from ${e.length} source files`),u.push(" */"),u.push("");let l=r.importOrder||["bun"],p=Array.from(i.values()),d=Array(p.length);for(let k=0;k<p.length;k++){let S=p[k].source,T=l.length;for(let b=0;b<l.length;b++)if(S.startsWith(l[b])){T=b;break}d[k]=T}let C=p.map((k,S)=>S);C.sort((k,S)=>{let T=d[k],b=d[S];if(T!==b)return T-b;return p[k].source.localeCompare(p[S].source)});let v=C.map((k)=>p[k]);for(let k of v)if(k.isSideEffect)u.push(`import '${k.source}';`);else if(k.specifiers.size>0){let S=Array.from(k.specifiers.values()).map((b)=>{let B=b.isType?"type ":"";return b.alias?`${B}${b.name} as ${b.alias}`:`${B}${b.name}`}),T=k.isTypeOnly?"type ":"";u.push(`import ${T}{ ${S.join(", ")} } from '${k.source}';`)}if(v.length>0)u.push("");let w=new Map;for(let{declaration:k,file:S}of n){if(!w.has(S))w.set(S,[]);w.get(S).push(k)}for(let[k,S]of w){let T=rc(r.cwd,k);u.push(`// From: ${T}`);for(let b of S){if(r.keepComments&&b.leadingComments)for(let B of b.leadingComments)u.push(B);u.push(Ds(b))}u.push("")}let x=u.join(`
|
|
47
|
-
|
|
48
|
-
|
|
49
|
+
}`}function Il(m,d){let g=l+m.length;while(g<a&&ke(n.charCodeAt(g)))g++;for(let y=0;y<d.length;y++)if(g+y>=a||n.charCodeAt(g+y)!==d.charCodeAt(y))return!1;return g+d.length>=a||!Je(n.charCodeAt(g+d.length))}function Dt(m,d,g){l+=g.length,h();let y="",C=n.charCodeAt(l);if(C===fe||C===de){let O=l;A(C),y=n.slice(O,l)}else{y=R();while(l<a&&n.charCodeAt(l)===at)l++,y+=`.${R()}`}h();let v=l<a&&n.charCodeAt(l)===j?Mi():"{}",T=`${d?"export ":""}declare ${g} ${y} ${v}`,F=le(m),E=y.startsWith("'")||y.startsWith('"');return{kind:"module",name:y,text:T,isExported:d,source:E?y.slice(1,-1):void 0,leadingComments:F,start:m,end:l}}function cs(m,d){ie();let g=p(d,l);if(g.charCodeAt(g.length-1)===U)g=g.slice(0,-1).trimEnd();if(!g)return;let y=It(g.charCodeAt(0));for(let O=1;y&&O<g.length;O++)y=Je(g.charCodeAt(O));let C=le(m);if(y){c.push({kind:"export",name:"default",text:`export default ${g};`,isExported:!0,isTypeOnly:!1,leadingComments:C,start:m,end:l});return}let v="__dtsx_default_export__",T=1;while(n.includes(v))v=`__dtsx_default_export_${T++}__`;let F=xe(g,!1),E=F==="unknown"&&Nc(g)?`typeof ${g}`:F;c.push({kind:"variable",name:v,text:`declare const ${v}: ${E};`,isExported:!1,typeAnnotation:E,modifiers:["const"],start:m,end:l}),c.push({kind:"export",name:"default",text:`export default ${v};`,isExported:!0,isTypeOnly:!1,leadingComments:C,start:m,end:l})}while(l<a){if(h(),l>=a)break;let m=l,d=n.charCodeAt(l);if(d===105&&b("import"))c.push(st(m));else if(d===101&&b("export")){l+=6,h();let g=n.charCodeAt(l);if(g===100&&b("default")){l+=7,h();let y=l,C=n.charCodeAt(l);if(C===102&&b("function")){let v=wt(m,!0,!1,!0);if(v)c.push(v)}else if(C===97&&b("async")&&os("async")!==U)if(l+=5,h(),b("function")){let v=wt(m,!0,!0,!0);if(v)c.push(v)}else cs(m,y);else if(C===99&&b("class")){let v=Ct(m,!0,!1,!0);c.push(v)}else if(C===97&&b("abstract")){if(l+=8,h(),b("class")){let v=Ct(m,!0,!0,!0);c.push(v)}}else cs(m,y)}else if(g===116&&b("type")){let y=l;if(l+=4,h(),l<a&&n.charCodeAt(l)===j){sr();let C=p(m,l),v=le(m);c.push({kind:"export",name:"",text:C,isExported:!0,isTypeOnly:!0,source:rt(C),leadingComments:v,start:m,end:l})}else if(l<a&&n.charCodeAt(l)===Oe){kt();let C=p(m,l);c.push({kind:"export",name:"",text:C,isExported:!0,isTypeOnly:!0,source:rt(C),start:m,end:l})}else{l=y;let C=Wi(m,!0);c.push(C)}}else if(g===105&&b("interface")){let y=Ni(m,!0);c.push(y)}else if(g===102&&b("function")){let y=wt(m,!0,!1,!1);if(y)c.push(y)}else if(g===97&&b("async"))if(l+=5,h(),b("function")){let y=wt(m,!0,!0,!1);if(y)c.push(y)}else ie();else if(g===99)if(b("class")){let y=Ct(m,!0,!1);c.push(y)}else if(b("const")){let y=l;if(l+=5,h(),b("enum")){l=y+5,h();let C=Pt(m,!0,!0);c.push(C)}else{l=y;let C=Ft(m,"const",!0);for(let v=0;v<C.length;v++)c.push(C[v])}}else ie();else if(g===97&&b("abstract")){if(l+=8,h(),b("class")){let y=Ct(m,!0,!0);c.push(y)}}else if(g===108&&b("let")){let y=Ft(m,"let",!0);for(let C=0;C<y.length;C++)c.push(y[C])}else if(g===118&&b("var")){let y=Ft(m,"var",!0);for(let C=0;C<y.length;C++)c.push(y[C])}else if(g===101&&b("enum")){let y=Pt(m,!0,!1);c.push(y)}else if(g===100&&b("declare"))l+=7,h(),fs(m,!0);else if(g===110&&b("namespace")&&L(9)){let y=Dt(m,!0,"namespace");c.push(y)}else if(g===109&&b("module")&&L(6)){let y=Dt(m,!0,"module");c.push(y)}else if(g===j){sr();let y=p(m,l),C=y.includes("export type"),v=le(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:C,source:rt(y),leadingComments:v,start:m,end:l})}else if(g===Oe){kt();let y=p(m,l),C=le(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:!1,source:rt(y),leadingComments:C,start:m,end:l})}else{ie();let y=p(m,l);if(y)c.push({kind:"export",name:"",text:y,isExported:!0,start:m,end:l})}}else if(d===100&&b("declare"))l+=7,h(),fs(m,!1);else if(d===105&&b("interface")){let g=Ni(m,!1);f.set(g.name,g)}else if(d===116&&b("type")){let g=Wi(m,!1);f.set(g.name,g),c.push(g)}else if(d===102&&b("function")){let g=wt(m,!1,!1,!1);if(g)f.set(g.name,g);else ie()}else if(d===97)if(b("async")){let g=l;if(l+=5,h(),b("function")){let y=wt(m,!1,!0,!1);if(y)f.set(y.name,y);else l=g,ie()}else l=g,ie()}else if(b("abstract"))if(l+=8,h(),b("class")){let g=Ct(m,!1,!1);f.set(g.name,g),c.push(g)}else ie();else l++,ie();else if(d===99)if(b("class")){let g=Ct(m,!1,!1);f.set(g.name,g),c.push(g)}else if(b("const")){let g=l;if(l+=5,h(),b("enum")){l=g+5,h();let y=Pt(m,!1,!0);f.set(y.name,y),c.push(y)}else{l=g;let y=Ft(m,"const",!1);for(let C=0;C<y.length;C++)f.set(y[C].name,y[C])}}else l++,ie();else if(d===101&&b("enum")){let g=Pt(m,!1,!1);f.set(g.name,g),c.push(g)}else if(d===108&&b("let"))ie();else if(d===118&&b("var"))ie();else if(d===109&&b("module")&&L(6)){let g=Dt(m,!1,"module");c.push(g)}else if(d===110&&b("namespace")&&L(9)){let g=Dt(m,!1,"namespace");c.push(g)}else{let g=n.charCodeAt(l);if(g===fe||g===de){if(A(g),l<a&&n.charCodeAt(l)===U)l++}else if(g===De){if($(),l<a&&n.charCodeAt(l)===U)l++}else if(g===Tc){if(l++,R(),h(),l<a&&n.charCodeAt(l)===at)l++,R(),h();if(l<a&&n.charCodeAt(l)===X)G(X,ge)}else l++,ie()}}if(f.size>0)Fc(c,f);if(u.size>0){let m=new Map;for(let g of c)if(g.kind==="function")m.set(g.name,(m.get(g.name)||0)+1);let d=new Set;for(let[g,y]of m)if(y>1)d.add(g);if(d.size>0){let g=new Set;for(let y of d)for(let C=c.length-1;C>=0;C--)if(c[C].kind==="function"&&c[C].name===y&&u.has(C)){g.add(C);break}if(g.size>0){let y=[...g].sort((C,v)=>v-C);for(let C of y)c.splice(C,1)}}}return c;function fs(m,d){if(b("function")){let g=wt(m,d,!1,!1);if(g)c.push(g)}else if(b("async")){if(l+=5,h(),b("function")){let g=wt(m,d,!0,!1);if(g)c.push(g)}}else if(b("class")){let g=Ct(m,d,!1);c.push(g)}else if(b("abstract")){if(l+=8,h(),b("class")){let g=Ct(m,d,!0);c.push(g)}}else if(b("interface")){let g=Ni(m,d);c.push(g)}else if(b("type")){let g=Wi(m,d);c.push(g)}else if(b("enum")){let g=Pt(m,d,!1);c.push(g)}else if(b("const")){let g=l;if(l+=5,h(),b("enum")){l=g+5,h();let y=Pt(m,d,!0);c.push(y)}else if(d){l=g;let y=Ft(m,"const",!0);for(let C=0;C<y.length;C++)c.push(y[C])}else ie()}else if(b("let")||b("var"))if(d){let g=b("let")?"let":"var",y=Ft(m,g,!0);for(let C=0;C<y.length;C++)c.push(y[C])}else ie();else if(b("module")){let g=Dt(m,d,"module");c.push(g)}else if(b("namespace")){let g=Dt(m,d,"namespace");c.push(g)}else if(b("global")){l+=6,h();let g=`declare global ${l<a&&n.charCodeAt(l)===j?Mi():"{}"}`,y=le(m);c.push({kind:"module",name:"global",text:g,isExported:!1,leadingComments:y,start:m,end:l})}else ie()}}function Is(e,t){let r=0,i=e.length;while(r<i){let n=e.charCodeAt(r);if(n>=65&&n<=90||n>=97&&n<=122||n===95||n===36||n>127){let s=r;r++;while(r<i){let o=e.charCodeAt(r);if(o>=65&&o<=90||o>=97&&o<=122||o>=48&&o<=57||o===95||o===36||o>127)r++;else break}t.add(e.substring(s,r))}else r++}}function Bs(e,t){let r=0;while(r<e.length){let i=e.charCodeAt(r);if(i===fe||i===de||i===De){let u=i;r++;while(r<e.length)if(e.charCodeAt(r)===Ue)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(i===z&&e.charCodeAt(r+1)===z){r+=2;while(r<e.length&&e.charCodeAt(r)!==ye&&e.charCodeAt(r)!==be)r++;continue}if(i===z&&e.charCodeAt(r+1)===Oe){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!It(i)){r++;continue}let n=r++;while(r<e.length&&Je(e.charCodeAt(r)))r++;let s=n-1,o=r;while(s>=0&&ke(e.charCodeAt(s)))s--;while(o<e.length&&ke(e.charCodeAt(o)))o++;let a=s>=0?e.charCodeAt(s):0,c=o<e.length?e.charCodeAt(o):0,f=n>=3&&e.slice(n-3,n)==="...";if(c===Ke||a===at&&!f)continue;if(c===X&&(a===j||a===Ge))continue;t.add(e.slice(n,r))}}function Fc(e,t){let r=new Set,i=new Set;for(let o of e)i.add(o.name);let n=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o];if(a.kind!=="import"){if(s.push(a.text),Is(a.text,n),typeof a.value==="string")Bs(a.value,n)}}for(;;){let o=[];for(let[f,u]of t){if(r.has(f))continue;if(n.has(f)){if(!i.has(f))o.push(u),i.add(f);r.add(f)}}if(o.length===0)break;o.sort((f,u)=>(f.start??1/0)-(u.start??1/0));let a=[],c=0;for(let f=0;f<e.length;f++){let u=e[f].start??1/0;while(c<o.length&&(o[c].start??1/0)<=u)a.push(o[c++]);a.push(e[f])}while(c<o.length)a.push(o[c++]);e.length=0;for(let f=0;f<a.length;f++)e.push(a[f]);for(let f of o)if(f.kind!=="import"){if(s.push(f.text),Is(f.text,n),typeof f.value==="string")Bs(f.value,n)}}}var We=32,Fe=9,ye=10,be=13,z=47,Oe=42,fe=39,de=34,De=96,Ue=92,j=123,K=125,X=40,ge=41,ce=91,Ee=93,pe=60,he=62,U=59,Ke=58,we=61,Ge=44,at=46,Fr=63,Pr=35,Tc=64,Ls=36,Rc=95,Qi;var Js=ue(()=>{Xi();Qi=["public","protected","private","readonly","override"]});function Us(e){return e.endsWith(".vue")}function Pc(e){let t={script:null,scriptSetup:null},r=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,i;while((i=r.exec(e))!==null){let n=i[1]||"",s=/lang\s*=\s*["']([^"']+)["']/i.exec(n)?.[1]?.toLowerCase()??"js",o={content:i[2]??"",attrs:n,setup:/\bsetup\b/.test(n),lang:s};if(o.setup)t.scriptSetup=o;else t.script=o}return t}function lt(e,t){let r=e[t];t++;while(t<e.length){let i=e[t];if(i==="\\"){t+=2;continue}if(i===r)return t+1;t++}return t}function vt(e,t){t++;let r=0;while(t<e.length){let i=e[t];if(i==="\\"){t+=2;continue}if(i==="`"&&r===0)return t+1;if(i==="$"&&e[t+1]==="{"){r++,t+=2;continue}if(i==="}"){if(r>0)r--;t++;continue}t++}return t}function Bt(e,t){if(e[t+1]==="/"){let r=e.indexOf(`
|
|
50
|
+
`,t+2);return r===-1?e.length:r+1}if(e[t+1]==="*"){let r=e.indexOf("*/",t+2);return r===-1?e.length:r+2}return t+1}function je(e,t,r,i){let n=0,s=t;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){s=lt(e,s);continue}if(o==="`"){s=vt(e,s);continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=Bt(e,s);continue}if(o===r)n++;else if(o===i){if(n--,n===0)return s}s++}return-1}function tn(e,t){let r=0,i=t;while(i<e.length){let n=e[i];if(n==='"'||n==="'"){i=lt(e,i);continue}if(n==="`"){i=vt(e,i);continue}if(n==="/"&&(e[i+1]==="/"||e[i+1]==="*")){i=Bt(e,i);continue}if(n==="="&&e[i+1]===">"){i+=2;continue}if(n==="<")r++;else if(n===">"){if(r--,r===0)return i}i++}return-1}function Lt(e,t=","){let r=[],i=0,n="",s=0;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){let a=lt(e,s);n+=e.slice(s,a),s=a;continue}if(o==="`"){let a=vt(e,s);n+=e.slice(s,a),s=a;continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=Bt(e,s);continue}if(o==="{"||o==="["||o==="("||o==="<")i++;else if(o==="}"||o==="]"||o===")"||o===">")i--;if(o===t&&i===0){r.push(n),n="",s++;continue}n+=o,s++}if(n.trim()!=="")r.push(n);return r}function mr(e){let t=e.trim();if(!t.startsWith("{"))return[];let r=je(t,0,"{","}");if(r===-1)return[];let i=t.slice(1,r),n=[];for(let s of Lt(i)){let o=-1,a=0;for(let u=0;u<s.length;u++){let l=s[u];if(l==='"'||l==="'"){u=lt(s,u)-1;continue}if(l==="`"){u=vt(s,u)-1;continue}if(l==="{"||l==="["||l==="("||l==="<")a++;else if(l==="}"||l==="]"||l===")"||l===">")a--;else if(l===":"&&a===0){o=u;break}}if(o!==-1){n.push({key:dr(s.slice(0,o).trim()),value:s.slice(o+1).trim(),isMethod:!1});continue}let c=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(s.trim());if(c){n.push({key:dr(c[1]),value:s.trim(),isMethod:!0});continue}let f=s.trim();if(f)n.push({key:dr(f),value:"",isMethod:!1})}return n}function dr(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function Mr(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function rn(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),i;while((i=r.exec(e))!==null){let n=i.index+i[0].length;while(n<e.length&&/\s/.test(e[n]))n++;let s=null;if(e[n]==="<"){let c=tn(e,n);if(c===-1)return null;s=e.slice(n+1,c).trim(),n=c+1;while(n<e.length&&/\s/.test(e[n]))n++}if(e[n]!=="(")continue;let o=je(e,n,"(",")");if(o===-1)return null;let a=Lt(e.slice(n+1,o));return{generic:s,arg:a.length>0?a[0].trim():null}}return null}function Dc(e,t){let r=Hs(e,t);if(!r)return null;return r.kind==="interface"?e.slice(r.bodyStart,r.end):e.slice(r.bodyStart,r.end).trim()}function Hs(e,t){let r=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(r){let n=r.index+r[0].length-1,s=je(e,n,"{","}");if(s!==-1)return{kind:"interface",start:r.index,end:s+1,bodyStart:n}}let i=new RegExp(`\\btype\\s+${t}\\b[^=]*=`,"m").exec(e);if(i){let n=i.index+i[0].length,s=0,o=n;while(n<e.length){let a=e[n];if(a==='"'||a==="'"){n=lt(e,n);continue}if(a==="`"){n=vt(e,n);continue}if(a==="{"||a==="["||a==="("||a==="<")s++;else if(a==="}"||a==="]"||a===")"||a===">")s--;else if((a===";"||a===`
|
|
51
|
+
`)&&s===0)break;n++}return{kind:"type",start:i.index,end:n,bodyStart:o}}return null}function Mc(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let r=e.indexOf("<",t),i=tn(e,r);if(i===-1)return null;if(e.slice(i+1).trim()!=="")return null;return e.slice(r+1,i).trim()}function en(e){let t=e.trim(),r=Mc(t);if(r!==null)return{type:r,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let i=je(t,0,"[","]");if(i!==-1){let n=Lt(t.slice(1,i)).map((s)=>en(s).type).filter((s)=>s!=="unknown");return{type:n.length>0?[...new Set(n)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let i=mr(t),n=i.find((c)=>c.key==="type"),s=i.find((c)=>c.key==="required"),o=n?en(n.value).type:"unknown",a=!(s&&s.value.trim()==="true");return{type:o,optional:a}}if(Vs[t])return{type:Vs[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function qs(e){let t=e.trim();if(t.startsWith("{")){let r=mr(t);if(r.length===0)return"{}";return`{ ${r.map((i)=>{if(i.isMethod||i.value==="")return`${Mr(i.key)}?: unknown`;let n=en(i.value);return`${Mr(i.key)}${n.optional?"?":""}: ${n.type}`}).join(", ")} }`}if(t.startsWith("[")){let r=je(t,0,"[","]");if(r===-1)return null;let i=Lt(t.slice(1,r)).map((n)=>dr(n.trim())).filter((n)=>n!=="");if(i.length===0)return"{}";return`{ ${i.map((n)=>`${Mr(n)}?: unknown`).join(", ")} }`}return null}function Ic(e){let t=e.trim();if(!t.startsWith("["))return null;let r=je(t,0,"[","]");if(r===-1)return null;let i=Lt(t.slice(1,r)).map((n)=>n.trim());if(i.length===0)return"{}";if(!i.every((n)=>n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"')))return"string[]";return`[${i.map((n)=>JSON.stringify(dr(n))).join(", ")}]`}function Bc(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=mr(t);if(r.length===0)return"{}";return`{ ${r.map((i)=>`${JSON.stringify(i.key)}: (...args: any[]) => void`).join(", ")} }`}function zs(e){return Ic(e)??Bc(e)}function Lc(e){let t=[],r=0,i="",n=0;while(n<e.length){let s=e[n];if(s==='"'||s==="'"){let o=lt(e,n);i+=e.slice(n,o),n=o;continue}if(s==="`"){let o=vt(e,n);i+=e.slice(n,o),n=o;continue}if(s==="/"&&(e[n+1]==="/"||e[n+1]==="*")){let o=Bt(e,n);i+=e.slice(n,o),n=o;continue}if(s==="="&&e[n+1]===">"){i+="=>",n+=2;continue}if(s==="{"||s==="["||s==="("||s==="<")r++;else if(s==="}"||s==="]"||s===")"||s===">")r--;if((s===";"||s===","||s===`
|
|
52
|
+
`)&&r===0){if(i.trim()!=="")t.push(i.trim());i="",n++;continue}i+=s,n++}if(i.trim()!=="")t.push(i.trim());return t}function jc(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=je(t,0,"{","}");if(r===-1||t.slice(r+1).trim()!=="")return null;let i=Lc(t.slice(1,r));if(i.length===0)return"{}";let n=[];for(let s of i){let o=/^\(\s*\w+\s*:\s*/.exec(s);if(!o)return null;let a=o[0].length,c=s[a];if(c!=="'"&&c!=='"'&&c!=="`")return null;let f=lt(s,a),u=s.slice(a+1,f-1),l=je(s,s.indexOf("(",0),"(",")");if(l===-1)return null;let p=s.slice(a,l),h=Lt(p).slice(1),w=s.slice(l+1).trim();if(w.startsWith(":"))w=w.slice(1).trim();if(w==="")w="void";n.push(`${JSON.stringify(u)}: (${h.map((A)=>A.trim()).join(", ")}) => ${w}`)}return`{ ${n.join(", ")} }`}function _c(e){let t=e;for(let r of["defineProps","defineEmits","defineExpose","defineOptions"])t=Zc(t,r);return t}function Zc(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),i=[],n=e,s;while((s=r.exec(e))!==null){let o=e.lastIndexOf(`
|
|
53
|
+
`,s.index)+1,a=e.slice(o,s.index),c=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(a);if(!c)continue;let f=s.index+s[0].length;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]==="<"){let p=tn(e,f);if(p===-1)continue;f=p+1;while(f<e.length&&/\s/.test(e[f]))f++}if(e[f]!=="(")continue;let u=je(e,f,"(",")");if(u===-1)continue;if(c[1]){let p=o+a.length-c[1].length,h=e.indexOf("(",p);if(h!==-1){let w=je(e,h,"(",")");if(w!==-1)u=w}}let l=u+1;while(l<e.length&&e[l]!==`
|
|
54
|
+
`&&/\s|;/.test(e[l]))l++;if(e[l]===`
|
|
55
|
+
`)l++;i.push([o,l])}for(let o=i.length-1;o>=0;o--)n=n.slice(0,i[o][0])+n.slice(i[o][1]);return n}function Jc(e){let t=/\bexport\s+default\b/g,r;while((r=t.exec(e))!==null){let i=r.index+r[0].length;while(i<e.length&&/\s/.test(e[i]))i++;let n=-1,s=-1,o=-1;if(e[i]==="{")n=i,s=je(e,i,"{","}"),o=s;else if(e.startsWith("defineComponent",i)){let f=e.indexOf("(",i);if(f!==-1){let u=f+1;while(u<e.length&&/\s/.test(e[u]))u++;if(e[u]==="{")n=u,s=je(e,u,"{","}"),o=je(e,f,"(",")")}}if(n===-1||s===-1||o===-1)return{options:null,script:e,passthrough:!0};let a=o+1;if(e[a]===";")a++;let c=(e.slice(0,r.index)+e.slice(a)).trim();return{options:e.slice(n,s+1),script:c,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function Ys(e,t){let r=mr(e).find((i)=>i.key===t);return r&&r.value!==""?r.value:null}function Ks(e,t){let r=Vc(e),i=e;for(let n=r.length-1;n>=0;n--){let s=r[n],o=i.slice(0,s.start)+i.slice(s.end);if(new RegExp(`\\b${s.name}\\b`).test(o))continue;if(new RegExp(`\\btypeof\\s+${s.name}\\b`).test(t))continue;i=o}return i}function Vc(e){let t=[],r=/^[ \t]*(const|let|var|(?:async[ \t]+)?function)[ \t]+([A-Za-z_$][\w$]*)[ \t]*(?::[^=\n]+)?=?/gm,i;while((i=r.exec(e))!==null){let n=e.lastIndexOf(`
|
|
56
|
+
`,i.index)+1;if(/\bexport\b/.test(e.slice(n,i.index)))continue;let s=i[1],o=i[2],a=i.index+i[0].length,c=-1;if(s.endsWith("function")){let f=e.indexOf("(",a);if(f===-1)continue;let u=je(e,f,"(",")");if(u===-1)continue;a=u+1;while(a<e.length&&/\s/.test(e[a]))a++;if(e[a]===":")while(a<e.length&&e[a]!=="{"&&e[a]!==`
|
|
57
|
+
`)a++;while(a<e.length&&/\s/.test(e[a])&&e[a]!==`
|
|
58
|
+
`)a++;if(e[a]!=="{")continue;let l=je(e,a,"{","}");if(l===-1)continue;c=l+1}else{let f=0;while(a<e.length){let u=e[a];if(u==='"'||u==="'"){a=lt(e,a);continue}if(u==="`"){a=vt(e,a);continue}if(u==="/"&&(e[a+1]==="/"||e[a+1]==="*")){a=Bt(e,a);continue}if(u==="{"||u==="["||u==="(")f++;else if(u==="}"||u==="]"||u===")")f--;else if(u===";"&&f===0){c=a+1;break}else if(u===`
|
|
59
|
+
`&&f===0){c=a;break}a++}if(c===-1)c=e.length}if(e[c]===`
|
|
60
|
+
`)c++;t.push({name:o,start:i.index,end:c})}return t}function Gs(e,t,r){let i=e.indexOf(r);if(i===-1)return e;let n=e.lastIndexOf(`
|
|
61
|
+
`,i)+1;if(/\bexport\b/.test(e.slice(n,i)))return e;let s=e.slice(0,i)+e.slice(i+r.length);if(new RegExp(`\\b${t}\\b`).test(s))return e;return s}function Yc(e){let t="",r=0,i=()=>{for(let s=t.length-1;s>=0;s--)if(!/\s/.test(t[s]))return t[s];return""},n=(s)=>{for(let o=s;o<e.length;o++)if(!/\s/.test(e[o]))return e[o];return""};while(r<e.length){let s=e[r];if(s==='"'||s==="'"){let o=lt(e,r);t+=e.slice(r,o),r=o;continue}if(s==="`"){let o=vt(e,r);t+=e.slice(r,o),r=o;continue}if(s==="/"&&e[r+1]==="*"){let o=Bt(e,r);t+=e.slice(r,o).replace(/\s*\n\s*/g," "),r=o;continue}if(s==="/"&&e[r+1]==="/"){let o=r+2;while(o<e.length&&e[o]!==`
|
|
62
|
+
`)o++;let a=e.slice(r+2,o).trim();if(a!==""&&!a.includes("*/"))t+=`/* ${a} */`;r=o;continue}if(s===`
|
|
63
|
+
`){let o=i(),a=n(r+1);if(o===""||a===""){r++;continue}let c=Kc(t);if(!c&&("{;,(<:=[".includes(o)||"}),]>;|&".includes(a))){if(!t.endsWith(" ")&&!t.endsWith(";"))t+=" "}else if(c){if(!t.endsWith(" "))t+=" "}else{if(t.endsWith(" "))t=t.slice(0,-1);t+="; "}r++;while(r<e.length&&(e[r]===" "||e[r]==="\t"))r++;continue}t+=s,r++}return t}function Kc(e){let t=e.length-1;while(t>=0&&/\s/.test(e[t]))t--;if(t<1||e[t]!=="/"||e[t-1]!=="*")return!1;let r=e.lastIndexOf("/*",t);if(r===-1)return!1;for(let i=r-1;i>=0;i--){let n=e[i];if(/\s/.test(n))continue;return"{;,(<:".includes(n)}return!0}function Gc(e,t){let r=[e,t].filter((i)=>i!==null);for(let i of r){let n=rn(i,"defineProps");if(!n)continue;if(n.generic){let s=n.generic;if(s.startsWith("{"))return{type:s};if(/^[A-Za-z_$][\w$]*$/.test(s)){for(let o of r){let a=Hs(o,s);if(!a)continue;let c=Dc(o,s);if(c===null)continue;return{type:c,inlinedLocal:{name:s,declText:o.slice(a.start,a.end)}}}return{type:s}}return{type:s}}if(n.arg){let s=qs(n.arg);if(s!==null)return{type:s}}}return null}function Uc(e,t){let r=[e,t].filter((i)=>i!==null);for(let i of r){let n=rn(i,"defineEmits");if(!n)continue;if(n.generic)return jc(n.generic)??n.generic;if(n.arg){let s=zs(n.arg);if(s!==null)return s}}return null}function Hc(e,t){let r=[e,t].filter((i)=>i!==null);for(let i of r){let n=rn(i,"defineExpose");if(!n||!n.arg||!n.arg.startsWith("{"))continue;let s=mr(n.arg);if(s.length===0)return null;return`{ ${s.map((o)=>{let a=o.isMethod||/=>|^\s*function\b/.test(o.value);return`${Mr(o.key)}: ${a?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function Xs(e){let t=Pc(e),r="",i=null,n=null;if(t.script){let $=Jc(t.script.content);if($.passthrough)return t.scriptSetup?`${t.script.content}
|
|
64
|
+
${t.scriptSetup.content}`:t.script.content;if(r=$.script,$.options){let x=Ys($.options,"props");if(x)i=qs(x);let S=Ys($.options,"emits");if(S)n=zs(S)}}let s=t.scriptSetup?.content??null,o=s!==null?_c(s):null,a=Gc(s,s!==null?null:r),c=a?.type??i??"{}",f=Uc(s,null)??n,u=Hc(s,null),l=a?.inlinedLocal;if(l){if(r=Gs(r,l.name,l.declText),o!==null)o=Gs(o,l.name,l.declText)}let p=[c,u??"{}"];if(f)p.push("{}","{}","{}","{}","{}",f);let h=Yc(`DefineComponent<${p.join(", ")}>`),w=[],A=Ks(r,h);if(A.trim()!=="")w.push(A);if(o&&o.trim()!==""){let $=Ks(o,h);if($.trim()!=="")w.push($)}return w.push("import type { DefineComponent } from 'vue'"),w.push(`type __DtsxComponentType = ${h}`),w.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),w.push("export default __dtsx_component__"),w.join(`
|
|
65
|
+
`)}var Vs;var Qs=ue(()=>{Vs={String:"string",Number:"number",Boolean:"boolean",Array:"unknown[]",Object:"Record<string, unknown>",Function:"(...args: any[]) => any",Symbol:"symbol",Promise:"Promise<unknown>",Date:"Date",BigInt:"bigint"}});function to(e,t,r=!0,i=!1){if(Us(t))e=Xs(e);let n=lr(e),s=`${t}:${r?1:0}:${i?1:0}`,o=jt.get(s);if(o&&o.contentHash===n)return o.lastAccess=++eo,o.declarations;let a=i?js(e,t,r):_s(e,t,r);if(jt.set(s,{declarations:a,contentHash:n,lastAccess:++eo}),jt.size>qc){let c=Math.max(1,Math.ceil(jt.size*0.1)),f=[];for(let[u,l]of jt)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)jt.delete(f[u][0])}return a}var qc=100,eo=0,jt;var ro=ue(()=>{Js();Qs();ji();jt=new Map});function Ir(e,t,r=!0,i=!1){return to(e,t,r,i)}var nn=ue(()=>{ro()});import{dirname as Am,relative as zc,resolve as vm}from"path";async function io(e,t,r){let i=new Map,n=[],s=new Set,o=0,a=0,c=0,f=[];for(let S of e){let k=t.get(S);if(!k)continue;f.push({file:S,decls:Ir(k,S,r.keepComments)})}for(let{file:S,decls:k}of f){o+=k.length;for(let R of k)if(R.kind==="import"){a++;let b=R.source||"";if(b.startsWith("."))continue;if(!i.has(b))i.set(b,{source:b,specifiers:new Map,isTypeOnly:R.isTypeOnly||!1,isSideEffect:R.isSideEffect||!1});let L=i.get(b);if(R.specifiers)for(let re of R.specifiers){let P=re.alias||re.name;if(!L.specifiers.has(P))L.specifiers.set(P,{name:re.name,alias:re.alias,isType:re.isType||!1})}if(!R.isTypeOnly)L.isTypeOnly=!1}else if(R.isExported||R.kind==="export"){if(c++,R.kind==="export"&&R.source&&(R.source.startsWith(".")||R.source.startsWith("/")))continue;if(R.name&&s.has(R.name))continue;if(R.name)s.add(R.name);n.push({declaration:R,file:S})}}let u=[];u.push("/**"),u.push(" * Bundled TypeScript declarations"),u.push(` * Generated from ${e.length} source files`),u.push(" */"),u.push("");let l=r.importOrder||["bun"],p=Array.from(i.values()),h=Array(p.length);for(let S=0;S<p.length;S++){let k=p[S].source,R=l.length;for(let b=0;b<l.length;b++)if(k.startsWith(l[b])){R=b;break}h[S]=R}let w=p.map((S,k)=>k);w.sort((S,k)=>{let R=h[S],b=h[k];if(R!==b)return R-b;return p[S].source.localeCompare(p[k].source)});let A=w.map((S)=>p[S]);for(let S of A)if(S.isSideEffect)u.push(`import '${S.source}';`);else if(S.specifiers.size>0){let k=Array.from(S.specifiers.values()).map((b)=>{let L=b.isType?"type ":"";return b.alias?`${L}${b.name} as ${b.alias}`:`${L}${b.name}`}),R=S.isTypeOnly?"type ":"";u.push(`import ${R}{ ${k.join(", ")} } from '${S.source}';`)}if(A.length>0)u.push("");let $=new Map;for(let{declaration:S,file:k}of n){if(!$.has(k))$.set(k,[]);$.get(k).push(S)}for(let[S,k]of $){let R=zc(r.cwd,S);u.push(`// From: ${R}`);for(let b of k){if(r.keepComments&&b.leadingComments)for(let L of b.leadingComments)u.push(L);u.push(no(b))}u.push("")}let x=u.join(`
|
|
66
|
+
`);return{content:x,files:e,declarationCount:o,importCount:a,exportCount:c,size:Buffer.byteLength(x,"utf8"),warnings:[]}}function no(e){if(e.text){let r=e.text.trim();if(e.isExported&&!r.startsWith("export"))r=`export ${r}`;if(!r.endsWith(";")&&!r.endsWith("}"))r+=";";return r}let t=[];if(e.isExported)t.push("export");if(e.isDefault)t.push("default");switch(e.kind){case"function":if(t.push("declare function"),t.push(e.name),e.generics)t.push(e.generics);if(t.push(`(${Xc(e.parameters)})`),e.returnType)t.push(`: ${e.returnType}`);break;case"variable":if(t.push("declare const"),t.push(e.name),e.typeAnnotation)t.push(`: ${e.typeAnnotation}`);break;case"interface":if(t.push("interface"),t.push(e.name),e.generics)t.push(e.generics);if(e.extends)t.push(`extends ${e.extends}`);if(t.push("{"),e.members)for(let r of e.members)t.push(` ${r.name}${r.typeAnnotation?`: ${r.typeAnnotation}`:""};`);t.push("}");break;case"type":if(t.push("type"),t.push(e.name),e.generics)t.push(e.generics);t.push("="),t.push(e.typeAnnotation||"unknown");break;case"class":if(t.push("declare class"),t.push(e.name),e.generics)t.push(e.generics);if(e.extends)t.push(`extends ${e.extends}`);if(e.implements&&e.implements.length>0)t.push(`implements ${e.implements.join(", ")}`);if(t.push("{"),e.members)for(let r of e.members)t.push(` ${no(r)}`);t.push("}");break;case"enum":if(t.push("declare enum"),t.push(e.name),t.push("{"),e.members){let r=e.members.map((i)=>i.value!==void 0?`${i.name} = ${i.value}`:i.name);t.push(` ${r.join(`,
|
|
67
|
+
`)}`)}t.push("}");break;default:return e.text||""}return t.join(" ")}function Xc(e){if(!e||e.length===0)return"";return e.map((t)=>{let r="";if(t.rest)r+="...";if(r+=t.name,t.optional)r+="?";if(t.type)r+=`: ${t.type}`;if(t.defaultValue)r+=` = ${t.defaultValue}`;return r}).join(", ")}var so=ue(()=>{nn()});function lo(e,t={}){let{lineEnding:r="lf",trailingNewline:i=!0,maxBlankLines:n=1,trimTrailingWhitespace:s=!0,normalizeIndentation:o=!0,indent:a={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:l=!0}=t,p=e;if(p=tf(p,r),f?.enabled!==!1)p=af(p,f||{});if(c)p=lf(p,c);if(s)p=rf(p);if(p=nf(p,n),o)p=of(p,a);if(i||l)p=sf(p);return p}function tf(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
|
|
49
68
|
`)!==-1)r=r.replace(/\r\n/g,`
|
|
50
69
|
`);if(r.indexOf("\r")!==-1)r=r.replace(/\r/g,`
|
|
51
70
|
`)}if(t==="crlf")r=r.replace(/\n/g,`\r
|
|
52
|
-
`);return r}function
|
|
71
|
+
`);return r}function rf(e){return e.split(`
|
|
53
72
|
`).map((t)=>t.replace(/[\t ]+$/,"")).join(`
|
|
54
|
-
`)}function
|
|
55
|
-
`.repeat(t+1))}function
|
|
56
|
-
`}function
|
|
57
|
-
`),
|
|
58
|
-
`)}function
|
|
59
|
-
`),
|
|
60
|
-
`)}function
|
|
61
|
-
`),
|
|
62
|
-
`)}function
|
|
73
|
+
`)}function nf(e,t){let r=new RegExp(`\\n{${t+2},}`,"g");return e.replace(r,`
|
|
74
|
+
`.repeat(t+1))}function sf(e){return`${e.replace(/\s+$/,"")}
|
|
75
|
+
`}function of(e,t){let{style:r="spaces",size:i=2}=t,n=r==="tabs"?"\t":" ".repeat(i),s=e.split(`
|
|
76
|
+
`),o=[];for(let a of s){let c=a.match(/^([\t ]*)(.*)$/);if(!c){o.push(a);continue}let[,f,u]=c;if(!u){o.push("");continue}let l=f.replace(/\t/g," "),p=Math.floor(l.length/2);o.push(n.repeat(p)+u)}return o.join(`
|
|
77
|
+
`)}function af(e,t){let{groups:r=ef,separateGroups:i=!0,alphabetize:n=!0}=t,s=e.split(`
|
|
78
|
+
`),o=[],a=[],c=-1;for(let w=0;w<s.length;w++){let A=s[w],$=oo(A);if($)o.push({line:A,source:$.source,group:$.group,isType:$.isType}),c=w;else if(o.length>0&&A.trim()==="")continue;else if(o.length>0||A.trim()!==""){if(o.length===0||w>c+1)a.push(A)}}if(o.length===0)return e;let f=new Map;for(let w of r)f.set(w,[]);for(let w of o)(f.get(w.group)||f.get("external")||[]).push(w);if(n)for(let[,w]of f)w.sort((A,$)=>{if(A.isType!==$.isType)return A.isType?1:-1;return A.source.localeCompare($.source)});let u=[],l=null;for(let w of r){let A=f.get(w)||[];if(A.length===0)continue;if(i&&l!==null)u.push("");for(let $ of A)u.push($.line);l=w}let p=s.slice(0,s.findIndex((w)=>oo(w)!==null)),h=a;while(h.length>0&&h[0].trim()==="")h.shift();return[...p,...u,"",...h].join(`
|
|
79
|
+
`)}function oo(e){let t=e.trim(),r=t.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!r){let s=t.match(/^import\s+['"]([^'"]+)['"]/);if(s)return{source:s[1],group:ao(s[1]),isType:!1};return null}let i=!!r[1],n=r[2];return{source:n,group:i?"type":ao(n),isType:i}}function ao(e){if(e.startsWith("node:"))return"builtin";let t=["assert","buffer","child_process","cluster","crypto","dgram","dns","events","fs","http","https","net","os","path","querystring","readline","stream","url","util","zlib"];if(t.includes(e)||t.includes(e.split("/")[0]))return"builtin";if(e==="."||e==="./index"||e==="./index.js"||e==="./index.ts")return"index";if(e.startsWith("./"))return"sibling";if(e.startsWith("../"))return"parent";if(e.startsWith("@/")||e.startsWith("~/")||e.startsWith("#"))return"internal";if(e.startsWith("@"))return"scoped";return"external"}function lf(e,t){let{kinds:r=Qc,alphabetize:i=!1,groupExports:n=!0}=t,s=e.split(`
|
|
80
|
+
`),o=[],a=[],c=[],f=null,u=0,l=!0,p=!1,h=[];for(let $=0;$<s.length;$++){let x=s[$],S=x.trim(),k=u,R=S.startsWith("///"),b=k===0&&!R&&(S.startsWith("//")||S.startsWith("/*"));if(p||b){if(h.push(x),!p&&S.startsWith("/*")&&!S.includes("*/"))p=!0;else if(p&&S.includes("*/"))p=!1;continue}if(k===0&&h.length>0&&S===""){h.push(x);continue}u+=(x.match(/\{/g)||[]).length,u-=(x.match(/\}/g)||[]).length;let L=cf(S);if(l&&L&&L.kind!=="import"&&!S.startsWith("//")&&!S.startsWith("/*"))l=!1;if(l){if(h.length>0){if(L?.kind==="import"||!L)a.push(...h),h.length=0}a.push(x);continue}if(L&&u<=1){if(f)o.push(f);f={lines:h.length>0?[...h,x]:[x],kind:L.kind,name:L.name,isExport:L.isExport},h.length=0}else if(f)f.lines.push(x);else{if(S==="")continue;c.push(x)}}if(f)o.push(f);if(h.length>0)c.push(...h);o.sort(($,x)=>{if(n&&$.isExport!==x.isExport)return $.isExport?-1:1;let S=r.indexOf($.kind),k=r.indexOf(x.kind),R=S>=0?S:r.length,b=k>=0?k:r.length;if(R!==b)return R-b;if(i)return $.name.localeCompare(x.name);return 0});let w=[...a],A=null;for(let $ of o){if(A!==null&&$.kind!==A)w.push("");w.push(...$.lines),A=$.kind}if(c.length>0)w.push(""),w.push(...c);return w.join(`
|
|
81
|
+
`)}function cf(e){let t=e.startsWith("export "),r=t?e.slice(7):e;if(e.startsWith("import "))return{kind:"import",name:e.match(/from\s+['"]([^'"]+)['"]/)?.[1]||"",isExport:!1};if(r.startsWith("type ")||r.startsWith("declare type "))return{kind:"type",name:r.match(/type\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("interface ")||r.startsWith("declare interface "))return{kind:"interface",name:r.match(/interface\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("class ")||r.startsWith("abstract class ")||r.startsWith("declare class ")||r.startsWith("declare abstract class "))return{kind:"class",name:r.match(/class\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("enum ")||r.startsWith("const enum ")||r.startsWith("declare enum ")||r.startsWith("declare const enum "))return{kind:"enum",name:r.match(/enum\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("function ")||r.startsWith("async function ")||r.startsWith("declare function ")||r.startsWith("declare async function "))return{kind:"function",name:r.match(/function\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("const ")||r.startsWith("let ")||r.startsWith("var ")||r.startsWith("declare const ")||r.startsWith("declare let ")||r.startsWith("declare var "))return{kind:"variable",name:r.match(/(?:const|let|var)\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("namespace ")||r.startsWith("declare namespace "))return{kind:"namespace",name:r.match(/namespace\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("module ")||r.startsWith("declare module "))return{kind:"module",name:r.match(/module\s+['"]?(\w+)['"]?/)?.[1]||"",isExport:t};if(e.startsWith("export {")||e.startsWith("export *")||e.startsWith("export type {"))return{kind:"export",name:"",isExport:!0};return null}var Qc,ef;var co=ue(()=>{Qc=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],ef=["builtin","external","scoped","internal","parent","sibling","index","type"]});async function ff(){if(Br!==null)return Br;try{return xt=await import("prettier"),Br=!0,!0}catch{return Br=!1,!1}}async function uf(e,t){if(!xt)return null;try{if(t&&xt.resolveConfig){let r=await xt.resolveConfig(t);if(r)return r}if(e&&xt.resolveConfig){let r=await xt.resolveConfig(e);if(r)return r}return null}catch{return null}}async function hf(e,t){if(!xt)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return xt.format(e,r)}function df(e,t={}){let{indentSize:r=2,useTabs:i=!1,maxLineWidth:n=100,trailingNewline:s=!0,normalizeWhitespace:o=!0,sortImports:a=!0,groupImports:c=!0}=t,f=e,u=i?"\t":" ".repeat(r);if(f.indexOf(`\r
|
|
63
82
|
`)!==-1)f=f.replace(/\r\n/g,`
|
|
64
|
-
`);if(
|
|
83
|
+
`);if(o){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
|
|
65
84
|
|
|
66
85
|
|
|
67
86
|
`)!==-1)f=f.replace(/\n{3,}/g,`
|
|
68
87
|
|
|
69
|
-
`);f=
|
|
88
|
+
`);f=mf(f,u)}if(a||c)f=gf(f,{sort:a,group:c});if(n>0)f=yf(f,n,u);if(s&&!f.endsWith(`
|
|
70
89
|
`))f+=`
|
|
71
|
-
`;return f}function
|
|
72
|
-
`),i=[];for(let n of r){let s=n.match(/^(\s*)(.*)$/);if(!s){i.push(n);continue}let[,a
|
|
73
|
-
`)}function
|
|
74
|
-
`),i=[],n=[],s=!1,
|
|
75
|
-
`)}function
|
|
76
|
-
`),n=[];for(let s of i){if(s.length<=t){n.push(s);continue}if(s.trimStart().startsWith("import ")){n.push(s);continue}let
|
|
77
|
-
`)}function vc(e,t,r,i){let n=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!n)return[e];let[,,s,a,o,c]=n,f=o.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${r}${s}${a}`,...f.map((u)=>`${i}${u.trim()};`),`${r}${c.trim()}`]}function Ac(e,t,r,i){let n=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!n)return[e];let[,,s,a]=n,o=a.split(/\s*\|\s*/).filter((c)=>c.trim());if(o.length<=2)return[e];return[`${r}${s}`,...o.map((c,f)=>`${i}${f>0?"| ":" "}${c.trim()}`)]}async function _s(e,t={},r){let i=[];if(t.usePrettier!==!1){if(await mc())try{let n={...await gc(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await pc(e,n),usedPrettier:!0}}catch(n){i.push(`Prettier formatting failed: ${n}. Using built-in formatter.`)}else if(t.usePrettier===!0)i.push("Prettier requested but not available. Using built-in formatter.")}return{content:yc(e,t.builtIn),usedPrettier:!1,warnings:i.length>0?i:void 0}}var Tr=null,bt=null;var Zs=()=>{};function Dt(e){return Vs[e]>=Vs[Rr]}function Oc(){if(!Ec)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Sc(e,t){let r=Oc();if(e||r)return[`${r}${e}`,...t];return t}function It(e,t,r){let i=Sc(t,r);if(Js){Js(e,...i);return}switch(e){case"debug":console.debug(...i);break;case"info":console.log(...i);break;case"warn":console.warn(...i);break;case"error":console.error(...i);break}}function Ks(e){return{debug:(...t)=>{if(Dt("debug"))It("debug",e,t)},info:(...t)=>{if(Dt("info"))It("info",e,t)},warn:(...t)=>{if(Dt("warn"))It("warn",e,t)},error:(...t)=>{if(Dt("error"))It("error",e,t)},setLevel:(t)=>{Rr=t},getLevel:()=>Rr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return Ks(r)},time:(t)=>{let r=performance.now();return()=>{let i=performance.now()-r;if(Dt("debug"))It("debug",e,[`${t}: ${i.toFixed(2)}ms`])}},progress:(t)=>{if(Dt("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else It("info",e,[t])}}}function Ui(e){Rr=e}var Vs,Rr="info",xc="[dtsx]",Ec=!1,Js=null,V;var Us=he(()=>{Vs={debug:0,info:1,warn:2,error:3,silent:4};V=Ks(xc)});import kc from"process";import{existsSync as Gs,statSync as Ys}from"fs";import{existsSync as Tc,mkdirSync as Dd,readdirSync as Id,readFileSync as Rc,writeFileSync as Ld}from"fs";import{homedir as Lt}from"os";import{dirname as Md,resolve as Ye}from"path";import fi from"process";import{existsSync as Hs,statSync as qs}from"fs";import{existsSync as dn,mkdirSync as Nc,readdirSync as Wc,writeFileSync as Pc}from"fs";import{homedir as jt}from"os";import{dirname as zs,resolve as _e}from"path";import Ot from"process";import{join as Fc,relative as Dc,resolve as Xs}from"path";import qr from"process";import{existsSync as Pa,mkdirSync as qd,readdirSync as zd,writeFileSync as Xd}from"fs";import{homedir as Gi}from"os";import{dirname as tm,resolve as Me}from"path";import lr from"process";import{join as Ic,relative as Lc,resolve as Qs}from"path";import zr from"process";import{existsSync as Fa,mkdirSync as am,readdirSync as om,writeFileSync as lm}from"fs";import{dirname as fm,resolve as Xr}from"path";import mn from"process";import{Buffer as vt}from"buffer";import{createCipheriv as jc,createDecipheriv as Bc,randomBytes as Yi}from"crypto";import{closeSync as Hi,createReadStream as ea,createWriteStream as Mc,existsSync as qi,fsyncSync as ta,openSync as ra,writeFileSync as _c}from"fs";import{access as Zc,constants as ia,mkdir as Vc,readdir as Nr,rename as na,stat as Bt,unlink as Wr,writeFile as zi}from"fs/promises";import{join as Mt}from"path";import De from"process";import{pipeline as Jc}from"stream/promises";import{createGzip as sa}from"zlib";import _t from"process";import ft from"process";import{Buffer as ot}from"buffer";import{createCipheriv as Kc,createDecipheriv as Uc,randomBytes as Xi}from"crypto";import{closeSync as Qi,createReadStream as aa,createWriteStream as Gc,existsSync as Pr,fsyncSync as oa,openSync as la,writeFileSync as Yc}from"fs";import{access as Hc,constants as ca,mkdir as qc,readdir as Fr,rename as fa,stat as Zt,unlink as Dr,writeFile as en}from"fs/promises";import{isAbsolute as zc,join as Vt,resolve as Xc}from"path";import se from"process";import{pipeline as Qc}from"stream/promises";import{createGzip as ua}from"zlib";import Jt from"process";import ut from"process";import Ir from"process";import{existsSync as Lr}from"fs";import{resolve as tn}from"path";import{existsSync as ef}from"fs";import{existsSync as tf,readdirSync as rf}from"fs";import{extname as rn,resolve as ha}from"path";import nf from"process";import{join as sf,relative as af,resolve as da}from"path";import Qr from"process";import{Buffer as lt}from"buffer";import{createCipheriv as of,createDecipheriv as lf,randomBytes as nn}from"crypto";import{closeSync as sn,createReadStream as ma,createWriteStream as cf,existsSync as jr,fsyncSync as ga,openSync as pa,writeFileSync as ff}from"fs";import{access as uf,constants as ya,mkdir as hf,readdir as Br,rename as wa,stat as Kt,unlink as Mr,writeFile as an}from"fs/promises";import{isAbsolute as df,join as Ut,resolve as mf}from"path";import ae from"process";import{pipeline as gf}from"stream/promises";import{createGzip as $a}from"zlib";import Gt from"process";import ht from"process";import _r from"process";import{existsSync as Zr}from"fs";import{resolve as on}from"path";import{existsSync as pf}from"fs";class Da{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],[,i])=>r.timestamp.getTime()-i.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,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Gs(e))return!0;return Ys(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,i){try{let n=Gs(r)?Ys(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}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((i,n)=>i+n.size,0),r=e.map((i)=>i.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 i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Ia{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:n,...r}),s}catch(s){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:n,...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((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function $f(e,t){this[e]=wf.bind(null,t)}class On{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],[,i])=>r.timestamp.getTime()-i.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,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Hs(e))return!0;return qs(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,i){try{let n=Hs(r)?qs(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}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((i,n)=>i+n.size,0),r=e.map((i)=>i.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 i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Sn{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:n,...r}),s}catch(s){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:n,...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((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function vf(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function Af(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function xf(e){return e.getStats().size*2}function kn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ge(t[0])&&"id"in t[0]&&t[0].id===3&&ge(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ge(t)&&ge(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(ge(e)&&"arr"in e&&Array.isArray(e.arr)&&ge(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ge(t[0])&&ge(e[0])){let i=[...t];for(let n of e)if(ge(n)&&"name"in n){if(!i.find((s)=>ge(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(ge(n)&&"path"in n){if(!i.find((s)=>ge(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>ti(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!ge(t)||!ge(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(ge(n)&&ge(r[i]))r[i]=kn(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&ge(n[0])&&ge(r[i][0])){let s=[...n];for(let a of r[i])if(ge(a)&&"name"in a){if(!s.find((o)=>ge(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(ge(a)&&"path"in a){if(!s.find((o)=>ge(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>ti(o,a)))s.push(a);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let a of r[i])if(!s.includes(a))s.push(a);r[i]=s}else r[i]=n;else r[i]=n}return r}function ti(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(!ti(e[r],t[r]))return!1;return!0}if(ge(e)&&ge(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ti(e[n],t[n]))return!1}return!0}return!1}function ge(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Ef(e,t){if(!Fa(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return kn(t,i)}catch{return null}}catch{return null}}async function Of({name:e="",cwd:t,defaultConfig:r}){let i=t||mn.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let a of s)for(let o of n){let c=Xr(i,`${a}${o}`),f=await Ef(c,r);if(f!==null)return f}try{let a=Xr(i,"package.json");if(Fa(a)){let o=(await import(a))[e];if(o&&typeof o==="object"&&!Array.isArray(o))try{return kn(r,o)}catch{}}}catch{}return r}function Sf(e,t={}){let r=zr.cwd();while(r.includes("storage"))r=Qs(r,"..");let i=Qs(r,e||"");if(t?.relative)return Lc(zr.cwd(),i);return i}async function kf(){try{let e=await Of({name:"clarity",defaultConfig:Ur,cwd:zr.cwd(),endpoint:"",headers:{}});return{...Ur,...e}}catch{return Ur}}function ve(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Tf(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ft<"u"){let e=ft.type;if(e==="renderer"||e==="worker")return!1;return!!(ft.versions&&(ft.versions.node||ft.versions.bun))}return!1}class ja{async format(e){let t=await Tf(),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:_t.pid,hostname:t(),environment:_t.env.NODE_ENV||"development",platform:_t.platform,version:_t.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_t.env.NODE_ENV||_t.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ri{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={...pn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ja,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??De.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Gr,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Gr};return{...Gr,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:pn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await Zc(this.config.logDirectory,ia.F_OK|ia.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Vc(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:vt.from(e);try{if(!qi(this.currentLogFile))await zi(this.currentLogFile,"",{mode:420});if(i=ra(this.currentLogFile,"a",420),_c(i,o,{flag:"a"}),ta(i),i!==void 0)Hi(i),i=void 0;if((await Bt(this.currentLogFile)).size===0){if(await zi(this.currentLogFile,o,{flag:"w",mode:420}),(await Bt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=a*2**n;await new Promise((p)=>setTimeout(p,l)),n++;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{Hi(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(n===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let c=a*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 Mt(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 Mt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Mt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ve())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return Yi(16).toString("hex")}generateKey(){return Yi(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=Yi(16),i=jc("aes-256-gcm",t,r),n=vt.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:vt.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=sa(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(vt.from(vt.concat(n)))),i.on("error",r),i.write(e),i.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(ve())return;let e=await Bt(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Nr(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Bt(r).catch(()=>null))try{if(await na(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await Wr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await zi(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Bt(r).catch(()=>null))await na(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Nr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Wr(Mt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=ea(e),i=Mc(t),n=sa();await Jc(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}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()})),qi(this.currentLogFile))try{let e=ra(this.currentLogFile,"r+");ta(e),Hi(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(!ve()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Nr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Wr(Mt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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?ue.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=De.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${ue.cyan(n)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);if(this.fancy&&!ve()){let f=Ya[e],u=this.options.showTags!==!1&&this.name?ue.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:ue.gray(a),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:a,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:ue.green(a),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:a,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:a,level:e}),console.error(l),o){let p=o.split(`
|
|
78
|
-
`);for(let
|
|
79
|
-
`;if(
|
|
80
|
-
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!
|
|
81
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
82
|
-
`),
|
|
83
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(
|
|
84
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||
|
|
85
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ve()||!De.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(ve()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Nr(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Mt(this.config.logDirectory,i);if(e.before)try{if((await Bt(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 i of r)try{await Wr(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Kr(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&oe(t[0])&&"id"in t[0]&&t[0].id===3&&oe(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(oe(t)&&oe(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(oe(e)&&"arr"in e&&Array.isArray(e.arr)&&oe(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&oe(t[0])&&oe(e[0])){let i=[...t];for(let n of e)if(oe(n)&&"name"in n){if(!i.find((s)=>oe(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(oe(n)&&"path"in n){if(!i.find((s)=>oe(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>ii(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!oe(t)||!oe(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(oe(n)&&oe(r[i]))r[i]=Kr(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&oe(n[0])&&oe(r[i][0])){let s=[...n];for(let a of r[i])if(oe(a)&&"name"in a){if(!s.find((o)=>oe(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(oe(a)&&"path"in a){if(!s.find((o)=>oe(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>ii(o,a)))s.push(a);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let a of r[i])if(!s.includes(a))s.push(a);r[i]=s}else r[i]=n;else r[i]=n}return r}function Tn(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Kr(e,t);if(Array.isArray(e))return r==="replace"?t:Kr(e,t);if(!oe(t)||!oe(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],a=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(a))if(r==="replace")i[n]=s;else i[n]=Kr(a,s);else if(oe(s)&&oe(a))i[n]=Tn(a,s,r);else i[n]=s}return i}function ii(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(!ii(e[r],t[r]))return!1;return!0}if(oe(e)&&oe(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ii(e[n],t[n]))return!1}return!0}return!1}function oe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Vr(e,t,r="replace"){if(!Pa(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Tn(t,n,r)}catch{return null}}catch{return null}}function Rf(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],p=(v)=>v.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${l.map(p).join("_")}`,C=`${i}_${l.map((v)=>v.toUpperCase()).join("_")}`;if(r)Le.info(`Checking environment variable ${d} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,l);else{let v=lr.env[d]||lr.env[C];if(v!==void 0){if(r)Le.info(`Using environment variable ${v?d:C} for config ${e}.${l.join(".")}`);if(typeof u==="number")c[f]=Number(v);else if(typeof u==="boolean")c[f]=v.toLowerCase()==="true";else if(Array.isArray(u))try{let w=JSON.parse(v);if(Array.isArray(w))c[f]=w;else c[f]=v.split(",").map((x)=>x.trim())}catch{c[f]=v.split(",").map((w)=>w.trim())}else c[f]=v}}}return c}return s(n)}async function Nf({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:a=!0,arrayStrategy:o="replace"}){let c=a&&typeof n==="object"&&n!==null&&!Array.isArray(n)?Rf(e,n,s):n,f=r||lr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Le.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),p=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],v=Array.from(new Set([f,Me(f,"config"),Me(f,".config"),i?Me(f,i):void 0].filter(Boolean)));for(let w of v){if(s)Le.info(`Searching for configuration in: ${w}`);let x=[Me(f,"config"),Me(f,".config")].concat(i?[Me(f,i)]:[]).includes(w)?[...l,...p,...d,...C]:[...p,...l,...C,...d];for(let k of x)for(let S of u){let T=Me(w,`${k}${S}`),b=await Vr(T,c,o);if(b!==null){if(s)Le.success(`Configuration loaded from: ${T}`);return b}}}if(e){let w=Me(Gi(),".config",e),x=["config",`${e}.config`];if(t)x.push(`${t}.config`);if(s)Le.info(`Checking user config directory: ${w}`);for(let k of x)for(let S of u){let T=Me(w,`${k}${S}`),b=await Vr(T,c,o);if(b!==null){if(s)Le.success(`Configuration loaded from user config directory: ${T}`);return b}}}if(e){let w=Me(Gi(),".config"),x=[`.${e}.config`];if(t)x.push(`.${t}.config`);if(s)Le.info(`Checking user config directory for dotfile configs: ${w}`);for(let k of x)for(let S of u){let T=Me(w,`${k}${S}`),b=await Vr(T,c,o);if(b!==null){if(s)Le.success(`Configuration loaded from user config directory dotfile: ${T}`);return b}}}if(e){let w=Gi(),x=[`.${e}.config`,`.${e}`];if(t)x.push(`.${t}.config`),x.push(`.${t}`);if(s)Le.info(`Checking user home directory for dotfile configs: ${w}`);for(let k of x)for(let S of u){let T=Me(w,`${k}${S}`),b=await Vr(T,c,o);if(b!==null){if(s)Le.success(`Configuration loaded from user home directory: ${T}`);return b}}}try{let w=Me(f,"package.json");if(Pa(w)){let x=await import(w),k=x[e];if(!k&&t){if(k=x[t],k&&s)Le.success(`Using alias "${t}" configuration from package.json`)}if(k&&typeof k==="object"&&!Array.isArray(k))try{if(s)Le.success(`Configuration loaded from package.json: ${k===x[e]?e:t}`);return Tn(c,k,o)}catch(S){if(s)Le.warn("Failed to merge package.json config:",S)}}}catch(w){if(s)Le.warn("Failed to load package.json:",w)}if(s)Le.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Wf(e,t={}){let r=qr.cwd();while(r.includes("storage"))r=Xs(r,"..");let i=Xs(r,e||"");if(t?.relative)return Dc(qr.cwd(),i);return i}async function Pf(){try{let e=await Nf({name:"clarity",alias:"logging",defaultConfig:Yr,cwd:qr.cwd()});return{...Yr,...e||{}}}catch{return Yr}}function ke(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ff(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ut<"u"){let e=ut.type;if(e==="renderer"||e==="worker")return!1;return!!(ut.versions&&(ut.versions.node||ut.versions.bun))}return!1}class Ba{async format(e){let t=await Ff(),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:Jt.pid,hostname:t(),environment:Jt.env.NODE_ENV||"development",platform:Jt.platform,version:Jt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Jt.env.NODE_ENV||Jt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ni{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={...yn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ba,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??se.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{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{...Hr,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Hr};return{...Hr,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:yn.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(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ke()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await Hc(this.config.logDirectory,ca.F_OK|ca.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await qc(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ot.from(e);try{if(!Pr(this.currentLogFile))await en(this.currentLogFile,"",{mode:420});if(i=la(this.currentLogFile,"a",420),Yc(i,o,{flag:"a"}),oa(i),i!==void 0)Qi(i),i=void 0;if((await Zt(this.currentLogFile)).size===0){if(await en(this.currentLogFile,o,{flag:"w",mode:420}),(await Zt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=a*2**n;await new Promise((p)=>setTimeout(p,l)),n++;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{Qi(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(n===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let c=a*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 Vt(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 Vt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Vt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ke())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return Xi(16).toString("hex")}generateKey(){return Xi(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=Xi(16),i=Kc("aes-256-gcm",t,r),n=ot.isBuffer(e)?e:ot.from(e,"utf8"),s=i.update(n),a=i.final(),o=s.length+a.length,c=i.getAuthTag(),f=ot.allocUnsafe(16+o+16);return r.copy(f,0),s.copy(f,16),a.copy(f,16+s.length),c.copy(f,16+o),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=ua(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(ot.from(ot.concat(n)))),i.on("error",r),i.write(e),i.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(ke())return;if(!this.shouldWriteToFile())return;let e=await Zt(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Fr(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Zt(r).catch(()=>null))try{if(await fa(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await Dr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await en(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Zt(r).catch(()=>null))await fa(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Fr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Dr(Vt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=aa(e),i=Gc(t),n=ua();await Qc(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(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()})),Pr(this.currentLogFile))try{let e=la(this.currentLogFile,"r+");oa(e),Qi(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(!ke()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Fr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Dr(Vt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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()?ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ke())return!1;let e=typeof se.env.NO_COLOR<"u",t=se.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof se.stderr<"u"&&se.stderr.isTTY||typeof se.stdout<"u"&&se.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=se.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${ee.cyan(n)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=ee.underline(ee.blue(i)),a=this.toAbsoluteFilePath(n);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${o}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>ee.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>ee.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>ee.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>ee.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>ee.strikethrough(i)),t}supportsHyperlinks(){if(ke())return!1;let e=se.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=se.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(zc(t)||t.startsWith("./")||t.startsWith("../"))t=Xc(t);else return null;return Pr(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 i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":Ha[e],p=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:ee.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:ee.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.error(d),o){let C=o.split(`
|
|
86
|
-
`);for(let
|
|
87
|
-
`;if(
|
|
88
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
89
|
-
`);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
90
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:
|
|
91
|
-
`),c=Math.max(...
|
|
92
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
93
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!se.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=ee.green("\u2501".repeat(i)),
|
|
94
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
90
|
+
`;return f}function mf(e,t){let r=e.split(`
|
|
91
|
+
`),i=[];for(let n of r){let s=n.match(/^(\s*)(.*)$/);if(!s){i.push(n);continue}let[,o,a]=s;if(!a){i.push("");continue}let c=o.replace(/\t/g," ").length,f=Math.floor(c/2);i.push(t.repeat(f)+a)}return i.join(`
|
|
92
|
+
`)}function gf(e,t){let r=e.split(`
|
|
93
|
+
`),i=[],n=[],s=!1,o=0;for(let c=0;c<r.length;c++){let f=r[c],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){s=!0,o=c;let l=u[1];i.push({line:f,source:u[2],isType:l.startsWith("import type ")||l.startsWith("import type\t")})}else if(s&&f.trim()==="")continue;else{if(s)s=!1;n.push(f)}}if(i.length===0)return e;if(t.sort)i.sort((c,f)=>{if(c.isType!==f.isType)return c.isType?1:-1;return pf(c.source,f.source)});let a;if(t.group){let c=[],f=[],u=[],l=[],p=[];for(let h=0;h<i.length;h++){let w=i[h],A=w.source;if(A.charCodeAt(0)===46)p.push(w);else if(A.startsWith("node:"))c.push(w);else if(A.charCodeAt(0)===64)l.push(w);else if(A.includes("/"))u.push(w);else f.push(w)}a=[...c.map((h)=>h.line),...c.length>0&&f.length>0?[""]:[],...f.map((h)=>h.line),...(c.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((h)=>h.line),...l.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...l.map((h)=>h.line),...p.length>0?[""]:[],...p.map((h)=>h.line)]}else a=i.map((c)=>c.line);return[...a,"",...n].join(`
|
|
94
|
+
`)}function pf(e,t){let r=e.startsWith("node:"),i=t.startsWith("node:");if(r!==i)return r?-1:1;let n=e.startsWith("."),s=t.startsWith(".");if(n!==s)return n?1:-1;return e.localeCompare(t)}function yf(e,t,r){let i=e.split(`
|
|
95
|
+
`),n=[];for(let s of i){if(s.length<=t){n.push(s);continue}if(s.trimStart().startsWith("import ")){n.push(s);continue}let o=s.match(/^(\s*)/)?.[1]||"",a=o+r;if(s.includes("{")&&s.includes("}")){let c=$f(s,t,o,a);n.push(...c);continue}if(s.includes(" | ")){let c=wf(s,t,o,a);n.push(...c);continue}n.push(s)}return n.join(`
|
|
96
|
+
`)}function $f(e,t,r,i){let n=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!n)return[e];let[,,s,o,a,c]=n,f=a.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${r}${s}${o}`,...f.map((u)=>`${i}${u.trim()};`),`${r}${c.trim()}`]}function wf(e,t,r,i){let n=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!n)return[e];let[,,s,o]=n,a=o.split(/\s*\|\s*/).filter((c)=>c.trim());if(a.length<=2)return[e];return[`${r}${s}`,...a.map((c,f)=>`${i}${f>0?"| ":" "}${c.trim()}`)]}async function fo(e,t={},r){let i=[];if(t.usePrettier!==!1){if(await ff())try{let n={...await uf(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await hf(e,n),usedPrettier:!0}}catch(n){i.push(`Prettier formatting failed: ${n}. Using built-in formatter.`)}else if(t.usePrettier===!0)i.push("Prettier requested but not available. Using built-in formatter.")}return{content:df(e,t.builtIn),usedPrettier:!1,warnings:i.length>0?i:void 0}}var Br=null,xt=null;var uo=()=>{};function _t(e){return ho[e]>=ho[Lr]}function Af(){if(!bf)return"";return`[${new Date().toISOString().slice(11,23)}] `}function vf(e,t){let r=Af();if(e||r)return[`${r}${e}`,...t];return t}function Zt(e,t,r){let i=vf(t,r);if(mo){mo(e,...i);return}switch(e){case"debug":console.debug(...i);break;case"info":console.log(...i);break;case"warn":console.warn(...i);break;case"error":console.error(...i);break}}function go(e){return{debug:(...t)=>{if(_t("debug"))Zt("debug",e,t)},info:(...t)=>{if(_t("info"))Zt("info",e,t)},warn:(...t)=>{if(_t("warn"))Zt("warn",e,t)},error:(...t)=>{if(_t("error"))Zt("error",e,t)},setLevel:(t)=>{Lr=t},getLevel:()=>Lr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return go(r)},time:(t)=>{let r=performance.now();return()=>{let i=performance.now()-r;if(_t("debug"))Zt("debug",e,[`${t}: ${i.toFixed(2)}ms`])}},progress:(t)=>{if(_t("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Zt("info",e,[t])}}}function sn(e){Lr=e}var ho,Lr="info",Cf="[dtsx]",bf=!1,mo=null,J;var po=ue(()=>{ho={debug:0,info:1,warn:2,error:3,silent:4};J=go(Cf)});import xf from"process";import{existsSync as yo,statSync as $o}from"fs";import{existsSync as Ef,mkdirSync as Nm,readdirSync as Wm,readFileSync as Of,writeFileSync as Fm}from"fs";import{homedir as Jt}from"os";import{dirname as Mm,resolve as He}from"path";import wi from"process";import{existsSync as wo,statSync as Co}from"fs";import{existsSync as En,mkdirSync as kf,readdirSync as Sf,writeFileSync as Tf}from"fs";import{homedir as Vt}from"os";import{dirname as bo,resolve as Ze}from"path";import Rt from"process";import{join as Rf,relative as Nf,resolve as Ao}from"path";import si from"process";import{existsSync as ia,mkdirSync as Km,readdirSync as Gm,writeFileSync as Um}from"fs";import{homedir as on}from"os";import{dirname as zm,resolve as _e}from"path";import pr from"process";import{join as Wf,relative as Ff,resolve as vo}from"path";import oi from"process";import{existsSync as na,mkdirSync as rg,readdirSync as ig,writeFileSync as ng}from"fs";import{dirname as og,resolve as ai}from"path";import On from"process";import{Buffer as Et}from"buffer";import{createCipheriv as Pf,createDecipheriv as Df,randomBytes as an}from"crypto";import{closeSync as ln,createReadStream as xo,createWriteStream as Mf,existsSync as cn,fsyncSync as Eo,openSync as Oo,writeFileSync as If}from"fs";import{access as Bf,constants as ko,mkdir as Lf,readdir as jr,rename as So,stat as Yt,unlink as _r,writeFile as fn}from"fs/promises";import{join as Kt}from"path";import Me from"process";import{pipeline as jf}from"stream/promises";import{createGzip as To}from"zlib";import Gt from"process";import ht from"process";import{Buffer as ct}from"buffer";import{createCipheriv as _f,createDecipheriv as Zf,randomBytes as un}from"crypto";import{closeSync as hn,createReadStream as Ro,createWriteStream as Jf,existsSync as Zr,fsyncSync as No,openSync as Wo,writeFileSync as Vf}from"fs";import{access as Yf,constants as Fo,mkdir as Kf,readdir as Jr,rename as Po,stat as Ut,unlink as Vr,writeFile as dn}from"fs/promises";import{isAbsolute as Gf,join as Ht,resolve as Uf}from"path";import se from"process";import{pipeline as Hf}from"stream/promises";import{createGzip as Do}from"zlib";import qt from"process";import dt from"process";import Yr from"process";import{existsSync as Kr}from"fs";import{resolve as mn}from"path";import{existsSync as qf}from"fs";import{existsSync as zf,readdirSync as Xf}from"fs";import{extname as gn,resolve as Mo}from"path";import Qf from"process";import{join as eu,relative as tu,resolve as Io}from"path";import li from"process";import{Buffer as ft}from"buffer";import{createCipheriv as ru,createDecipheriv as iu,randomBytes as pn}from"crypto";import{closeSync as yn,createReadStream as Bo,createWriteStream as nu,existsSync as Gr,fsyncSync as Lo,openSync as jo,writeFileSync as su}from"fs";import{access as ou,constants as _o,mkdir as au,readdir as Ur,rename as Zo,stat as zt,unlink as Hr,writeFile as $n}from"fs/promises";import{isAbsolute as lu,join as Xt,resolve as cu}from"path";import oe from"process";import{pipeline as fu}from"stream/promises";import{createGzip as Jo}from"zlib";import Qt from"process";import mt from"process";import qr from"process";import{existsSync as zr}from"fs";import{resolve as wn}from"path";import{existsSync as uu}from"fs";class sa{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],[,i])=>r.timestamp.getTime()-i.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,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{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),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!yo(e))return!0;return $o(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,i){try{let n=yo(r)?$o(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}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((i,n)=>i+n.size,0),r=e.map((i)=>i.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 i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class oa{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...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((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function mu(e,t){this[e]=du.bind(null,t)}class Bn{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],[,i])=>r.timestamp.getTime()-i.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,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{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),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!wo(e))return!0;return Co(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,i){try{let n=wo(r)?Co(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}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((i,n)=>i+n.size,0),r=e.map((i)=>i.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 i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Ln{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...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((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function yu(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function $u(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function wu(e){return e.getStats().size*2}function jn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&$e(t[0])&&"id"in t[0]&&t[0].id===3&&$e(t[1])&&"id"in t[1]&&t[1].id===4)return t;if($e(t)&&$e(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($e(e)&&"arr"in e&&Array.isArray(e.arr)&&$e(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&$e(t[0])&&$e(e[0])){let i=[...t];for(let n of e)if($e(n)&&"name"in n){if(!i.find((s)=>$e(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if($e(n)&&"path"in n){if(!i.find((s)=>$e(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>fi(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!$e(t)||!$e(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if($e(n)&&$e(r[i]))r[i]=jn(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&$e(n[0])&&$e(r[i][0])){let s=[...n];for(let o of r[i])if($e(o)&&"name"in o){if(!s.find((a)=>$e(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if($e(o)&&"path"in o){if(!s.find((a)=>$e(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>fi(a,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function fi(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(!fi(e[r],t[r]))return!1;return!0}if($e(e)&&$e(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!fi(e[n],t[n]))return!1}return!0}return!1}function $e(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Cu(e,t){if(!na(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return jn(t,i)}catch{return null}}catch{return null}}async function bu({name:e="",cwd:t,defaultConfig:r}){let i=t||On.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let a of n){let c=ai(i,`${o}${a}`),f=await Cu(c,r);if(f!==null)return f}try{let o=ai(i,"package.json");if(na(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return jn(r,a)}catch{}}}catch{}return r}function Au(e,t={}){let r=oi.cwd();while(r.includes("storage"))r=vo(r,"..");let i=vo(r,e||"");if(t?.relative)return Ff(oi.cwd(),i);return i}async function vu(){try{let e=await bu({name:"clarity",defaultConfig:ti,cwd:oi.cwd(),endpoint:"",headers:{}});return{...ti,...e}}catch{return ti}}function Ae(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xu(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ht<"u"){let e=ht.type;if(e==="renderer"||e==="worker")return!1;return!!(ht.versions&&(ht.versions.node||ht.versions.bun))}return!1}class la{async format(e){let t=await xu(),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:Gt.pid,hostname:t(),environment:Gt.env.NODE_ENV||"development",platform:Gt.platform,version:Gt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Gt.env.NODE_ENV||Gt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ui{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={...Sn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new la,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??Me.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ri,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ri};return{...ri,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Sn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await Bf(this.config.logDirectory,ko.F_OK|ko.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Lf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Et.from(e);try{if(!cn(this.currentLogFile))await fn(this.currentLogFile,"",{mode:420});if(i=Oo(this.currentLogFile,"a",420),If(i,a,{flag:"a"}),Eo(i),i!==void 0)ln(i),i=void 0;if((await Yt(this.currentLogFile)).size===0){if(await fn(this.currentLogFile,a,{flag:"w",mode:420}),(await Yt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=o*2**n;await new Promise((p)=>setTimeout(p,l)),n++;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{ln(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(n===s-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}n++;let c=o*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 Kt(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 Kt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Kt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ae())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return an(16).toString("hex")}generateKey(){return an(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=an(16),i=Pf("aes-256-gcm",t,r),n=Et.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:Et.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=To(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Et.from(Et.concat(n)))),i.on("error",r),i.write(e),i.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(Ae())return;let e=await Yt(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await jr(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Yt(r).catch(()=>null))try{if(await So(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await _r(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await fn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Yt(r).catch(()=>null))await So(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await jr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await _r(Kt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=xo(e),i=Mf(t),n=To();await jf(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}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()})),cn(this.currentLogFile))try{let e=Oo(this.currentLogFile,"r+");Eo(e),ln(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(!Ae()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await jr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await _r(Kt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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?me.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(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(i)h.push(i.replace(/[[\]]/g,""));return h.push(n),h.join(" ")}let c=Me.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${me.cyan(n)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!Ae()){let f=$a[e],u=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:me.gray(o),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:o,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:me.green(o),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:o,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:o,level:e}),console.error(l),a){let p=a.split(`
|
|
97
|
+
`);for(let h of p)if(h.trim()&&!h.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:me.gray(` ${h}`),level:e,showTimestamp:!1}))}break}}else if(!Ae()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let c=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
98
|
+
`;if(a)c+=`${a}
|
|
99
|
+
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!Ae()){let r=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:me.blue("\u25D0"),tag:r,message:`${me.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
100
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!Ae()){let f=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:me.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ae())console.error(c.trim());await this.writeToFile(c)}}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 ui(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(Ae())throw Error("createReadStream is not supported in browser environments");if(!cn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return xo(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 i=Et.isBuffer(e)?e:Et.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),o=i.slice(16,-16),a=Df("aes-256-gcm",r,n);return a.setAuthTag(s),Et.concat([a.update(o),a.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ae()}isServerMode(){return!Ae()}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),i=this.formatFileTimestamp(t);if(this.fancy&&!Ae()){let s=e.split(`
|
|
101
|
+
`),o=Math.max(...s.map((u)=>u.length))+2,a=`\u250C${"\u2500".repeat(o)}\u2510`,c=`\u2514${"\u2500".repeat(o)}\u2518`,f=s.map((u)=>{let l=" ".repeat(o-u.length-2);return`\u2502 ${u}${l} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:me.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:me.cyan(a)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:me.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:me.cyan(c),showTimestamp:!1}))}else if(!Ae())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let n=`${i} ${this.environment}.INFO: [BOX] ${e}
|
|
102
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(Ae())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${me.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();Me.stdin.removeListener("data",r);try{if(typeof Me.stdin.setRawMode==="function")Me.stdin.setRawMode(!1)}catch{}Me.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof Me.stdin.setRawMode==="function")Me.stdin.setRawMode(!0)}catch{}Me.stdin.resume(),Me.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 n=/%([sdijfo%])/g,s=0;if(r=e.replace(n,(o,a)=>{if(a==="%")return"%";if(s>=t.length)return o;let c=t[s++];switch(a){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 o}}),s<t.length)r+=` ${t.slice(s).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}if(this.fancy&&!Ae()){let n=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"",s=me.blue("\u25D0");console.error(`${s} ${n} ${me.cyan(r)}`)}let i=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
103
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||Ae()||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:(i,n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Ae())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,i)),n!==void 0)this.activeProgressBar.message=n;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Ae())return;if(this.activeProgressBar.current=this.activeProgressBar.total,i!==void 0)this.activeProgressBar.message=i;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(i,n="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Ae())return;Me.stdout.write(`${"\r".padEnd(Me.stdout.columns||80)}\r`),this.log(n,i),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||Ae()||!Me.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=me.green("\u2501".repeat(i)),o=me.gray("\u2501".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||r===100?me.green("\u2713"):me.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${me.gray(this.formatTag(this.name))}`:"",p=`\r${u}${l} ${a} ${c}${f}`,h=Me.stdout.columns||80,w=" ".repeat(Math.max(0,h-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${w}`,Me.stdout.write(e.lastRenderedLine),t)Me.stdout.write(`
|
|
104
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ae()||!Me.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(Ae()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await jr(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Kt(this.config.logDirectory,i);if(e.before)try{if((await Yt(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 i of r)try{await _r(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ei(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ae(t[0])&&"id"in t[0]&&t[0].id===3&&ae(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ae(t)&&ae(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(ae(e)&&"arr"in e&&Array.isArray(e.arr)&&ae(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ae(t[0])&&ae(e[0])){let i=[...t];for(let n of e)if(ae(n)&&"name"in n){if(!i.find((s)=>ae(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(ae(n)&&"path"in n){if(!i.find((s)=>ae(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>hi(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!ae(t)||!ae(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(ae(n)&&ae(r[i]))r[i]=ei(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&ae(n[0])&&ae(r[i][0])){let s=[...n];for(let o of r[i])if(ae(o)&&"name"in o){if(!s.find((a)=>ae(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(ae(o)&&"path"in o){if(!s.find((a)=>ae(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>hi(a,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function _n(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ei(e,t);if(Array.isArray(e))return r==="replace"?t:ei(e,t);if(!ae(t)||!ae(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],o=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")i[n]=s;else i[n]=ei(o,s);else if(ae(s)&&ae(o))i[n]=_n(o,s,r);else i[n]=s}return i}function hi(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(!hi(e[r],t[r]))return!1;return!0}if(ae(e)&&ae(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!hi(e[n],t[n]))return!1}return!0}return!1}function ae(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Xr(e,t,r="replace"){if(!ia(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return _n(t,n,r)}catch{return null}}catch{return null}}function Eu(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let l=[...a,f],p=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),h=`${i}_${l.map(p).join("_")}`,w=`${i}_${l.map((A)=>A.toUpperCase()).join("_")}`;if(r)Be.info(`Checking environment variable ${h} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,l);else{let A=pr.env[h]||pr.env[w];if(A!==void 0){if(r)Be.info(`Using environment variable ${A?h:w} for config ${e}.${l.join(".")}`);if(typeof u==="number")c[f]=Number(A);else if(typeof u==="boolean")c[f]=A.toLowerCase()==="true";else if(Array.isArray(u))try{let $=JSON.parse(A);if(Array.isArray($))c[f]=$;else c[f]=A.split(",").map((x)=>x.trim())}catch{c[f]=A.split(",").map(($)=>$.trim())}else c[f]=A}}}return c}return s(n)}async function Ou({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:o=!0,arrayStrategy:a="replace"}){let c=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?Eu(e,n,s):n,f=r||pr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Be.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),p=[`${e}.config`,`.${e}.config`].filter(Boolean),h=t?[t,`.${t}`]:[],w=t?[`${t}.config`,`.${t}.config`]:[],A=Array.from(new Set([f,_e(f,"config"),_e(f,".config"),i?_e(f,i):void 0].filter(Boolean)));for(let $ of A){if(s)Be.info(`Searching for configuration in: ${$}`);let x=[_e(f,"config"),_e(f,".config")].concat(i?[_e(f,i)]:[]).includes($)?[...l,...p,...h,...w]:[...p,...l,...w,...h];for(let S of x)for(let k of u){let R=_e($,`${S}${k}`),b=await Xr(R,c,a);if(b!==null){if(s)Be.success(`Configuration loaded from: ${R}`);return b}}}if(e){let $=_e(on(),".config",e),x=["config",`${e}.config`];if(t)x.push(`${t}.config`);if(s)Be.info(`Checking user config directory: ${$}`);for(let S of x)for(let k of u){let R=_e($,`${S}${k}`),b=await Xr(R,c,a);if(b!==null){if(s)Be.success(`Configuration loaded from user config directory: ${R}`);return b}}}if(e){let $=_e(on(),".config"),x=[`.${e}.config`];if(t)x.push(`.${t}.config`);if(s)Be.info(`Checking user config directory for dotfile configs: ${$}`);for(let S of x)for(let k of u){let R=_e($,`${S}${k}`),b=await Xr(R,c,a);if(b!==null){if(s)Be.success(`Configuration loaded from user config directory dotfile: ${R}`);return b}}}if(e){let $=on(),x=[`.${e}.config`,`.${e}`];if(t)x.push(`.${t}.config`),x.push(`.${t}`);if(s)Be.info(`Checking user home directory for dotfile configs: ${$}`);for(let S of x)for(let k of u){let R=_e($,`${S}${k}`),b=await Xr(R,c,a);if(b!==null){if(s)Be.success(`Configuration loaded from user home directory: ${R}`);return b}}}try{let $=_e(f,"package.json");if(ia($)){let x=await import($),S=x[e];if(!S&&t){if(S=x[t],S&&s)Be.success(`Using alias "${t}" configuration from package.json`)}if(S&&typeof S==="object"&&!Array.isArray(S))try{if(s)Be.success(`Configuration loaded from package.json: ${S===x[e]?e:t}`);return _n(c,S,a)}catch(k){if(s)Be.warn("Failed to merge package.json config:",k)}}}catch($){if(s)Be.warn("Failed to load package.json:",$)}if(s)Be.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function ku(e,t={}){let r=si.cwd();while(r.includes("storage"))r=Ao(r,"..");let i=Ao(r,e||"");if(t?.relative)return Nf(si.cwd(),i);return i}async function Su(){try{let e=await Ou({name:"clarity",alias:"logging",defaultConfig:ii,cwd:si.cwd()});return{...ii,...e||{}}}catch{return ii}}function Se(){if(dt.env.NODE_ENV==="test"||dt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Tu(){if(dt.env.NODE_ENV==="test"||dt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof dt<"u"){let e=dt.type;if(e==="renderer"||e==="worker")return!1;return!!(dt.versions&&(dt.versions.node||dt.versions.bun))}return!1}class ca{async format(e){let t=await Tu(),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:qt.pid,hostname:t(),environment:qt.env.NODE_ENV||"development",platform:qt.platform,version:qt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qt.env.NODE_ENV||qt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class di{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={...Tn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ca,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??se.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{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{...ni,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ni};return{...ni,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Tn.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(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Se()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await Yf(this.config.logDirectory,Fo.F_OK|Fo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Kf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ct.from(e);try{if(!Zr(this.currentLogFile))await dn(this.currentLogFile,"",{mode:420});if(i=Wo(this.currentLogFile,"a",420),Vf(i,a,{flag:"a"}),No(i),i!==void 0)hn(i),i=void 0;if((await Ut(this.currentLogFile)).size===0){if(await dn(this.currentLogFile,a,{flag:"w",mode:420}),(await Ut(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=o*2**n;await new Promise((p)=>setTimeout(p,l)),n++;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{hn(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(n===s-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}n++;let c=o*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 Ht(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 Ht(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ht(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Se())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return un(16).toString("hex")}generateKey(){return un(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=un(16),i=_f("aes-256-gcm",t,r),n=ct.isBuffer(e)?e:ct.from(e,"utf8"),s=i.update(n),o=i.final(),a=s.length+o.length,c=i.getAuthTag(),f=ct.allocUnsafe(16+a+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Do(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(ct.from(ct.concat(n)))),i.on("error",r),i.write(e),i.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(Se())return;if(!this.shouldWriteToFile())return;let e=await Ut(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Jr(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Ut(r).catch(()=>null))try{if(await Po(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Vr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await dn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Ut(r).catch(()=>null))await Po(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Jr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await Vr(Ht(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Ro(e),i=Jf(t),n=Do();await Hf(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(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()})),Zr(this.currentLogFile))try{let e=Wo(this.currentLogFile,"r+");No(e),hn(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(!Se()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Jr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Vr(Ht(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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()?ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Se())return!1;let e=typeof se.env.NO_COLOR<"u",t=se.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof se.stderr<"u"&&se.stderr.isTTY||typeof se.stdout<"u"&&se.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(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(i)h.push(i.replace(/[[\]]/g,""));return h.push(n),h.join(" ")}let c=se.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${ee.cyan(n)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=ee.underline(ee.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>ee.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>ee.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>ee.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>ee.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>ee.strikethrough(i)),t}supportsHyperlinks(){if(Se())return!1;let e=se.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=se.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Gf(t)||t.startsWith("./")||t.startsWith("../"))t=Uf(t);else return null;return Zr(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 i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":wa[e],p=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:ee.gray(c),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:ee.green(c),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.error(h),a){let w=a.split(`
|
|
105
|
+
`);for(let A of w)if(A.trim()&&!A.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:ee.gray(` ${A}`),level:e,showTimestamp:!1}))}break}}else if(!Se()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
106
|
+
`;if(a)u+=`${a}
|
|
107
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!Se()&&se.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Se()&&se.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!Se()&&se.stdout.isTTY)se.stdout.write(`
|
|
108
|
+
`);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!Se()&&se.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":ee.blue("\u25D0"),tag:r,message:`${ee.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
109
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":ee.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Se())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}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 di(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(Se())throw Error("createReadStream is not supported in browser environments");if(!Zr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ro(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 i=ct.isBuffer(e)?e:ct.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),a=Zf("aes-256-gcm",r,n);a.setAuthTag(s);let c=a.update(o),f=a.final(),u=c.length+f.length,l=ct.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Se()}isServerMode(){return!Se()}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),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
|
|
110
|
+
`),c=Math.max(...a.map((p)=>p.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=a.map((p)=>{return this.formatConsoleMessage({timestamp:r,message:ee.cyan(p),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:ee.cyan(f),showTimestamp:!1})),l.forEach((p)=>console.error(p)),console.error(this.formatConsoleMessage({timestamp:r,message:ee.cyan(u),showTimestamp:!1}))}else if(!Se())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
111
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Se())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ee.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();se.stdin.removeListener("data",r);try{if(typeof se.stdin.setRawMode==="function")se.stdin.setRawMode(!1)}catch{}se.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof se.stdin.setRawMode==="function")se.stdin.setRawMode(!0)}catch{}se.stdin.resume(),se.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,a=0;if(r=e.replace(o,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${ee.blue("\u25D0")} `;console.error(`${a}${o} ${ee.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
112
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!se.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=ee.green("\u2501".repeat(i)),o=ee.gray("\u2501".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?ee.green("\u2713"):ee.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${ee.gray(this.formatTag(this.name))}`:"",p=`\r${u}${l} ${a} ${c}${f}`,h=se.stdout.columns||80,w=" ".repeat(Math.max(0,h-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${w}`,se.stdout.write(e.lastRenderedLine),t)se.stdout.write(`
|
|
113
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Se()||!se.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(Se()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Jr(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Ht(this.config.logDirectory,i);if(e.before)try{if((await Ut(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 i of r)try{await Vr(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function fa(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!n(o))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function ua(e){return e instanceof Ve}function Ru(e){return e instanceof mi}function Nu(e){if(ua(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class Ci{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:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:a=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return wr.track("applyEnvironmentVariables",f,{configName:e});return f()}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,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=o.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${r}_${a.join("_")}`,f=i.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let u=Yr.env[c]||(f?Yr.env[f]:void 0);if(u!==void 0){if(i.verbose){let l=Yr.env[c]?c:f}try{e[n]=this.parseEnvironmentValue(u,typeof s,c,i.customParsers,i.configName)}catch(l){if(l instanceof gi)throw l;throw Ot.envVar(c,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Ot.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(Yr.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){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,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:a,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}:
|
|
95
114
|
|
|
96
115
|
`;for(let i of e)r+=`${i.key}
|
|
97
116
|
`,r+=` Type: ${i.type}
|
|
@@ -103,25 +122,25 @@ ${h.join(`
|
|
|
103
122
|
`;r+=`| Variable | Type | Description | Example |
|
|
104
123
|
`,r+=`|----------|------|-------------|----------|
|
|
105
124
|
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
106
|
-
`;return r}}function Lf(e,t){let r=Ua("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function Za(e,t,r={}){return Va(e,t,r,new WeakMap)}function Va(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:a}=r;if(t===null||t===void 0)return s?e:t;if(a){let o=a(e,t);if(o!==void 0)return o}if(Array.isArray(t)||Array.isArray(e))return Ja(e,t,n,i);if(!He(t)||!He(e))return t;return _f(e,t,r,i)}function Ja(e,t,r,i){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 jf(e,t);case"smart":return Bf(e,t,i);default:return t}return t}function jf(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>gn(n,i)))r.push(i);return r}function Bf(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(He(t[0])&&He(e[0]))return Mf(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Mf(e,t,r){let i=[...t];for(let n of e){if(!He(n)){i.push(n);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in n){if(i.find((c)=>He(c)&&(o in c)&&c[o]===n[o])){a=!0;break}}if(!a)i.push(n)}return i}function _f(e,t,r,i){let n=t;if(He(n)&&i.has(n))return i.get(n);let s={...e};if(He(n))i.set(n,s);for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;let o=n[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(He(o)&&He(c))s[a]=Va(c,o,r,i);else if(Array.isArray(o)||Array.isArray(c))s[a]=Ja(c,o,r.arrayMergeMode||"smart",i);else s[a]=o}return s}function Rn(e,t,r="replace"){return Za(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function gn(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(!gn(e[r],t[r]))return!1;return!0}if(He(e)&&He(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!gn(e[n],t[n]))return!1}return!0}return!1}function He(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class hi{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(n){let f=Yt.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Lr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,d=Object.keys(u).length>0;if(!p&&!d)throw new cr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new cr(e,Error("Configuration must export a valid object"),"unknown");let C={config:Rn(t,l,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)Yt.setWithFileCheck("file",C,e,s);return C}catch(f){throw f instanceof Error?At.configLoad(e,f):At.configLoad(e,Error(String(f)))}};if(a)return ur.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let a of this.extensions)n.push(tn(t,`${s}${a}`));return n}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 Ma(async()=>{return Lr(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Lr(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let a of this.extensions){let o=tn(e,`${s}${a}`);if(await this.checkFileAccess(o))i.push(o)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=tn(e,a);if(await this.checkFileAccess(o))i.push(o)}}catch{return[]}return i}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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Lr(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}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(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Nn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],p);else return this.validateWithJSONSchema(e,t,p)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await ur.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!ef(t))throw new fr(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new fr(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(i.push({path:r,message:`Expected type ${o.join(" or ")}, got ${a}`,expected:o.join(" or "),actual:a,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.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)i.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)i.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))i.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)i.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)i.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 a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(s.validateRequired&&t.required){for(let o of t.required)if(!(o in a)){if(i.push({path:r?`${r}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[o,c]of Object.entries(t.properties))if(o in a){let f=r?`${r}.${o}`:o;if(this.validateObjectAgainstSchema(a[o],c,f,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let o=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(a))if(!o.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(i.push(...o),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.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))i.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 n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,a]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(a)})}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:za},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Wn{fileLoader=new hi;envProcessor=new ui;validator=new Nn;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...a}=e;try{if(r?.enabled){let c=this.checkCache(a.name||"",a);if(c)return c}let o;try{o=await this.loadConfigurationStrategies(a,!0,r)}catch(c){let f=a.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(o.config,n,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)Xe.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);o.metrics=c}return o}catch(o){let c=Date.now()-t;throw Xe.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||Ot.cwd(),p=[],d=await this.loadLocalConfiguration(i,n,l,a,o,f,u,c,r);if(d)return p.push(...this.getLocalSearchPaths(i,n,l,a)),this.finalizeResult(d,p,c,i,u);let C=await this.loadHomeConfiguration(i,n,o,f,u,c);if(C)return p.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(C,p,c,i,u);let v=await this.loadPackageJsonConfiguration(i,n,l,o,f,u,c);if(v)return p.push(_e(l,"package.json")),this.finalizeResult(v,p,c,i,u);if(p.push(...this.getAllSearchPaths(i,n,l,a)),t)throw At.configNotFound(i,p,n);return{...await this.applyEnvironmentVariables(i,o,c,u),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,a,o,c){let f=o?or(e,n,a):n,u=this.getLocalDirectories(r,i);for(let l of u){if(a)Xe.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(a)Xe.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let a=s?or(e,r,n):r,o=[_e(jt(),".config",e),_e(jt(),".config"),jt()];for(let c of o){if(n)Xe.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:i,verbose:n});if(u){if(n)Xe.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,a){let o=a?or(e,i,s):i;try{let c=_e(r,"package.json");if(!dn(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Xe.success(`Configuration loaded from package.json: ${l}`);return{config:Rn(o,u,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)Xe.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:or(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(n.length>0)throw At.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Yt.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Yt.set(n,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,_e(e,"config"),_e(e,".config"),t?_e(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(_e(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let a of n)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[_e(jt(),".config",e),_e(jt(),".config"),jt()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Ca(e){let t=!(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")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function Zf(e){return dt.loadConfig({...e,__strictErrorHandling:!0})}async function Ka(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 i;if(r)i=await dt.loadConfig(e);else i=await dt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)Xe.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await dt.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function Vf(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await dt.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"&&Ca(r)))return(await dt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await dt.loadConfig({...e,cwd:e.cwd||Ot.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Ca(t)))return(await dt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Jf(e,t,r="replace"){let i=new hi;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function or(e,t,r=!1){let i=new ui,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],p=[`${n}_${l.join("_").toUpperCase()}`,`${n}_${l.map((v)=>v.toUpperCase()).join("")}`,`${n}_${l.map((v)=>v.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,C;for(let v of p)if(d=Ot.env[v],d!==void 0){C=v;break}if(d!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let v=Number(d);if(!Number.isNaN(v))c[f]=v}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((v)=>v.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function Kf(e){let t=_e(Ot.cwd(),e.configDir),r=_e(Ot.cwd(),e.generatedDir),i=_e(r,"config-types.ts");if(!dn(zs(i)))Nc(zs(i),{recursive:!0,mode:511});let n=dn(t)?Wc(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${Cu}
|
|
125
|
+
`;return r}}function Wu(e,t){let r=pa("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function ha(e,t,r={}){return da(e,t,r,new WeakMap)}function da(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return ma(e,t,n,i);if(!qe(t)||!qe(e))return t;return Mu(e,t,r,i)}function ma(e,t,r,i){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 Fu(e,t);case"smart":return Pu(e,t,i);default:return t}return t}function Fu(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>kn(n,i)))r.push(i);return r}function Pu(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(qe(t[0])&&qe(e[0]))return Du(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Du(e,t,r){let i=[...t];for(let n of e){if(!qe(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in n){if(i.find((c)=>qe(c)&&(a in c)&&c[a]===n[a])){o=!0;break}}if(!o)i.push(n)}return i}function Mu(e,t,r,i){let n=t;if(qe(n)&&i.has(n))return i.get(n);let s={...e};if(qe(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let a=n[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(qe(a)&&qe(c))s[o]=da(c,a,r,i);else if(Array.isArray(a)||Array.isArray(c))s[o]=ma(c,a,r.arrayMergeMode||"smart",i);else s[o]=a}return s}function Zn(e,t,r="replace"){return ha(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function kn(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(!kn(e[r],t[r]))return!1;return!0}if(qe(e)&&qe(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!kn(e[n],t[n]))return!1}return!0}return!1}function qe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class bi{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(n){let f=er.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Kr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,h=Object.keys(u).length>0;if(!p&&!h)throw new yr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new yr(e,Error("Configuration must export a valid object"),"unknown");let w={config:Zn(t,l,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)er.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?Ot.configLoad(e,f):Ot.configLoad(e,Error(String(f)))}};if(o)return wr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(mn(t,`${s}${o}`));return n}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 fa(async()=>{return Kr(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Kr(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let a=mn(e,`${s}${o}`);if(await this.checkFileAccess(a))i.push(a)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=mn(e,o);if(await this.checkFileAccess(a))i.push(a)}}catch{return[]}return i}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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Kr(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}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(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Jn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],p);else return this.validateWithJSONSchema(e,t,p)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await wr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!qf(t))throw new $r(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new $r(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(i.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.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)i.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)i.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))i.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)i.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)i.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 a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(i.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,f,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(i.push(...a),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.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))i.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 n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,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:ba},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Vn{fileLoader=new bi;envProcessor=new Ci;validator=new Jn;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...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(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))a={...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(!f)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(a.config,n,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)Qe.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw Qe.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||Rt.cwd(),p=[],h=await this.loadLocalConfiguration(i,n,l,o,a,f,u,c,r);if(h)return p.push(...this.getLocalSearchPaths(i,n,l,o)),this.finalizeResult(h,p,c,i,u);let w=await this.loadHomeConfiguration(i,n,a,f,u,c);if(w)return p.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(w,p,c,i,u);let A=await this.loadPackageJsonConfiguration(i,n,l,a,f,u,c);if(A)return p.push(Ze(l,"package.json")),this.finalizeResult(A,p,c,i,u);if(p.push(...this.getAllSearchPaths(i,n,l,o)),t)throw Ot.configNotFound(i,p,n);return{...await this.applyEnvironmentVariables(i,a,c,u),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,a,c){let f=a?gr(e,n,o):n,u=this.getLocalDirectories(r,i);for(let l of u){if(o)Qe.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),h=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(h){if(o)Qe.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?gr(e,r,n):r,a=[Ze(Vt(),".config",e),Ze(Vt(),".config"),Vt()];for(let c of a){if(n)Qe.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,o,{arrayStrategy:i,verbose:n});if(u){if(n)Qe.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let a=o?gr(e,i,s):i;try{let c=Ze(r,"package.json");if(!En(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Qe.success(`Configuration loaded from package.json: ${l}`);return{config:Zn(a,u,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)Qe.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:gr(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw Ot.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return er.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);er.set(n,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,Ze(e,"config"),Ze(e,".config"),t?Ze(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Ze(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ze(Vt(),".config",e),Ze(Vt(),".config"),Vt()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Vo(e){let t=!(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")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function Iu(e){return gt.loadConfig({...e,__strictErrorHandling:!0})}async function ga(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 i;if(r)i=await gt.loadConfig(e);else i=await gt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)Qe.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await gt.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function Bu(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await gt.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"&&Vo(r)))return(await gt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await gt.loadConfig({...e,cwd:e.cwd||Rt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Vo(t)))return(await gt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Lu(e,t,r="replace"){let i=new bi;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function gr(e,t,r=!1){let i=new Ci,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let l=[...a,f],p=[`${n}_${l.join("_").toUpperCase()}`,`${n}_${l.map((A)=>A.toUpperCase()).join("")}`,`${n}_${l.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,w;for(let A of p)if(h=Rt.env[A],h!==void 0){w=A;break}if(h!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let A=Number(h);if(!Number.isNaN(A))c[f]=A}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((A)=>A.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function ju(e){let t=Ze(Rt.cwd(),e.configDir),r=Ze(Rt.cwd(),e.generatedDir),i=Ze(r,"config-types.ts");if(!En(bo(i)))kf(bo(i),{recursive:!0,mode:511});let n=En(t)?Sf(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${gh}
|
|
107
126
|
export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
|
|
108
|
-
`;
|
|
109
|
-
${n.map((c)=>{let f=
|
|
127
|
+
`;Tf(i,s,{mode:438})}function _u(e){let t=null,r=null,i=()=>{if(!r)r=ga(e).then((s)=>{return t=s,s},(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)Qe.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,o){if(t)return t[o];let a=n[o];return i(),a},has(s,o){return o in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||n,o)},set(s,o,a){if(!t)t={...n};return t[o]=a,!0}})}function Zu(e){let t=Mo(Qf.cwd(),e?.configDir||"./config");function r(){if(!zf(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=Xf(t).filter((c)=>n.has(gn(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),a=new Map;for(let{base:c,file:f}of o){let u=gn(f).toLowerCase(),l=a.get(c);if(!l){a.set(c,f);continue}let p=gn(l).toLowerCase();if(s.indexOf(u)<s.indexOf(p))a.set(c,f)}return Array.from(a.entries()).map(([c,f])=>({base:c,file:f})).sort((c,f)=>c.base.localeCompare(f.base))}function i(){let n=r(),s=n.map((c)=>c.base),o=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",a=n.length?`{
|
|
128
|
+
${n.map((c)=>{let f=Mo(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
|
|
110
129
|
`)}
|
|
111
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
112
|
-
export type ConfigByName = ${
|
|
130
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
131
|
+
export type ConfigByName = ${a}
|
|
113
132
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
114
133
|
export type ConfigOf = Config
|
|
115
|
-
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>{return{path:s.path,namespace:"bunfig-virtual"}}),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:i(),loader:"ts"}})}}}function vu(e,t={}){let r=Qr.cwd();while(r.includes("storage"))r=da(r,"..");let i=da(r,e||"");if(t?.relative)return af(Qr.cwd(),i);return i}function Re(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xu(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ht<"u"){let e=ht.type;if(e==="renderer"||e==="worker")return!1;return!!(ht.versions&&(ht.versions.node||ht.versions.bun))}return!1}class to{async format(e){let t=await xu(),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:Gt.pid,hostname:t(),environment:Gt.env.NODE_ENV||"development",platform:Gt.platform,version:Gt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Gt.env.NODE_ENV||Gt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class di{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={...oi},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new to,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??ae.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{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{...hn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...hn};return{...hn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:oi.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(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Re()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await uf(this.config.logDirectory,ya.F_OK|ya.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await hf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:lt.from(e);try{if(!jr(this.currentLogFile))await an(this.currentLogFile,"",{mode:420});if(i=pa(this.currentLogFile,"a",420),ff(i,o,{flag:"a"}),ga(i),i!==void 0)sn(i),i=void 0;if((await Kt(this.currentLogFile)).size===0){if(await an(this.currentLogFile,o,{flag:"w",mode:420}),(await Kt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=a*2**n;await new Promise((p)=>setTimeout(p,l)),n++;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{sn(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(n===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let c=a*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 Ut(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 Ut(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ut(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Re())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return nn(16).toString("hex")}generateKey(){return nn(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=nn(16),i=of("aes-256-gcm",t,r),n=lt.isBuffer(e)?e:lt.from(e,"utf8"),s=i.update(n),a=i.final(),o=s.length+a.length,c=i.getAuthTag(),f=lt.allocUnsafe(16+o+16);return r.copy(f,0),s.copy(f,16),a.copy(f,16+s.length),c.copy(f,16+o),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=$a(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(lt.from(lt.concat(n)))),i.on("error",r),i.write(e),i.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(Re())return;if(!this.shouldWriteToFile())return;let e=await Kt(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Br(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Kt(r).catch(()=>null))try{if(await wa(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await Mr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await an(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Kt(r).catch(()=>null))await wa(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Br(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Mr(Ut(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=ma(e),i=cf(t),n=$a();await gf(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(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()})),jr(this.currentLogFile))try{let e=pa(this.currentLogFile,"r+");ga(e),sn(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(!Re()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Br(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Mr(Ut(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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()?te.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Re())return!1;let e=typeof ae.env.NO_COLOR<"u",t=ae.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ae.stderr<"u"&&ae.stderr.isTTY||typeof ae.stdout<"u"&&ae.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=ae.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${te.cyan(n)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=te.underline(te.blue(i)),a=this.toAbsoluteFilePath(n);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${o}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>te.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>te.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>te.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>te.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>te.strikethrough(i)),t}supportsHyperlinks(){if(Re())return!1;let e=ae.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=ae.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(df(t)||t.startsWith("./")||t.startsWith("../"))t=mf(t);else return null;return jr(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 i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":Tu[e],p=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:te.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:te.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.error(d),o){let C=o.split(`
|
|
116
|
-
`);for(let
|
|
117
|
-
`;if(
|
|
118
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!Re()&&
|
|
119
|
-
`);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!Re()&&
|
|
120
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:
|
|
121
|
-
`),c=Math.max(...
|
|
122
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
123
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
124
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Re()||!
|
|
134
|
+
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>{return{path:s.path,namespace:"bunfig-virtual"}}),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:i(),loader:"ts"}})}}}function yh(e,t={}){let r=li.cwd();while(r.includes("storage"))r=Io(r,"..");let i=Io(r,e||"");if(t?.relative)return tu(li.cwd(),i);return i}function Re(){if(mt.env.NODE_ENV==="test"||mt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wh(){if(mt.env.NODE_ENV==="test"||mt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof mt<"u"){let e=mt.type;if(e==="renderer"||e==="worker")return!1;return!!(mt.versions&&(mt.versions.node||mt.versions.bun))}return!1}class Ea{async format(e){let t=await wh(),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:Qt.pid,hostname:t(),environment:Qt.env.NODE_ENV||"development",platform:Qt.platform,version:Qt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qt.env.NODE_ENV||Qt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ai{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={...pi},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ea,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??oe.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{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{...xn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...xn};return{...xn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:pi.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(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Re()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await ou(this.config.logDirectory,_o.F_OK|_o.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await au(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ft.from(e);try{if(!Gr(this.currentLogFile))await $n(this.currentLogFile,"",{mode:420});if(i=jo(this.currentLogFile,"a",420),su(i,a,{flag:"a"}),Lo(i),i!==void 0)yn(i),i=void 0;if((await zt(this.currentLogFile)).size===0){if(await $n(this.currentLogFile,a,{flag:"w",mode:420}),(await zt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=o*2**n;await new Promise((p)=>setTimeout(p,l)),n++;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{yn(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(n===s-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}n++;let c=o*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 Xt(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 Xt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Xt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Re())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return pn(16).toString("hex")}generateKey(){return pn(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=pn(16),i=ru("aes-256-gcm",t,r),n=ft.isBuffer(e)?e:ft.from(e,"utf8"),s=i.update(n),o=i.final(),a=s.length+o.length,c=i.getAuthTag(),f=ft.allocUnsafe(16+a+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Jo(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(ft.from(ft.concat(n)))),i.on("error",r),i.write(e),i.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(Re())return;if(!this.shouldWriteToFile())return;let e=await zt(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Ur(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await zt(r).catch(()=>null))try{if(await Zo(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Hr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await $n(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await zt(r).catch(()=>null))await Zo(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Ur(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await Hr(Xt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Bo(e),i=nu(t),n=Jo();await fu(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(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()})),Gr(this.currentLogFile))try{let e=jo(this.currentLogFile,"r+");Lo(e),yn(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(!Re()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Ur(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Hr(Xt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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()?te.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Re())return!1;let e=typeof oe.env.NO_COLOR<"u",t=oe.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof oe.stderr<"u"&&oe.stderr.isTTY||typeof oe.stdout<"u"&&oe.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(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(i)h.push(i.replace(/[[\]]/g,""));return h.push(n),h.join(" ")}let c=oe.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${te.cyan(n)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=te.underline(te.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>te.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>te.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>te.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>te.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>te.strikethrough(i)),t}supportsHyperlinks(){if(Re())return!1;let e=oe.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=oe.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(lu(t)||t.startsWith("./")||t.startsWith("../"))t=cu(t);else return null;return Gr(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 i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":xh[e],p=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:te.gray(c),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:te.green(c),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.error(h),a){let w=a.split(`
|
|
135
|
+
`);for(let A of w)if(A.trim()&&!A.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:te.gray(` ${A}`),level:e,showTimestamp:!1}))}break}}else if(!Re()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
136
|
+
`;if(a)u+=`${a}
|
|
137
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!Re()&&oe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Re()&&oe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!Re()&&oe.stdout.isTTY)oe.stdout.write(`
|
|
138
|
+
`);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!Re()&&oe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":te.blue("\u25D0"),tag:r,message:`${te.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
139
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":te.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Re())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}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 Ai(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(Re())throw Error("createReadStream is not supported in browser environments");if(!Gr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Bo(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 i=ft.isBuffer(e)?e:ft.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),a=iu("aes-256-gcm",r,n);a.setAuthTag(s);let c=a.update(o),f=a.final(),u=c.length+f.length,l=ft.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Re()}isServerMode(){return!Re()}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),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
|
|
140
|
+
`),c=Math.max(...a.map((p)=>p.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=a.map((p)=>{return this.formatConsoleMessage({timestamp:r,message:te.cyan(p),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:te.cyan(f),showTimestamp:!1})),l.forEach((p)=>console.error(p)),console.error(this.formatConsoleMessage({timestamp:r,message:te.cyan(u),showTimestamp:!1}))}else if(!Re())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
141
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Re())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${te.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();oe.stdin.removeListener("data",r);try{if(typeof oe.stdin.setRawMode==="function")oe.stdin.setRawMode(!1)}catch{}oe.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof oe.stdin.setRawMode==="function")oe.stdin.setRawMode(!0)}catch{}oe.stdin.resume(),oe.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,a=0;if(r=e.replace(o,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${te.blue("\u25D0")} `;console.error(`${a}${o} ${te.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
142
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!oe.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=te.green("\u2501".repeat(i)),o=te.gray("\u2501".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?te.green("\u2713"):te.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${te.gray(this.formatTag(this.name))}`:"",p=`\r${u}${l} ${a} ${c}${f}`,h=oe.stdout.columns||80,w=" ".repeat(Math.max(0,h-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${w}`,oe.stdout.write(e.lastRenderedLine),t)oe.stdout.write(`
|
|
143
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Re()||!oe.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(Re()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ur(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Xt(this.config.logDirectory,i);if(e.before)try{if((await zt(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 i of r)try{await Hr(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Eh(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!n(o))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class Kn{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:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:a=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return In.track("applyEnvironmentVariables",f,{configName:e});return f()}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,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=o.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${r}_${a.join("_")}`,f=i.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let u=qr.env[c]||(f?qr.env[f]:void 0);if(u!==void 0){if(i.verbose){let l=qr.env[c]?c:f}try{e[n]=this.parseEnvironmentValue(u,typeof s,c,i.customParsers,i.configName)}catch(l){if(l instanceof Yn)throw l;throw tr.envVar(c,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw tr.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(qr.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){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,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:a,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}:
|
|
125
144
|
|
|
126
145
|
`;for(let i of e)r+=`${i.key}
|
|
127
146
|
`,r+=` Type: ${i.type}
|
|
@@ -133,64 +152,64 @@ export type ConfigOf = Config
|
|
|
133
152
|
`;r+=`| Variable | Type | Description | Example |
|
|
134
153
|
`,r+=`|----------|------|-------------|----------|
|
|
135
154
|
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
136
|
-
`;return r}}function Nu(e,t,r={}){return co(e,t,r,new WeakMap)}function co(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:a}=r;if(t===null||t===void 0)return s?e:t;if(a){let o=a(e,t);if(o!==void 0)return o}if(Array.isArray(t)||Array.isArray(e))return fo(e,t,n,i);if(!qe(t)||!qe(e))return t;return Du(e,t,r,i)}function fo(e,t,r,i){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 Wu(e,t);case"smart":return Pu(e,t,i);default:return t}return t}function Wu(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>xn(n,i)))r.push(i);return r}function Pu(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(qe(t[0])&&qe(e[0]))return Fu(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Fu(e,t,r){let i=[...t];for(let n of e){if(!qe(n)){i.push(n);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in n){if(i.find((c)=>qe(c)&&(o in c)&&c[o]===n[o])){a=!0;break}}if(!a)i.push(n)}return i}function Du(e,t,r,i){let n=t;if(qe(n)&&i.has(n))return i.get(n);let s={...e};if(qe(n))i.set(n,s);for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;let o=n[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(qe(o)&&qe(c))s[a]=co(c,o,r,i);else if(Array.isArray(o)||Array.isArray(c))s[a]=fo(c,o,r.arrayMergeMode||"smart",i);else s[a]=o}return s}function uo(e,t,r="replace"){return Nu(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function xn(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(!xn(e[r],t[r]))return!1;return!0}if(qe(e)&&qe(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!xn(e[n],t[n]))return!1}return!0}return!1}function qe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ho{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(n){let f=ei.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Zr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,d=Object.keys(u).length>0;if(!p&&!d)throw new li(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new li(e,Error("Configuration must export a valid object"),"unknown");let C={config:uo(t,l,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)ei.setWithFileCheck("file",C,e,s);return C}catch(f){throw f instanceof Error?Ht.configLoad(e,f):Ht.configLoad(e,Error(String(f)))}};if(a)return En.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let a of this.extensions)n.push(on(t,`${s}${a}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return Ru(async()=>{return Zr(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Zr(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let a of this.extensions){let o=on(e,`${s}${a}`);if(await this.checkFileAccess(o))i.push(o)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=on(e,a);if(await this.checkFileAccess(o))i.push(o)}}catch{return[]}return i}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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Zr(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}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(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class mo{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],p);else return this.validateWithJSONSchema(e,t,p)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await En.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!pf(t))throw new ci(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new ci(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(i.push({path:r,message:`Expected type ${o.join(" or ")}, got ${a}`,expected:o.join(" or "),actual:a,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.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)i.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)i.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))i.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)i.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)i.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 a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(s.validateRequired&&t.required){for(let o of t.required)if(!(o in a)){if(i.push({path:r?`${r}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[o,c]of Object.entries(t.properties))if(o in a){let f=r?`${r}.${o}`:o;if(this.validateObjectAgainstSchema(a[o],c,f,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let o=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(a))if(!o.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(i.push(...o),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.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))i.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 n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,a]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(a)})}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:Iu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Lu(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class go{fileLoader=new ho;envProcessor=new Fn;validator=new mo;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...a}=e;try{if(r?.enabled){let c=this.checkCache(a.name||"",a);if(c)return c}let o;try{o=await this.loadConfigurationStrategies(a,!0,r)}catch(c){let f=a.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(o.config,n,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)ct.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);o.metrics=c}return o}catch(o){if(o instanceof Error&&o.name==="ConfigNotFoundError")throw o;let c=Date.now()-t;throw ct.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||fi.cwd(),p=[],d=await this.loadLocalConfiguration(i,n,l,a,o,f,u,c,r);if(d)return p.push(...this.getLocalSearchPaths(i,n,l,a)),this.finalizeResult(d,p,c,i,u);let C=await this.loadHomeConfiguration(i,n,o,f,u,c);if(C)return p.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(C,p,c,i,u);let v=await this.loadPackageJsonConfiguration(i,n,l,o,f,u,c);if(v)return p.push(Ye(l,"package.json")),this.finalizeResult(v,p,c,i,u);if(p.push(...this.getAllSearchPaths(i,n,l,a)),t)throw Ht.configNotFound(i,p,n);return{...await this.applyEnvironmentVariables(i,o,c,u),warnings:[`No configuration file found for "${i}"${Lu(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,a,o,c){let f=o?Jr(e,n,a):n,u=this.getLocalDirectories(r,i);for(let l of u){if(a)ct.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(a)ct.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let a=s?Jr(e,r,n):r,o=[Ye(Lt(),".config",e),Ye(Lt(),".config"),Lt()];for(let c of o){if(n)ct.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:i,verbose:n});if(u){if(n)ct.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,a){let o=a?Jr(e,i,s):i;try{let c=Ye(r,"package.json");if(!Tc(c))return null;let f={};try{f=JSON.parse(Rc(c,"utf8"))}catch(p){if(s)ct.warn("Failed to parse package.json:",[p instanceof Error?p:Error(String(p))]);return null}let u=f[e],l=e;if(!u&&t){let p=Array.isArray(t)?t:[t];for(let d of p){if(!d)continue;if(f[d]){u=f[d],l=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)ct.success(`Configuration loaded from package.json: ${l}`);return{config:uo(o,u,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)ct.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Jr(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(n.length>0)throw Ht.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ei.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);ei.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}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,Ye(e,"config"),Ye(e,".config"),t?Ye(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Ye(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let a of n)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ye(Lt(),".config",e),Ye(Lt(),".config"),Lt()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Jr(e,t,r=!1){let i=new Fn,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],p=[`${n}_${l.join("_").toUpperCase()}`,`${n}_${l.map((v)=>v.toUpperCase()).join("")}`,`${n}_${l.map((v)=>v.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,C;for(let v of p)if(d=fi.env[v],d!==void 0){C=v;break}if(d!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let v=Number(d);if(!Number.isNaN(v))c[f]=v}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((v)=>v.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var ei,En,yf,wf=(e)=>e,Cf=(e,t)=>{for(var r in t)yf(e,r,{get:t[r],enumerable:!0,configurable:!0,set:$f.bind(t,r)})},bf=(e,t)=>()=>(e&&(t=e(e=0)),t),La,Ua,Yt,ur,Ga,Yf,Hf,ba,Ur,pn,Ie,ue,qf,va,zf,Aa,Xf,Qf,ln,eu,xa,Ea,cn,tu,ru,iu,nu,Gr,Ya,su,Le,au,ou,Oa,Yr,yn,Te,ee,lu,Sa,cu,ka,fu,uu,fn,hu,Ta,Ra,du,un,mu,gu,pu,yu,wu,Hr,Ha,$u,Cu="0.15.6",Ve,si,cr,wn,$n,ai,Cn,bn,fr,vn,An,At,qa,za,Xe,dt,Xa,Qa,bu,Au,eo,oi,tg,Fe,te,rg,Eu,ig,Ou,ng,sg,Na,ag,Su,ku,og,Wa,lg,cg,fg,ug,hg,hn,Tu,dg,Qe,ro,li,io,no,Pn,so,ao,ci,oo,lo,Ht,Iu,ct,mg,gg,pg,ju,po;var yo=he(()=>{ei=new Da,En=new Ia,yf=Object.defineProperty;La={};Cf(La,{withErrorRecovery:()=>Ma,tryLoadConfig:()=>Jf,loadConfigWithResult:()=>Zf,loadConfig:()=>Ka,isRetryableError:()=>If,isConfigNotFoundError:()=>Df,isBunfigError:()=>_a,globalPerformanceMonitor:()=>ur,globalCache:()=>Yt,getEnvOrDefault:()=>Lf,generateConfigTypes:()=>Kf,defaultGeneratedDir:()=>Qa,defaultConfigDir:()=>Xa,deepMergeWithArrayStrategy:()=>Rn,deepMerge:()=>Za,createLibraryConfig:()=>Uf,config:()=>Vf,bunfigPlugin:()=>Gf,applyEnvVarsToConfig:()=>or,TypeGenerationError:()=>bn,SchemaValidationError:()=>fr,PluginError:()=>An,PerformanceMonitor:()=>Sn,FileSystemError:()=>Cn,ErrorFactory:()=>At,EnvVarError:()=>ai,EnvProcessor:()=>ui,ConfigValidator:()=>Nn,ConfigValidationError:()=>wn,ConfigNotFoundError:()=>si,ConfigMergeError:()=>$n,ConfigLoader:()=>Wn,ConfigLoadError:()=>cr,ConfigFileLoader:()=>hi,ConfigCache:()=>On,CacheUtils:()=>Ga,BunfigError:()=>Ve,BrowserConfigError:()=>vn,ArrayMergeStrategies:()=>qa});bu=bf(async()=>{Ua=import.meta.require,Yt=new On,ur=new Sn,Ga={createKey:vf,isEquivalent:Af,estimateMemoryUsage:xf},Yf=Xr(mn.cwd(),"config"),Hf=Xr(mn.cwd(),"src/generated"),ba=zr.env.CLARITY_LOG_DIR||Ic(Sf(),"logs"),Ur={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ba,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},pn=await kf(),Ie={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"},ue=Ie,qf=Ie.red,va=Ie.green,zf=Ie.yellow,Aa=Ie.blue,Xf=Ie.magenta,Qf=Ie.cyan,ln=Ie.white,eu=Ie.gray,xa=Ie.bgRed,Ea=Ie.bgYellow,cn=Ie.bold,tu=Ie.dim,ru=Ie.italic,iu=Ie.underline,nu=Ie.reset,Gr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ya={debug:"\uD83D\uDD0D",info:Aa("\u2139"),success:va("\u2713"),warning:Ea(ln(cn(" WARN "))),error:xa(ln(cn(" ERROR ")))},su=new ri("stacks"),Le=new ri("bunfig",{showTags:!0}),au=Me(lr.cwd(),"config"),ou=Me(lr.cwd(),"src/generated"),Oa=qr.env.CLARITY_LOG_DIR||Fc(Wf(),"logs"),Yr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Oa,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},yn=await Pf(),Te={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"},ee=Te,lu=Te.red,Sa=Te.green,cu=Te.yellow,ka=Te.blue,fu=Te.magenta,uu=Te.cyan,fn=Te.white,hu=Te.gray,Ta=Te.bgRed,Ra=Te.bgYellow,du=Te.bgGray,un=Te.bold,mu=Te.dim,gu=Te.italic,pu=Te.underline,yu=Te.strikethrough,wu=Te.reset,Hr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ha={debug:"\uD83D\uDD0D",info:ka("\u2139"),success:Sa("\u2713"),warning:Ra(fn(un(" WARN "))),error:Ta(fn(un(" ERROR ")))},$u=new ni("stacks"),Ve=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},si=class extends Ve{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r?` or alias "${r}"`:"";super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},cr=class extends Ve{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},wn=class extends Ve{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},$n=class extends Ve{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},ai=class extends Ve{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},Cn=class extends Ve{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},bn=class extends Ve{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},fr=class extends Ve{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},vn=class extends Ve{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},An=class extends Ve{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},At={configNotFound(e,t,r){return new si(e,t,r)},configLoad(e,t,r){return new cr(e,t,r)},configValidation(e,t,r){return new wn(e,t,r)},configMerge(e,t,r,i){return new $n(e,t,r,i)},envVar(e,t,r,i){return new ai(e,t,r,i)},fileSystem(e,t,r){return new Cn(e,t,r)},typeGeneration(e,t,r){return new bn(e,t,r)},schemaValidation(e,t,r){return new fr(e,t,r)},browserConfig(e,t,r,i){return new vn(e,t,r,i)},plugin(e,t,r){return new An(e,t,r)}},qa={replace:"replace",concat:"concat",smart:"smart"},za=/^https?:\/\//,Xe=new ni("bunfig",{showTags:!0}),dt=new Wn,Xa=_e(Ot.cwd(),"config"),Qa=_e(Ot.cwd(),"src/generated")});Au=Qr.env.CLARITY_LOG_DIR||sf(vu(),"logs"),eo={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Au,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},oi={...eo},tg=(async()=>{try{let{loadConfig:e}=await bu().then(()=>La),t=await e({name:"clarity",alias:"logging",defaultConfig:eo,cwd:Qr.cwd()});if(t)Object.assign(oi,t)}catch{}return oi})();Fe={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"},te=Fe,rg=Fe.red,Eu=Fe.green,ig=Fe.yellow,Ou=Fe.blue,ng=Fe.magenta,sg=Fe.cyan,Na=Fe.white,ag=Fe.gray,Su=Fe.bgRed,ku=Fe.bgYellow,og=Fe.bgGray,Wa=Fe.bold,lg=Fe.dim,cg=Fe.italic,fg=Fe.underline,ug=Fe.strikethrough,hg=Fe.reset,hn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Tu={debug:"\uD83D\uDD0D",info:Ou("\u2139"),success:Eu("\u2713"),warning:ku(Na(Wa(" WARN "))),error:Su(Na(Wa(" ERROR ")))};dg=new di("stacks");Qe=class Qe extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};ro=class ro extends Qe{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};li=class li extends Qe{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};io=class io extends Qe{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};no=class no extends Qe{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}};Pn=class Pn extends Qe{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}};so=class so extends Qe{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};ao=class ao extends Qe{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};ci=class ci extends Qe{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};oo=class oo extends Qe{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}};lo=class lo extends Qe{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Ht={configNotFound(e,t,r){return new ro(e,t,r)},configLoad(e,t,r){return new li(e,t,r)},configValidation(e,t,r){return new io(e,t,r)},configMerge(e,t,r,i){return new no(e,t,r,i)},envVar(e,t,r,i){return new Pn(e,t,r,i)},fileSystem(e,t,r){return new so(e,t,r)},typeGeneration(e,t,r){return new ao(e,t,r)},schemaValidation(e,t,r){return new ci(e,t,r)},browserConfig(e,t,r,i){return new oo(e,t,r,i)},plugin(e,t,r){return new lo(e,t,r)}};Iu=/^https?:\/\//;ct=new di("bunfig",{showTags:!0});mg=new go;gg=Ye(fi.cwd(),"config"),pg=Ye(fi.cwd(),"src/generated"),ju={cwd:kc.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},po=ju});function qt(e,t){let r=1,i=1;for(let n=0;n<t;n++)if(e.charCodeAt(n)===10)r++,i=1;else i++;return{line:r,column:i}}function wo(e){let t=[],r=[],i=[],n={")":"(","]":"[","}":"{"},s=0,a=0,o=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),l=e.charCodeAt(f+1);if(o!==-1){if(u===42&&l===47)r.push({start:o,end:f+2}),o=-1,f++;continue}if(s){if(u===92)f++;else if(u===s)r.push({start:a,end:f+1}),s=0;continue}if(u===47&&l===42){o=f,f++;continue}if(u===47&&l===47){let d=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:d,end:f});continue}if(u===39||u===34||u===96){s=u,a=f;continue}let p=e[f];if(p==="("||p==="["||p==="{")i.push({char:p,offset:f});else if(n[p]){let d=i.pop();if(!d||d.char!==n[p])t.push({...qt(e,f),message:`Unexpected closing delimiter ${p}`,code:"DTSX1004"})}}if(s)t.push({...qt(e,a),message:"Unterminated string literal",code:"DTSX1002"});if(o!==-1)t.push({...qt(e,o),message:"Unterminated block comment",code:"DTSX1003"});for(let f of i)t.push({...qt(e,f.offset),message:`Unclosed delimiter ${f.char}`,code:"DTSX1001"});let c=[[/\b(?:interface|class|enum)\s*(?=[{=])/g,"Declaration name expected"],[/\bfunction\s*(?=\()/g,"Function name expected"],[/\(\s*:/g,"Parameter name expected"]];for(let[f,u]of c)for(let l of e.matchAll(f)){if(r.some((p)=>l.index>=p.start&&l.index<p.end))continue;t.push({...qt(e,l.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((l)=>f.index>=l.start&&f.index<l.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...qt(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.sort((f,u)=>f.line-u.line||f.column-u.column)}var $o=()=>{};import{statSync as Bu}from"fs";import{readFile as Mu,readdir as Fg}from"fs/promises";import{createRequire as _u}from"module";import{dirname as Zu,isAbsolute as Co,join as Vu,resolve as bo}from"path";import Ju from"process";function In(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function hr(e,t,r="lf"){let i=t.replace(/\r\n/g,`
|
|
155
|
+
`;return r}}function Oh(e,t,r={}){return Fa(e,t,r,new WeakMap)}function Fa(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Pa(e,t,n,i);if(!ze(t)||!ze(e))return t;return Rh(e,t,r,i)}function Pa(e,t,r,i){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 kh(e,t);case"smart":return Sh(e,t,i);default:return t}return t}function kh(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Mn(n,i)))r.push(i);return r}function Sh(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(ze(t[0])&&ze(e[0]))return Th(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Th(e,t,r){let i=[...t];for(let n of e){if(!ze(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in n){if(i.find((c)=>ze(c)&&(a in c)&&c[a]===n[a])){o=!0;break}}if(!o)i.push(n)}return i}function Rh(e,t,r,i){let n=t;if(ze(n)&&i.has(n))return i.get(n);let s={...e};if(ze(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let a=n[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(ze(a)&&ze(c))s[o]=Fa(c,a,r,i);else if(Array.isArray(a)||Array.isArray(c))s[o]=Pa(c,a,r.arrayMergeMode||"smart",i);else s[o]=a}return s}function Da(e,t,r="replace"){return Oh(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Mn(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(!Mn(e[r],t[r]))return!1;return!0}if(ze(e)&&ze(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Mn(e[n],t[n]))return!1}return!0}return!1}function ze(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ma{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(n){let f=ci.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!zr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,h=Object.keys(u).length>0;if(!p&&!h)throw new yi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new yi(e,Error("Configuration must export a valid object"),"unknown");let w={config:Da(t,l,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)ci.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?tr.configLoad(e,f):tr.configLoad(e,Error(String(f)))}};if(o)return In.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(wn(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return Eh(async()=>{return zr(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!zr(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let a=wn(e,`${s}${o}`);if(await this.checkFileAccess(a))i.push(a)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=wn(e,o);if(await this.checkFileAccess(a))i.push(a)}}catch{return[]}return i}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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!zr(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}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(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Ia{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],p);else return this.validateWithJSONSchema(e,t,p)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await In.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!uu(t))throw new $i(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new $i(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(i.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.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)i.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)i.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))i.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)i.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)i.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 a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(i.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,f,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(i.push(...a),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.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))i.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 n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,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:Nh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Wh(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Ba{fileLoader=new Ma;envProcessor=new Kn;validator=new Ia;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...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(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))a={...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(!f)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(a.config,n,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)ut.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw ut.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||wi.cwd(),p=[],h=await this.loadLocalConfiguration(i,n,l,o,a,f,u,c,r);if(h)return p.push(...this.getLocalSearchPaths(i,n,l,o)),this.finalizeResult(h,p,c,i,u);let w=await this.loadHomeConfiguration(i,n,a,f,u,c);if(w)return p.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(w,p,c,i,u);let A=await this.loadPackageJsonConfiguration(i,n,l,a,f,u,c);if(A)return p.push(He(l,"package.json")),this.finalizeResult(A,p,c,i,u);if(p.push(...this.getAllSearchPaths(i,n,l,o)),t)throw tr.configNotFound(i,p,n);return{...await this.applyEnvironmentVariables(i,a,c,u),warnings:[`No configuration file found for "${i}"${Wh(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,a,c){let f=a?Qr(e,n,o):n,u=this.getLocalDirectories(r,i);for(let l of u){if(o)ut.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),h=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(h){if(o)ut.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?Qr(e,r,n):r,a=[He(Jt(),".config",e),He(Jt(),".config"),Jt()];for(let c of a){if(n)ut.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,o,{arrayStrategy:i,verbose:n});if(u){if(n)ut.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let a=o?Qr(e,i,s):i;try{let c=He(r,"package.json");if(!Ef(c))return null;let f={};try{f=JSON.parse(Of(c,"utf8"))}catch(p){if(s)ut.warn("Failed to parse package.json:",[p instanceof Error?p:Error(String(p))]);return null}let u=f[e],l=e;if(!u&&t){let p=Array.isArray(t)?t:[t];for(let h of p){if(!h)continue;if(f[h]){u=f[h],l=h;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)ut.success(`Configuration loaded from package.json: ${l}`);return{config:Da(a,u,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)ut.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Qr(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw tr.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ci.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);ci.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}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,He(e,"config"),He(e,".config"),t?He(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(He(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[He(Jt(),".config",e),He(Jt(),".config"),Jt()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Qr(e,t,r=!1){let i=new Kn,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let l=[...a,f],p=[`${n}_${l.join("_").toUpperCase()}`,`${n}_${l.map((A)=>A.toUpperCase()).join("")}`,`${n}_${l.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,w;for(let A of p)if(h=wi.env[A],h!==void 0){w=A;break}if(h!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let A=Number(h);if(!Number.isNaN(A))c[f]=A}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((A)=>A.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var ci,In,hu,du=(e)=>e,gu=(e,t)=>{for(var r in t)hu(e,r,{get:t[r],enumerable:!0,configurable:!0,set:mu.bind(t,r)})},pu=(e,t)=>()=>(e&&(t=e(e=0)),t),aa,pa,er,wr,ya,Ju,Vu,Yo,ti,Sn,Ie,me,Yu,Ko,Ku,Go,Gu,Uu,Cn,Hu,Uo,Ho,bn,qu,zu,Xu,Qu,ri,$a,eh,Be,th,rh,qo,ii,Tn,Te,ee,ih,zo,nh,Xo,sh,oh,An,ah,Qo,ea,lh,vn,ch,fh,uh,hh,dh,ni,wa,mh,gh="0.15.6",Ve,mi,yr,Rn,Nn,gi,Wn,Fn,$r,Pn,Dn,Ot,Ca,ba,Qe,gt,Aa,va,ph,$h,xa,pi,zg,Pe,te,Xg,Ch,Qg,bh,ep,tp,ta,rp,Ah,vh,ip,ra,np,sp,op,ap,lp,xn,xh,cp,et,Oa,yi,ka,Sa,Yn,Ta,Ra,$i,Na,Wa,tr,Nh,ut,fp,up,hp,Fh,La;var ja=ue(()=>{ci=new sa,In=new oa,hu=Object.defineProperty;aa={};gu(aa,{withErrorRecovery:()=>fa,tryLoadConfig:()=>Lu,loadConfigWithResult:()=>Iu,loadConfig:()=>ga,isRetryableError:()=>Nu,isConfigNotFoundError:()=>Ru,isBunfigError:()=>ua,globalPerformanceMonitor:()=>wr,globalCache:()=>er,getEnvOrDefault:()=>Wu,generateConfigTypes:()=>ju,defaultGeneratedDir:()=>va,defaultConfigDir:()=>Aa,deepMergeWithArrayStrategy:()=>Zn,deepMerge:()=>ha,createLibraryConfig:()=>_u,config:()=>Bu,bunfigPlugin:()=>Zu,applyEnvVarsToConfig:()=>gr,TypeGenerationError:()=>Fn,SchemaValidationError:()=>$r,PluginError:()=>Dn,PerformanceMonitor:()=>Ln,FileSystemError:()=>Wn,ErrorFactory:()=>Ot,EnvVarError:()=>gi,EnvProcessor:()=>Ci,ConfigValidator:()=>Jn,ConfigValidationError:()=>Rn,ConfigNotFoundError:()=>mi,ConfigMergeError:()=>Nn,ConfigLoader:()=>Vn,ConfigLoadError:()=>yr,ConfigFileLoader:()=>bi,ConfigCache:()=>Bn,CacheUtils:()=>ya,BunfigError:()=>Ve,BrowserConfigError:()=>Pn,ArrayMergeStrategies:()=>Ca});ph=pu(async()=>{pa=import.meta.require,er=new Bn,wr=new Ln,ya={createKey:yu,isEquivalent:$u,estimateMemoryUsage:wu},Ju=ai(On.cwd(),"config"),Vu=ai(On.cwd(),"src/generated"),Yo=oi.env.CLARITY_LOG_DIR||Wf(Au(),"logs"),ti={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Yo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Sn=await vu(),Ie={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"},me=Ie,Yu=Ie.red,Ko=Ie.green,Ku=Ie.yellow,Go=Ie.blue,Gu=Ie.magenta,Uu=Ie.cyan,Cn=Ie.white,Hu=Ie.gray,Uo=Ie.bgRed,Ho=Ie.bgYellow,bn=Ie.bold,qu=Ie.dim,zu=Ie.italic,Xu=Ie.underline,Qu=Ie.reset,ri={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$a={debug:"\uD83D\uDD0D",info:Go("\u2139"),success:Ko("\u2713"),warning:Ho(Cn(bn(" WARN "))),error:Uo(Cn(bn(" ERROR ")))},eh=new ui("stacks"),Be=new ui("bunfig",{showTags:!0}),th=_e(pr.cwd(),"config"),rh=_e(pr.cwd(),"src/generated"),qo=si.env.CLARITY_LOG_DIR||Rf(ku(),"logs"),ii={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:qo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Tn=await Su(),Te={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"},ee=Te,ih=Te.red,zo=Te.green,nh=Te.yellow,Xo=Te.blue,sh=Te.magenta,oh=Te.cyan,An=Te.white,ah=Te.gray,Qo=Te.bgRed,ea=Te.bgYellow,lh=Te.bgGray,vn=Te.bold,ch=Te.dim,fh=Te.italic,uh=Te.underline,hh=Te.strikethrough,dh=Te.reset,ni={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},wa={debug:"\uD83D\uDD0D",info:Xo("\u2139"),success:zo("\u2713"),warning:ea(An(vn(" WARN "))),error:Qo(An(vn(" ERROR ")))},mh=new di("stacks"),Ve=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},mi=class extends Ve{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r?` or alias "${r}"`:"";super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},yr=class extends Ve{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Rn=class extends Ve{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Nn=class extends Ve{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},gi=class extends Ve{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},Wn=class extends Ve{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Fn=class extends Ve{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},$r=class extends Ve{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Pn=class extends Ve{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},Dn=class extends Ve{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Ot={configNotFound(e,t,r){return new mi(e,t,r)},configLoad(e,t,r){return new yr(e,t,r)},configValidation(e,t,r){return new Rn(e,t,r)},configMerge(e,t,r,i){return new Nn(e,t,r,i)},envVar(e,t,r,i){return new gi(e,t,r,i)},fileSystem(e,t,r){return new Wn(e,t,r)},typeGeneration(e,t,r){return new Fn(e,t,r)},schemaValidation(e,t,r){return new $r(e,t,r)},browserConfig(e,t,r,i){return new Pn(e,t,r,i)},plugin(e,t,r){return new Dn(e,t,r)}},Ca={replace:"replace",concat:"concat",smart:"smart"},ba=/^https?:\/\//,Qe=new di("bunfig",{showTags:!0}),gt=new Vn,Aa=Ze(Rt.cwd(),"config"),va=Ze(Rt.cwd(),"src/generated")});$h=li.env.CLARITY_LOG_DIR||eu(yh(),"logs"),xa={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$h,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},pi={...xa},zg=(async()=>{try{let{loadConfig:e}=await ph().then(()=>aa),t=await e({name:"clarity",alias:"logging",defaultConfig:xa,cwd:li.cwd()});if(t)Object.assign(pi,t)}catch{}return pi})();Pe={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"},te=Pe,Xg=Pe.red,Ch=Pe.green,Qg=Pe.yellow,bh=Pe.blue,ep=Pe.magenta,tp=Pe.cyan,ta=Pe.white,rp=Pe.gray,Ah=Pe.bgRed,vh=Pe.bgYellow,ip=Pe.bgGray,ra=Pe.bold,np=Pe.dim,sp=Pe.italic,op=Pe.underline,ap=Pe.strikethrough,lp=Pe.reset,xn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xh={debug:"\uD83D\uDD0D",info:bh("\u2139"),success:Ch("\u2713"),warning:vh(ta(ra(" WARN "))),error:Ah(ta(ra(" ERROR ")))};cp=new Ai("stacks");et=class et extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};Oa=class Oa extends et{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};yi=class yi extends et{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};ka=class ka extends et{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Sa=class Sa extends et{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}};Yn=class Yn extends et{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}};Ta=class Ta extends et{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Ra=class Ra extends et{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};$i=class $i extends et{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Na=class Na extends et{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}};Wa=class Wa extends et{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};tr={configNotFound(e,t,r){return new Oa(e,t,r)},configLoad(e,t,r){return new yi(e,t,r)},configValidation(e,t,r){return new ka(e,t,r)},configMerge(e,t,r,i){return new Sa(e,t,r,i)},envVar(e,t,r,i){return new Yn(e,t,r,i)},fileSystem(e,t,r){return new Ta(e,t,r)},typeGeneration(e,t,r){return new Ra(e,t,r)},schemaValidation(e,t,r){return new $i(e,t,r)},browserConfig(e,t,r,i){return new Na(e,t,r,i)},plugin(e,t,r){return new Wa(e,t,r)}};Nh=/^https?:\/\//;ut=new Ai("bunfig",{showTags:!0});fp=new Ba;up=He(wi.cwd(),"config"),hp=He(wi.cwd(),"src/generated"),Fh={cwd:xf.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},La=Fh});function rr(e,t){let r=1,i=1;for(let n=0;n<t;n++)if(e.charCodeAt(n)===10)r++,i=1;else i++;return{line:r,column:i}}function _a(e){let t=[],r=[],i=[],n={")":"(","]":"[","}":"{"},s=0,o=0,a=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),l=e.charCodeAt(f+1);if(a!==-1){if(u===42&&l===47)r.push({start:a,end:f+2}),a=-1,f++;continue}if(s){if(u===92)f++;else if(u===s)r.push({start:o,end:f+1}),s=0;continue}if(u===47&&l===42){a=f,f++;continue}if(u===47&&l===47){let h=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:h,end:f});continue}if(u===39||u===34||u===96){s=u,o=f;continue}let p=e[f];if(p==="("||p==="["||p==="{")i.push({char:p,offset:f});else if(n[p]){let h=i.pop();if(!h||h.char!==n[p])t.push({...rr(e,f),message:`Unexpected closing delimiter ${p}`,code:"DTSX1004"})}}if(s)t.push({...rr(e,o),message:"Unterminated string literal",code:"DTSX1002"});if(a!==-1)t.push({...rr(e,a),message:"Unterminated block comment",code:"DTSX1003"});for(let f of i)t.push({...rr(e,f.offset),message:`Unclosed delimiter ${f.char}`,code:"DTSX1001"});let c=[[/\b(?:interface|class|enum)\s*(?=[{=])/g,"Declaration name expected"],[/\bfunction\s*(?=\()/g,"Function name expected"],[/\(\s*:/g,"Parameter name expected"]];for(let[f,u]of c)for(let l of e.matchAll(f)){if(r.some((p)=>l.index>=p.start&&l.index<p.end))continue;t.push({...rr(e,l.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((l)=>f.index>=l.start&&f.index<l.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...rr(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.sort((f,u)=>f.line-u.line||f.column-u.column)}var Za=()=>{};import{statSync as Ph}from"fs";import{readFile as Dh,readdir as Rp}from"fs/promises";import{createRequire as Mh}from"module";import{dirname as Ih,isAbsolute as Ja,join as Bh,resolve as Va}from"path";import Lh from"process";function Un(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function Cr(e,t,r="lf"){let i=t.replace(/\r\n/g,`
|
|
137
156
|
`);if(!i.endsWith(`
|
|
138
157
|
`))i+=`
|
|
139
158
|
`;if(r==="crlf")i=i.replace(/\n/g,`\r
|
|
140
|
-
`);await
|
|
141
|
-
`;r++}r=Math.min(r+2,e.length);continue}if(n===44){let s=r+1;while(s<e.length){while(s<e.length&&e.charCodeAt(s)<=32)s++;if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10)s++;continue}if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===42){s+=2;while(s+1<e.length&&!(e.charCodeAt(s)===42&&e.charCodeAt(s+1)===47))s++;s=Math.min(s+2,e.length);continue}break}let
|
|
159
|
+
`);await us(e,i)}function jh(e){let t="",r=0,i=0;while(r<e.length){let n=e.charCodeAt(r);if(i){if(t+=e[r],n===92&&r+1<e.length){t+=e[r+1],r+=2;continue}if(n===i)i=0;r++;continue}if(n===34){i=n,t+=e[r++];continue}if(n===47&&e.charCodeAt(r+1)===47){r+=2;while(r<e.length&&e.charCodeAt(r)!==10)r++;continue}if(n===47&&e.charCodeAt(r+1)===42){r+=2;while(r+1<e.length&&!(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47)){if(e.charCodeAt(r)===10)t+=`
|
|
160
|
+
`;r++}r=Math.min(r+2,e.length);continue}if(n===44){let s=r+1;while(s<e.length){while(s<e.length&&e.charCodeAt(s)<=32)s++;if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10)s++;continue}if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===42){s+=2;while(s+1<e.length&&!(e.charCodeAt(s)===42&&e.charCodeAt(s+1)===47))s++;s=Math.min(s+2,e.length);continue}break}let o=e.charCodeAt(s);if(o===93||o===125){r++;continue}}t+=e[r++]}return t}function Gn(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(Bh(e,"tsconfig.json"));for(let r of t)try{if(Ph(r).isFile())return r}catch{}return null}function _h(e,t){if(Ja(e)||e.startsWith("."))return Gn(Va(Ih(t),e));let r=Mh(t);for(let i of[e,`${e}/tsconfig.json`])try{let n=Gn(r.resolve(i));if(n)return n}catch{}return null}async function Ya(e,t){let r=Gn(e);if(!r||t.has(r))return;t.add(r);let i=await Dh(r,"utf8"),n=JSON.parse(jh(i)),s=typeof n.extends==="string"?[n.extends]:n.extends??[],o;for(let a of s){let c=_h(a,r);if(!c)continue;let f=await Ya(c,t);if(f!==void 0)o=f}return n.compilerOptions?.isolatedDeclarations??o}async function Ka(e){try{let t=e?.cwd||Lh.cwd(),r=e?.tsconfigPath||"tsconfig.json",i=Ja(r)?r:Va(t,r);return await Ya(i,new Set)??!1}catch{return!1}}function Ga(e,t){let r={isValid:!0,errors:[]};for(let i of _a(e))r.errors.push({line:i.line,column:i.column,message:i.message,code:i.code});return r.isValid=r.errors.length===0,r}function Ua(e,t,r){if(e===t)return"";let i=e.split(`
|
|
142
161
|
`),n=t.split(`
|
|
143
|
-
`),s=new Map,
|
|
144
|
-
`)}function
|
|
145
|
-
`),s=[];function
|
|
146
|
-
`).length;for(let l=0;l<n.length;l++){if(n[l].trim()===""){s.push("");continue}
|
|
147
|
-
${
|
|
148
|
-
`}var
|
|
149
|
-
`),s=e.location.line-1;if(s>=0&&s<n.length){let
|
|
150
|
-
`)}var
|
|
162
|
+
`),s=new Map,o=new Map;for(let u=0;u<i.length;u++)s.set(i[u],(s.get(i[u])??0)+1);for(let u=0;u<n.length;u++)o.set(n[u],(o.get(n[u])??0)+1);let a=[],c=[];for(let[u,l]of s){let p=l-(o.get(u)??0);for(let h=0;h<p;h++)a.push(u)}for(let[u,l]of o){let p=l-(s.get(u)??0);for(let h=0;h<p;h++)c.push(u)}if(a.length===0&&c.length===0)return"";let f=[`--- ${r}`,`+++ ${r}`];for(let u=0;u<a.length;u++)f.push(`- ${a[u]}`);for(let u=0;u<c.length;u++)f.push(`+ ${c[u]}`);return f.join(`
|
|
163
|
+
`)}function Ha(e,t,r,i){let n=e.split(`
|
|
164
|
+
`),s=[];function o(l){let p="",h=l<0?-l<<1|1:l<<1;do{let w=h&31;if(h>>>=5,h>0)w|=32;p+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[w]}while(h>0);return p}let a=0,c=0,f=0,u=i.split(`
|
|
165
|
+
`).length;for(let l=0;l<n.length;l++){if(n[l].trim()===""){s.push("");continue}a=0;let p=Math.min(l,u-1),h=[],w=0-a,A=0,$=p-c,x=0-f;h.push(o(w)+o(A)+o($)+o(x)),a=0,c=p,f=0,s.push(h.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[i],mappings:s.join(";")}}function qa(e,t){return`${e}
|
|
166
|
+
${Un()}${t}
|
|
167
|
+
`}var za=ue(()=>{Or();Za()});class vi{plugins=[];config=null;register(e){if(this.plugins.some((t)=>t.name===e.name))throw Error(`Plugin "${e.name}" is already registered`);this.plugins.push(e)}unregister(e){let t=this.plugins.findIndex((r)=>r.name===e);if(t>=0)return this.plugins.splice(t,1),!0;return!1}getPlugins(){return this.plugins}createLogger(e){return{debug:(t)=>console.debug(`[${e}] ${t}`),info:(t)=>console.info(`[${e}] ${t}`),warn:(t)=>console.warn(`[${e}] ${t}`),error:(t)=>console.error(`[${e}] ${t}`)}}async runOnStart(e){let t=e;for(let r of this.plugins)if(r.onStart){let i=await r.onStart(t);if(i)t=i}return this.config=t,t}async runOnBeforeFile(e,t){let r=t;for(let i of this.plugins)if(i.onBeforeFile){let n={filePath:e,sourceCode:t,content:r,config:this.config,log:this.createLogger(i.name)},s=await i.onBeforeFile(n);if(typeof s==="string")r=s}return r}async runOnDeclarations(e,t,r){let i=r;for(let n of this.plugins)if(n.onDeclarations){let s={filePath:e,sourceCode:t,declarations:i,config:this.config,log:this.createLogger(n.name)},o=await n.onDeclarations(s);if(o)i=o}return i}async runOnAfterFile(e,t,r){let i=r;for(let n of this.plugins)if(n.onAfterFile){let s={filePath:e,sourceCode:t,content:i,config:this.config,log:this.createLogger(n.name)},o=await n.onAfterFile(s);if(typeof o==="string")i=o}return i}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,r){for(let i of this.plugins)if(i.onError){let n={filePath:t,sourceCode:r,config:this.config,log:this.createLogger(i.name)};await i.onError(e,n)}}}function Zh(e){return e}var Dp,Mp;var Xa=ue(()=>{Dp=new vi;Mp=Zh({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(e)=>{return e.declarations.filter((t)=>{if(t.leadingComments){if(t.leadingComments.some((r)=>r.includes("@internal")))return e.log.debug(`Stripping internal declaration: ${t.name}`),!1}return!0})}})});function Qa(e,t,r){let i={file:t,message:"Unknown error",code:br.UNKNOWN_ERROR};if(e instanceof Error){i.message=e.message,i.stack=e.stack;let n=e.message.match(/\((\d+),(\d+)\)/);if(n)i.location={line:Number.parseInt(n[1],10),column:Number.parseInt(n[2],10)};if(e.message.includes("Cannot find")||e.message.includes("not found"))i.code=br.FILE_NOT_FOUND,i.suggestion="Check that the file path is correct and the file exists.";else if(e.message.includes("syntax")||e.message.includes("Unexpected token"))i.code=br.SYNTAX_ERROR,i.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))i.code=br.TYPE_INFERENCE_ERROR,i.suggestion="Add explicit type annotations to help with type inference.";else if(e.message.includes("parse")||e.message.includes("Parse"))i.code=br.PARSE_ERROR,i.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")i.message=e;return i}function el(e,t){let r=[],i=e.file;if(e.location)i+=`:${e.location.line}:${e.location.column}`;if(e.code)i+=` [${e.code}]`;if(r.push(i),r.push(` Error: ${e.message}`),t&&e.location){r.push("");let n=t.split(`
|
|
168
|
+
`),s=e.location.line-1;if(s>=0&&s<n.length){let o=Math.max(0,s-1),a=Math.min(n.length-1,s+1);for(let c=o;c<=a;c++){let f=(c+1).toString().padStart(4," "),u=c===s?">":" ";if(r.push(` ${u} ${f} | ${n[c]}`),c===s&&e.location.column>0){let l=" ".repeat(10+e.location.column-1);r.push(` ${l}^`)}}}}if(e.suggestion)r.push(""),r.push(` Suggestion: ${e.suggestion}`);return r.join(`
|
|
169
|
+
`)}var br;var tl=ue(()=>{br={PARSE_ERROR:"PARSE_ERROR",SYNTAX_ERROR:"SYNTAX_ERROR",FILE_NOT_FOUND:"FILE_NOT_FOUND",FILE_READ_ERROR:"FILE_READ_ERROR",FILE_WRITE_ERROR:"FILE_WRITE_ERROR",TYPE_INFERENCE_ERROR:"TYPE_INFERENCE_ERROR",UNRESOLVED_TYPE:"UNRESOLVED_TYPE",EXTRACTION_ERROR:"EXTRACTION_ERROR",PROCESSING_ERROR:"PROCESSING_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",INVALID_DECLARATION:"INVALID_DECLARATION",CONFIG_ERROR:"CONFIG_ERROR",INVALID_ENTRYPOINT:"INVALID_ENTRYPOINT",CIRCULAR_DEPENDENCY:"CIRCULAR_DEPENDENCY",TIMEOUT_ERROR:"TIMEOUT_ERROR",NOT_SUPPORTED:"NOT_SUPPORTED",UNKNOWN_ERROR:"UNKNOWN_ERROR"}});function Gh(e){switch(e){case"strict":return Vh;case"readonly":return Yh;case"simplified":return Kh;case"nullable":return[{pattern:/^(.+)\s*\|\s*undefined$/,replacement:"$1 | undefined",priority:5}];case"branded":return[{pattern:/^string$/,replacement:"string",condition:(t)=>t.declarationKind==="variable"&&(t.declarationName?.includes("path")??!1),priority:5}];default:return[]}}class il{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...Jh);if(e.presets)for(let t of e.presets)this.rules.push(...Gh(t));this.rules.push(...e.rules),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile()}recompile(){let e=Array(this.rules.length);for(let t=0;t<this.rules.length;t++){let r=this.rules[t],i=typeof r.pattern==="string"?new RegExp(r.pattern.replace(Uh,"\\$&"),r.global?"g":""):r.pattern;e[t]={rule:r,regex:i}}this.compiled=e}map(e,t={}){let r=!t.declarationName&&!t.declarationKind&&!t.filePath&&!t.isReturnType&&!t.isParameterType&&!t.isPropertyType?e:`${e}\x00${t.declarationName??""}\x00${t.declarationKind??""}\x00${t.filePath??""}\x00${t.isReturnType?"r":""}${t.isParameterType?"p":""}${t.isPropertyType?"P":""}`,i=this.cache.get(r);if(i!==void 0)return i;let n=e,s=null;for(let o=0;o<this.compiled.length;o++){let{rule:a,regex:c}=this.compiled[o];if(a.condition){if(!s)s={type:e,...t};if(!a.condition(s))continue}if(c.lastIndex=0,c.test(n)){if(c.lastIndex=0,n=n.replace(c,a.replacement),c.lastIndex=0,!a.global)break}}if(this.cache.size>=rl){let o=Math.ceil(rl*0.1),a=0;for(let c of this.cache.keys()){if(a++>=o)break;this.cache.delete(c)}}return this.cache.set(r,n),n}mapAll(e,t={}){return e.map((r)=>this.map(r,{...t,type:r}))}addRule(e){this.rules.push(e),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let t=this.rules.length;return this.rules=this.rules.filter((r)=>{let i=typeof r.pattern==="string"?r.pattern:r.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?i!==e:!e.test(i)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function xi(e={rules:[]}){return new il(e)}function nl(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(i,n)=>{return`: ${t.map(n.trim(),r)}`})}var Jh,Vh,Yh,Kh,Uh,rl=2048,Lp,jp;var sl=ue(()=>{Jh=[{pattern:/^Promise<void>$/,replacement:"Promise<void>",priority:-1},{pattern:/^Record<string,\s*any>$/,replacement:"Record<string, unknown>",priority:0},{pattern:/^Array<([^<>]+)>$/,replacement:"$1[]",priority:0}],Vh=[{pattern:/\bany\b/,replacement:"unknown",global:!0,priority:10},{pattern:/^object$/,replacement:"Record<string, unknown>",priority:10},{pattern:/^Function$/,replacement:"(...args: unknown[]) => unknown",priority:10}],Yh=[{pattern:/^(\w+)\[\]$/,replacement:"readonly $1[]",priority:5},{pattern:/^Array<(.+)>$/,replacement:"ReadonlyArray<$1>",priority:5},{pattern:/^Map<(.+),\s*(.+)>$/,replacement:"ReadonlyMap<$1, $2>",priority:5},{pattern:/^Set<(.+)>$/,replacement:"ReadonlySet<$1>",priority:5}],Kh=[{pattern:/^Partial<Partial<(.+)>>$/,replacement:"Partial<$1>",priority:5},{pattern:/^Required<Required<(.+)>>$/,replacement:"Required<$1>",priority:5},{pattern:/^Pick<Omit<(.+),\s*(.+)>,\s*(.+)>$/,replacement:"Pick<$1, $3>",priority:5}];Uh=/[.*+?^${}()|[\]\\]/g;Lp=xi({rules:[]}),jp=xi({rules:[],presets:["strict"]})});function pt(e,t=!0){if(!t||!e||e.length===0)return"";if(e.length===1){let i=e[0];if(i.length>0&&i.charCodeAt(0)>32&&i.charCodeAt(i.length-1)>32)return`${i}
|
|
151
170
|
`;return`${i.trim()}
|
|
152
171
|
`}let r="";for(let i=0;i<e.length;i++){if(i>0)r+=`
|
|
153
172
|
`;r+=e[i].trim()}return`${r}
|
|
154
|
-
`}var
|
|
155
|
-
`){let n=r,s=i;while(n<s&&(e[n]===" "||e[n]==="\t"||e[n]==="\r"))n++;while(s>n&&(e[s-1]===" "||e[s-1]==="\t"||e[s-1]==="\r"))s--;let
|
|
173
|
+
`}var ol=()=>{};function Xh(e){let t=[],r=0;for(let i=0;i<=e.length;i++)if(i===e.length||e[i]===`
|
|
174
|
+
`){let n=r,s=i;while(n<s&&(e[n]===" "||e[n]==="\t"||e[n]==="\r"))n++;while(s>n&&(e[s-1]===" "||e[s-1]==="\t"||e[s-1]==="\r"))s--;let o=e.slice(n,s);if(r=i+1,o.startsWith("///")){if(o.indexOf("<")===-1)continue;if(Hh.test(o)||qh.test(o)||zh.test(o))t.push(o)}else if(o===""||o.startsWith("//"))continue;else break}return t}function Qh(e){if(e.includes(`
|
|
156
175
|
`))return`/**
|
|
157
176
|
* ${e}
|
|
158
177
|
*/
|
|
159
178
|
`;return`/** ${e} */
|
|
160
|
-
`}function
|
|
161
|
-
`))
|
|
179
|
+
`}function ed(e){let t=e.indexOf("{");if(t===-1)return-1;let r=e.indexOf("<");if(r===-1||r>t)return t;let i=0,n=!1,s="";for(let o=0;o<e.length;o++){let a=e[o],c=o>0?e[o-1]:"";if(!n&&(a==='"'||a==="'"||a==="`"))n=!0,s=a;else if(n&&a===s&&c!=="\\")n=!1;if(!n){if(a==="<")i++;else if(a===">")i--;else if(a==="{"&&i===0)return o}}return-1}function td(e,t=!0){return pt(e.leadingComments,t)+e.text}function rd(e,t=!0){let r=pt(e.leadingComments,t);if(e.typeAnnotation&&!e.value)return r+e.text;let i="";if(e.isExported)i+="export ";i+="declare ";let n=e.modifiers?.[0]||"const";i+=`${n} `,i+=e.name;let{typeAnnotation:s,value:o}=e;if(o&&o.includes(" satisfies ")){let c=Ms(o);if(c)s=c}else if(!s&&o&&o.trim().endsWith("as const"))s=xe(o,!0);else if(!s&&o&&n==="const"){let c=o.trim(),f=c.startsWith("{")||c.startsWith("[");if(f)Hi();s=xe(o,!f)}else if(!s&&o)s=xe(o,n==="const");if(!s)s="unknown";let a="";if(t&&o&&!e.typeAnnotation&&!o.trim().endsWith("as const")){let c=o.trim();if(n!=="const"){if((s==="string"||s==="number"||s==="boolean")&&c.length>0)a=`@defaultValue ${c}`}else if(c.startsWith("{")||c.startsWith("[")){let f=qi();if(f)if(f.includes(`
|
|
180
|
+
`))a=`@defaultValue
|
|
162
181
|
* \`\`\`ts
|
|
163
182
|
${f.split(`
|
|
164
183
|
`).map((u)=>` * ${u}`).join(`
|
|
165
184
|
`)}
|
|
166
|
-
* \`\`\``;else
|
|
167
|
-
`))
|
|
185
|
+
* \`\`\``;else a=`@defaultValue \`${f}\``}}else if(t&&o&&e.typeAnnotation&&Ds(e.typeAnnotation)){Hi();let c=o.trim(),f=c.endsWith("as const")?c.slice(0,-8).trim():c;xe(f,!1);let u=qi();if(u)if(u.includes(`
|
|
186
|
+
`))a=`@defaultValue
|
|
168
187
|
* \`\`\`ts
|
|
169
188
|
${u.split(`
|
|
170
189
|
`).map((l)=>` * ${l}`).join(`
|
|
171
190
|
`)}
|
|
172
|
-
* \`\`\``;else
|
|
191
|
+
* \`\`\``;else a=`@defaultValue \`${u}\``}if(i+=`: ${s};`,a&&r&&r.includes("@defaultValue"))a="";if(a&&r){let c=r.trimEnd(),f=c.lastIndexOf("*/");if(f!==-1){let u=c.slice(0,f).trimEnd();if(u.startsWith("/** ")&&!u.includes(`
|
|
173
192
|
`))u=`/**
|
|
174
193
|
* ${u.slice(4)}`;return`${u}
|
|
175
|
-
* ${
|
|
194
|
+
* ${a}
|
|
176
195
|
*/
|
|
177
196
|
`+i}return`/**
|
|
178
197
|
* ${c.replace(/^\/\/\s*/,"")}
|
|
179
|
-
* ${
|
|
198
|
+
* ${a}
|
|
180
199
|
*/
|
|
181
|
-
${i}`}if(
|
|
182
|
-
`;n+=Z[q]}}}let
|
|
183
|
-
`));for(let q of f)if(Z.has(q.name))b.add(q.name)}}let
|
|
184
|
-
`);if(q&&
|
|
185
|
-
`;n+=
|
|
186
|
-
`;n
|
|
187
|
-
`;n+=
|
|
188
|
-
`;n+=x[P]}for(let P=0;P<
|
|
189
|
-
`;n+=
|
|
190
|
-
${
|
|
191
|
-
${
|
|
192
|
-
...`:"")),
|
|
193
|
-
`);if(r.failOnUnresolvedReExport)throw Error(
|
|
194
|
-
--- Generation Statistics ---`),
|
|
195
|
-
Errors:`);for(let
|
|
196
|
-
`)}if(r.plugins&&r.plugins.length>0)await i.runOnEnd(a);return V.debug("DTS generation complete!"),a}async function Go(e){try{return await $h(e)}catch{return ze(e)}}async function Eh(e){let t=ze(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(Mn(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let n=ze(t,e.bundleOutput);if(!pi(n,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===Ah(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,i]=await Promise.all([Go(t),Go(ze(e.cwd,e.root))]);if(pi(i,r))throw Error("Refusing to clean an outdir that contains the source root")}function Oh(e){let t=mr.get(e);if(!t){if(t=new Yo(e),mr.set(e,t),mr.size>xh){let r=mr.keys().next().value;if(r!==void 0)mr.delete(r)}}return t}async function Sh(e){let t=ze(e.cwd,e.outdir);async function r(i){let n;try{n=await wh(i,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async(s)=>{let a=ze(i,s.name);if(s.isDirectory()){await r(a);return}if(s.name.endsWith(".d.ts")||s.name.endsWith(".d.mts")||s.name.endsWith(".d.cts")||s.name.endsWith(".d.ts.map")||s.name.endsWith(".d.mts.map")||s.name.endsWith(".d.cts.map"))await Ch(a,{force:!0})}))}await r(t)}function jn(e,t,r){if(!t||t.length===0)return!1;let i=Ne(r,e);for(let n of t){let s=Oh(n);if(s.match(i)||s.match(e))return!0}return!1}async function kh(e){let t=[],r=ze(e.cwd,e.root),i=e.exclude||[],n=[...e.entrypoints,...e.include??[]];for(let s of n)if(Mn(s)&&Bn(s)){if(!s.includes("node_modules")){if(!pi(s,r)&&e.outputStructure!=="flat")V.warn(`Skipping entrypoint outside root: ${Ne(e.cwd,s)}`);else if(!jn(s,i,r))t.push(s)}}else{let a=new Yo(s);for await(let o of a.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(Bn(o)&&!o.includes("node_modules")){if(!jn(o,i,r))t.push(o)}}return[...new Set(t)].sort()}function pi(e,t){let r=Ne(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Mn(r)}function Th(e,t){let r=new Map;for(let i of e){let n=pr(i,t),s=r.get(n);if(s&&s!==i)throw Error(`Output path collision: ${Ne(t.cwd,s)} and ${Ne(t.cwd,i)} both emit ${Ne(t.cwd,n)}`);r.set(n,i)}}function Bn(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function pr(e,t){let r=ze(t.cwd,t.root),i=Ne(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs)$/,(n)=>{if(n===".mts"||n===".mjs")return".d.mts";if(n===".cts"||n===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return ze(t.cwd,t.outdir,i);else{let n=i.split("/").pop();return ze(t.cwd,t.outdir,n)}}function Rh(e,t,r=""){let i=Ne(gr(e),t).replace(/\\/g,"/");if(i=i.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)i+=r;if(!i.startsWith("."))i=`./${i}`;return i}function Nh(e,t,r){let i=pr(t,r),n=(s)=>{let a=br(s,t);if(!a.isRelative||!a.resolved)return s;if(/\.d\.(?:ts|mts|cts)$/.test(a.resolved))return s;let o=s.match(/[?#].*$/)?.[0]??"",c=o?s.slice(0,-o.length):s,f=vh(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return Rh(i,pr(a.resolved,r),u)+o};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${n(c)}${o}`}).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${n(c)}${o}`}).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${n(c)}${o}`})}async function Wh(e,t,r,i,n){let s=t;if(i)s=await i.runOnBeforeFile(e,t);let a=kr(s,e,r.keepComments,r.isolatedDeclarations??!1);if(i)a=await i.runOnDeclarations(e,s,a);let o=0,c=0;for(let u=0;u<a.length;u++){let l=a[u];if(l.kind==="import")o++;if(l.kind==="export"||l.isExported)c++}let f=Jo(a,{filePath:e,sourceCode:s,declarations:a},r.keepComments,r.importOrder);if(f=Nh(f,e,r),n)f=Do(f,n,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=Bs(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(i)f=await i.runOnAfterFile(e,s,f);return{content:f,declarationCount:a.length,importCount:o,exportCount:c}}var Yo,xh=50,mr;var qo=he(()=>{is();cs();Is();Ms();Zs();ko();$r();yo();To();Wo();Io();Ko();Us();Ki();us();({Glob:Yo}=globalThis.Bun);mr=new Map});var zo=he(()=>{qo()});var rl={};dl(rl,{dtsWatch:()=>Jh,dtsCheck:()=>Kh,dts:()=>Zn,default:()=>Gh,clearCache:()=>Uh,PluginErrorCodes:()=>_h,DtsxPluginError:()=>zt});import{createHash as Fh}from"crypto";import{existsSync as Dh,readFileSync as Ih,writeFileSync as Lh}from"fs";import{dirname as jh,join as Bh,relative as Xo,resolve as yr,sep as wi}from"path";import Mh from"process";class Qo{listeners=new Map;on(e,t){let r=this.listeners.get(e)||[];r.push(t),this.listeners.set(e,r)}async emit(e,t){let r={type:e,timestamp:Date.now(),data:t},i=this.listeners.get(e)||[];for(let n of i)await n(r)}}class _n{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=Bh(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(Dh(this.manifestPath)){let t=JSON.parse(Ih(this.manifestPath,"utf-8"));if(t.configHash===e&&t.version==="1.0")return t}}catch{}return{version:"1.0",configHash:e,entries:{}}}save(){try{let{mkdirSync:e}=Ph("fs");e(this.cacheDir,{recursive:!0}),Lh(this.manifestPath,JSON.stringify(this.manifest,null,2))}catch{}}getEntry(e){return this.manifest.entries[e]}setEntry(e,t){this.manifest.entries[e]=t}isValid(e,t){return this.getEntry(e)?.hash===t}clear(){this.manifest.entries={},this.save()}}function Zh(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return Fh("md5").update(JSON.stringify(t)).digest("hex")}function Zn(e={}){let{onSuccess:t,onError:r,failOnError:i=!0,incremental:n=!1,cacheDir:s=".dtsx-cache",on:a,timeout:o=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,l=new Qo;if(a){for(let[p,d]of Object.entries(a))if(d)l.on(p,d)}return{name:"bun-plugin-dtsx",async setup(p){let d=Date.now(),C=null,v=0;try{let w=tl(u,p),x=Zh(w);if(n)C=new _n(yr(s),x);if(await l.emit("start",{type:"start",files:w.entrypoints||[],config:w}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),n)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let S=await(async()=>{return new Promise((b,B)=>{let re=setTimeout(()=>{B(new zt(`Generation timed out after ${o}ms`,"TIMEOUT_ERROR",{timeout:o}))},o);yi(w).then((P)=>{clearTimeout(re),b(P)}).catch((P)=>{clearTimeout(re),B(P)})})})(),T=Date.now()-d;if(C)C.save();if(await l.emit("complete",{type:"complete",stats:S,duration:T,fromCache:v}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${T}ms`),v>0)console.log(`[bun-plugin-dtsx] ${v} files served from cache`)}if(t)await t(S)}catch(w){let x=el(w);if(await l.emit("error",{type:"error",error:x}),r)await r(x);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${x.code}`),console.error(` Message: ${x.message}`),x.context)console.error(` Context: ${JSON.stringify(x.context)}`);if(f&&x.stack)console.error(` Stack: ${x.stack}`)}if(i&&!c)throw x}}}}function el(e){if(e instanceof zt)return e;if(e instanceof Error){let t="GENERATION_ERROR";if(e.message.includes("config")||e.message.includes("Config"))t="CONFIG_ERROR";else if(e.message.includes("file")||e.message.includes("File")||e.message.includes("ENOENT"))t="FILE_ERROR";return new zt(e.message,t,{originalError:e.name},e)}return new zt(String(e),"GENERATION_ERROR")}function Vh(e){let t=e.map((i)=>jh(i).split(wi)),r=t[0];for(let i of t.slice(1)){let n=0;while(n<r.length&&n<i.length&&r[n]===i[n])n++;r=r.slice(0,n)}return r.join(wi)||wi}function tl(e,t){let r=e.cwd||Mh.cwd(),i=t?.config?.entrypoints,n=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",s=e.root||e.build?.config.root||t?.config.root;if(!s&&i?.length){let o=Vh(i.map((c)=>yr(r,c)));s=Xo(r,o)||"."}s=s||"./src";let a=e.entrypoints;if(!a)if(i?.length){let o=yr(r,s),c=[];for(let f of i){let u=yr(r,f);if(u===o||u.startsWith(o+wi))c.push(Xo(o,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${s}": ${f}`)}a=c.length?c:["index.ts"]}else a=["index.ts"];return{...e,cwd:r,root:s,entrypoints:a,outdir:n,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}function Jh(e={}){return Zn({...e,incremental:!0,verbose:e.verbose??!0})}function Kh(e){return{name:"bun-plugin-dtsx-check",async setup(t){let r=tl({...e,outdir:""},t);try{await yi({...r,clean:!1})}catch(i){let n=el(i);if(e.onError)await e.onError(n);if(e.failOnError!==!1)throw n}}}}function Uh(e=".dtsx-cache"){new _n(yr(e),"").clear()}var Ph,_h,zt,Gh;var il=he(()=>{zo();Ph=import.meta.require,_h={CONFIG_ERROR:"CONFIG_ERROR",GENERATION_ERROR:"GENERATION_ERROR",FILE_ERROR:"FILE_ERROR",CACHE_ERROR:"CACHE_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"};zt=class zt extends Error{code;context;cause;constructor(e,t,r,i){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=r,this.cause=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};Gh=Zn});import{mkdir as Yh,stat as Hh}from"fs/promises";import{bold as Vn,dim as Jn,green as qh,italic as nl,log as zh}from"@stacksjs/cli";import{path as et}from"@stacksjs/path";import{glob as sl}from"@stacksjs/storage";async function Xh(e){let t=await sl([et.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let i of t){let n=await Bun.file(i).text();try{r.transformSync(n)}catch(s){throw Error(`Invalid declaration generated at ${i}: ${s instanceof Error?s.message:String(s)}`)}}}async function Dp(e){let r=Date.now()-e.startTime,i=e.pkgName??`@stacksjs/${et.basename(e.dir)}`;if(e.result.errors&&e.result.errors.length>0)throw console.error("Build errors:",e.result.errors),Error(`Build failed with errors: ${JSON.stringify(e.result.errors)}`);else if(e.result.success!==void 0&&!e.result.success){let s=e.result.logs?.[0]||"Unknown build error";throw console.log(s),Error(`Build failed: ${s}`)}await Xh(e.dir);let n=await sl([et.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of n){let a=await Hh(s),o;if(a.size<1048576)o=`${(a.size/1024).toFixed(2)}kb`;else o=`${(a.size/1024/1024).toFixed(2)}mb`;let c=et.relative(e.dir,s).replace("dist/","");console.log(`${Vn(Jn(`[${o}]`))} ${Jn("dist/")}${c}`)}console.log(`${Vn(Jn(`[${r}ms]`))} Built ${nl(Vn(qh(i)))}`)}async function Ip(e){let t=e.pkgName??`@stacksjs/${et.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else zh.info(`Building ${nl(t)}...`);return{startTime:Date.now()}}async function Lp(e){let{dts:t}=await Promise.resolve().then(() => (il(),rl)),r=et.resolve(e.dir,"src"),i=et.resolve(e.dir,"dist"),n=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((a)=>!a.endsWith(".d.ts"));await Bun.build({entrypoints:n.map((a)=>et.resolve(r,a)),outdir:i,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??Qh(),plugins:[t({root:r,outdir:i})]});let s=new Bun.Transpiler({loader:"ts",target:"bun"});for(let a of n){let o=s.transformSync(await Bun.file(et.resolve(r,a)).text());o=o.replace(/(['"])(\.\.?\/[^'"]+?)\.tsx?\1/g,"$1$2.js$1");let c=et.resolve(i,a.replace(/\.ts$/,".js"));await Yh(et.dirname(c),{recursive:!0}),await Bun.write(c,o)}}function Qh(e=[]){let t=[];try{let r=Je("fs"),i=JSON.parse(r.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(i.dependencies??{}),...Object.keys(i.peerDependencies??{}),...Object.keys(i.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{Xh as validateDeclarations,Lp as transpilePackage,Dp as outro,Ip as intro,Qh as frameworkExternal};
|
|
200
|
+
${i}`}if(a)return`${Qh(a)}${i}`;return r+i}function id(e,t=!0){let r=pt(e.leadingComments,t),i=e.text;if(i.startsWith("export declare interface")||i.startsWith("declare interface"))return r+i;let n="";if(e.isExported)n+="export ";if(n+="declare interface ",n+=e.name,e.generics)n+=e.generics;if(e.extends)n+=` extends ${e.extends}`;let s=ed(e.text);if(s!==-1)n+=` ${e.text.slice(s)}`;else n+=" {}";return r+n}function nd(e,t=!0){let r=pt(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return r+e.text;let i="";if(e.isExported)i+="export ";if(!e.isExported&&!e.text.includes(" from "))i+="declare ";let n=e.text.indexOf("type ");if(n!==-1){let o=e.text.slice(n),a=o.length;while(a>0&&(o.charCodeAt(a-1)===59||o.charCodeAt(a-1)===32||o.charCodeAt(a-1)===10||o.charCodeAt(a-1)===13))a--;if(a<o.length)o=o.slice(0,a);i+=o}else{if(i+=`type ${e.name}`,e.generics)i+=e.generics;i+=" = any"}let s=i.trimEnd();if(!s.endsWith(";")&&!s.endsWith("}"))i+=";";return r+i}function sd(e,t=!0){return pt(e.leadingComments,t)+e.text}function od(e,t=!0){let r=pt(e.leadingComments,t),i="";if(e.isExported)i+="export ";if(i+="declare ",e.modifiers?.includes("const"))i+="const ";i+="enum ",i+=e.name;let n=e.text.indexOf("{");if(n!==-1)i+=` ${e.text.slice(n)}`;else i+=" {}";return r+i}function ad(e,t=!0){let r=pt(e.leadingComments,t);if(e.text.startsWith("declare global"))return r+e.text;if(e.source||(e.name.startsWith('"')||e.name.startsWith("'")||e.name.startsWith("`"))){let s="declare module ";s+=e.name;let o=e.text.indexOf("{");if(o!==-1)s+=` ${e.text.slice(o)}`;else s+=" {}";return r+s}let i="";if(e.isExported)i+="export ";if(!e.modifiers?.includes("declare"))i+="declare ";i+="namespace ",i+=e.name;let n=e.text.indexOf("{");if(n!==-1)i+=` ${e.text.slice(n)}`;else i+=" {}";return r+i}function ld(e){let t=Nt.get(e);if(t)return Nt.delete(e),Nt.set(e,t),t;return null}function al(e,t){if(Nt.set(e,t),Nt.size>200){let r=0;for(let i of Nt.keys()){if(r++>=20)break;Nt.delete(i)}}}function cd(e){let t=e.indexOf(" from ");if(t===-1)return null;let r=e.slice(t+6).trim(),i=r[0];if(i!=='"'&&i!=="'")return null;let n=r.indexOf(i,1);if(n===-1)return null;let s=r.slice(1,n),o=e.slice(0,t).trim(),a=o.startsWith("import type ");if(o.startsWith("import "))o=o.slice(7).trim();if(o.startsWith("type "))o=o.slice(5).trim();let c=null,f=[],u=!1,l=o.indexOf("{"),p=o.lastIndexOf("}");if(l!==-1&&p!==-1){let h=o.slice(0,l).trim();if(h.endsWith(","))c=h.slice(0,-1).trim()||null;let w=o.slice(l+1,p),A=0;for(let $=0;$<=w.length;$++)if($===w.length||w.charCodeAt($)===44){let x=A,S=$;while(x<S&&(w.charCodeAt(x)===32||w.charCodeAt(x)===9||w.charCodeAt(x)===10))x++;while(S>x&&(w.charCodeAt(S-1)===32||w.charCodeAt(S-1)===9||w.charCodeAt(S-1)===10))S--;if(x<S)f.push(w.slice(x,S));A=$+1}}else{let h=o.trim();if(h.startsWith("* as "))c=h.slice(5).trim()||null,u=!0;else c=h||null}return{defaultName:c,namedItems:f,source:s,isTypeOnly:a,isNamespace:u}}function fd(e){let t=ld(e);if(t)return t;let r=[],i=e.indexOf(" from ");if(i===-1)return al(e,r),r;let n=e.slice(0,i).trim();if(n.startsWith("import "))n=n.slice(7).trim();if(n.startsWith("type "))n=n.slice(5).trim();let s=n.indexOf("{"),o=n.lastIndexOf("}");if(s!==-1&&o!==-1){let a=n.slice(0,s).trim();if(a.endsWith(",")){let f=a.slice(0,-1).trim();if(f)r.push(f)}else if(a&&!a.includes(","))r.push(a);let c=n.slice(s+1,o).split(",");for(let f=0;f<c.length;f++){let u=c[f].trim();if(!u)continue;if(u.startsWith("type "))u=u.slice(5).trim();let l=u.indexOf(" as ");if(l!==-1)u=u.slice(l+4).trim();if(u)r.push(u)}}else{let a=n.trim();if(a.startsWith("* as ")){let c=a.slice(5).trim();if(c)r.push(c)}else if(a)r.push(a)}return al(e,r),r}function ll(e,t){throw Error(t||`Unexpected value: ${e}`)}function ud(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function cl(e){let t=new Set,r=0,i=e.length;while(r<i){let n=e.charCodeAt(r);if(n>=65&&n<=90||n>=97&&n<=122||n===95||n===36||n>127){let s=r;r++;while(r<i&&ud(e.charCodeAt(r)))r++;t.add(e.substring(s,r))}else r++}return t}function dl(e,t,r=!0,i=["bun"]){let n="",s=t.sourceCode;if(s){let P=0;while(P<s.length&&(s.charCodeAt(P)===32||s.charCodeAt(P)===9||s.charCodeAt(P)===10||s.charCodeAt(P)===13))P++;if(P<s.length-2&&s.charCodeAt(P)===47&&s.charCodeAt(P+1)===47&&s.charCodeAt(P+2)===47){let Z=Xh(s);if(Z.length>0)for(let q=0;q<Z.length;q++){if(n)n+=`
|
|
201
|
+
`;n+=Z[q]}}}let o=[],a=[],c=[],f=[],u=[],l=[],p=[],h=[],w=[];for(let P of e){let Z=P.kind;switch(Z){case"import":o.push(P);break;case"function":a.push(P);break;case"variable":c.push(P);break;case"interface":f.push(P);break;case"type":u.push(P);break;case"class":l.push(P);break;case"enum":p.push(P);break;case"module":h.push(P);break;case"export":w.push(P);break;case"namespace":h.push(P);break;case"unknown":break;default:ll(Z,`Unhandled declaration kind: ${Z}`)}}let A=new Set,$=[],x=[],S=[],k=new Set;for(let P of w){let Z=pt(P.leadingComments,r);if(P.text.startsWith("export default")){let q=P.text.endsWith(";")?P.text:`${P.text};`;S.push(Z+q)}else{let q=P.text.trim();if(!q.endsWith(";"))q+=";";let ne=q.match(hd);if(ne){let H=ne[1],G=0;for(let Y=0;Y<=H.length;Y++)if(Y===H.length||H.charCodeAt(Y)===44){let Ce=G,Q=Y;while(Ce<Q&&H.charCodeAt(Ce)<=32)Ce++;while(Q>Ce&&H.charCodeAt(Q-1)<=32)Q--;if(Ce<Q)A.add(H.slice(Ce,Q));G=Y+1}}let V=Z+q;if(!k.has(V))if(k.add(V),V.includes("export type"))$.push(V);else x.push(V)}}let R=new Map;if(o.length>0)for(let P of o){let Z=fd(P.text);for(let q of Z)R.set(q,P)}let b=new Set;if(f.length>0){let P=[];for(let Z of a)if(Z.isExported)P.push(Z.text);for(let Z of l)P.push(Z.text);for(let Z of u)P.push(Z.text);if(P.length>0){let Z=cl(P.join(`
|
|
202
|
+
`));for(let q of f)if(Z.has(q.name))b.add(q.name)}}let L=[];if(o.length>0){let P=new Set,Z=[];for(let V of a)if(V.isExported)Z.push(V.text);for(let V of c)if(Z.push(V.text),V.typeAnnotation)Z.push(V.typeAnnotation);for(let V of f)if(V.isExported||b.has(V.name))Z.push(V.text);for(let V of u)Z.push(V.text);for(let V of l)Z.push(V.text);for(let V of p)Z.push(V.text);for(let V of h)Z.push(V.text);for(let V of w)Z.push(V.text);let q=Z.join(`
|
|
203
|
+
`);if(q&&R.size>0){let V=cl(q);for(let H of R.keys())if(V.has(H))P.add(H)}for(let V of A)if(R.has(V))P.add(V);for(let V of o){if(V.isSideEffect){let le=V.text.trim(),st=le.endsWith(";")?le:`${le};`;L.push(st);continue}let H=cd(V.text);if(!H)continue;let{defaultName:G,namedItems:Y,source:Ce,isTypeOnly:Q,isNamespace:ie}=H,sr=G?P.has(G):!1,kt="",rt=0;for(let le=0;le<Y.length;le++){let st=Y[le],yt=st.charCodeAt(0)===116&&st.startsWith("type ")?st.slice(5).trim():st.trim(),or=yt.indexOf(" as ");if(or!==-1)yt=yt.slice(or+4).trim();if(P.has(yt)){if(rt>0)kt+=", ";kt+=st,rt++}}if(sr||rt>0){let le=Q?"import type ":"import ";if(sr&&G)if(ie)le+=`* as ${G}`;else le+=rt>0?`${G}, { ${kt} }`:G;else if(rt>0)le+=`{ ${kt} }`;le+=` from '${Ce}';`,L.push(le)}}let ne=i.length;if(L.length>1){if(fl!==i)fl=i,ul=i.map((Y)=>`from '${Y}`),hl=i.map((Y)=>`from "${Y}`);let V=ul,H=hl,G=new Map;for(let Y of L){let Ce=ne;for(let Q=0;Q<i.length;Q++)if(Y.includes(V[Q])||Y.includes(H[Q])){Ce=Q;break}G.set(Y,Ce)}L.sort((Y,Ce)=>{let Q=G.get(Y),ie=G.get(Ce);return Q!==ie?Q-ie:Y.localeCompare(Ce)})}}for(let P=0;P<L.length;P++){if(n)n+=`
|
|
204
|
+
`;n+=L[P]}for(let P=0;P<$.length;P++){if(n)n+=`
|
|
205
|
+
`;n+=$[P]}let re=[a,c,f,u,l,p,h];for(let P=0;P<re.length;P++){let Z=re[P];for(let q=0;q<Z.length;q++){let ne=Z[q],V="",H=ne.kind;switch(H){case"function":V=td(ne,r);break;case"variable":V=rd(ne,r);break;case"interface":V=id(ne,r);break;case"type":V=nd(ne,r);break;case"class":V=sd(ne,r);break;case"enum":V=od(ne,r);break;case"module":case"namespace":V=ad(ne,r);break;case"import":case"export":case"unknown":break;default:ll(H,`Unhandled declaration kind in processor: ${H}`)}if(V){if(n)n+=`
|
|
206
|
+
`;n+=V}}}for(let P=0;P<x.length;P++){if(n)n+=`
|
|
207
|
+
`;n+=x[P]}for(let P=0;P<S.length;P++){if(n)n+=`
|
|
208
|
+
`;n+=S[P]}if(!n&&(o.length>0||w.length>0))return"export {};";return n}var Hh,qh,zh,Nt,hd,fl=null,ul,hl;var ml=ue(()=>{ol();Xi();Hh=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,qh=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,zh=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;Nt=new Map;hd=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,ul=[],hl=[]});import{mkdir as Hn,readdir as dd,realpath as md,rm as gd}from"fs/promises";import{availableParallelism as pd}from"os";import{basename as $l,dirname as vr,extname as yd,isAbsolute as Xn,parse as $d,relative as Ne,resolve as Xe}from"path";async function gl(e,t,r,i,n){let s=$l(e)||"output.d.ts",o=Ne(vr(e),t),a=`${s}.map`,c=r.lastIndexOf(`
|
|
209
|
+
${Un()}`),f=c===-1?r:r.slice(0,c),u=Ha(f,s,o,i),l=`${e}.map`;return await Cr(l,JSON.stringify(u)),J.debug(` Generated source map: ${Ne(n,l)}`),a}async function Oi(e){let t=Date.now(),r={...La,...e};if(r.logLevel)sn(r.logLevel);else if(r.verbose)sn("debug");let i=new vi;if(r.plugins&&r.plugins.length>0){for(let $ of r.plugins)i.register($),J.debug(`Registered plugin: ${$.name}`);r=await i.runOnStart(r)}if(await Cd(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await Ka(r);let n=r.typeMappings?xi(r.typeMappings):void 0,s=null;if(r.incremental){if(s=new Ji(r),r.clearCache){if(J.debug("Clearing build cache..."),!r.dryRun)s.clear()}else if(s.load()){let $=s.getStats();J.debug(`Loaded build cache with ${$.entries} entries`)}else J.debug("No existing build cache found, starting fresh");if(!r.dryRun)Cs(r.cwd)}let o={generationMode:r.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},a=0;if(J.debug("Starting DTS generation..."),J.debug(`Using ${o.generationMode} declaration generation path`),J.debug("Config:",r),r.clean&&!r.dryRun)await Ad(r);let c=await vd(r),f=c.slice(),u=null;if(r.autoIncludeReExports!==!1&&f.length>0){u=await Li(f,{includeImports:!0});let $=Xe(r.cwd,r.root),x=r.exclude||[],S=[];for(let k of u.reachable){if(f.includes(k))continue;if(!zn(k))continue;if(k.endsWith(".d.ts"))continue;if(k.includes("node_modules"))continue;if(!Ei(k,$)){J.warn(`Skipping auto-included source outside root: ${Ne(r.cwd,k)}`);continue}if(qn(k,x,$))continue;S.push(k)}if(S.length>0)f=[...f,...S],J.debug(`Auto-included ${S.length} file(s) reached via relative re-exports`)}if(xd(f,r),s&&!r.dryRun){let $=s.prune(new Set(f),r.cwd);if($>0)J.debug(`Pruned ${$} deleted files from cache`)}if(J.debug(`Found ${f.length} TypeScript files`),r.progress&&f.length>0){let $=r.parallel?"parallel":"sequential";J.info(`Processing ${f.length} files (${$})...`)}let l=async($,x)=>{let S;try{let k=xr($,r),R=async(H)=>{if(!r.diff)return;try{let G=await ot(k),Y=Ua(G,H,Ne(r.cwd,k));if(Y)J.info(`
|
|
210
|
+
${Y}`);else J.debug(`[no changes] ${k}`)}catch{J.info(`[new file] ${Ne(r.cwd,k)}`)}},b=(H)=>{if(!r.validate)return 0;let G=Ga(H,k);if(G.isValid)return J.debug(`[validation] ${k} - OK`),0;J.warn(`[validation] ${Ne(r.cwd,k)} has ${G.errors.length} error(s):`);for(let Y of G.errors){let Ce=` Line ${Y.line}:${Y.column}`;if(Y.code)Ce+=` [${Y.code}]`;if(Ce+=` - ${Y.message}`,J.warn(Ce),Y.suggestion)J.warn(` Suggestion: ${Y.suggestion}`)}return G.errors.length},L=(H)=>{J.info(`[dry-run] Would generate: ${k}`),J.debug("--- Content preview ---"),J.debug(H.slice(0,500)+(H.length>500?`
|
|
211
|
+
...`:"")),J.debug("--- End preview ---")};if(s){let H=s.getCachedIfValid($,r.cwd);if(H){await R(H);let G=b(H);if(r.dryRun)L(H);else{if(await Hn(vr(k),{recursive:!0}),r.declarationMap)S=x??await ot($),await gl(k,$,H,S,r.cwd);await Cr(k,H,r.lineEnding)}return J.debug(`[cached] ${Ne(r.cwd,k)}`),{success:!0,file:$,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:G}}}S=x??await ot($);let{content:re,declarationCount:P,importCount:Z,exportCount:q}=await kd($,S,r,i,n),ne=re;if(r.prettier||r.indentStyle||r.indentSize){let H=await fo(ne,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},k);ne=H.content;for(let G of H.warnings??[])J.warn(`[format] ${G}`)}if(r.declarationMap){let H=`${$l(k)||"output.d.ts"}.map`;ne=qa(ne,H)}await R(ne);let V=b(ne);if(r.dryRun)L(ne);else{if(await Hn(vr(k),{recursive:!0}),r.declarationMap&&S)await gl(k,$,ne,S,r.cwd);if(await Cr(k,ne,r.lineEnding),s&&S)s.update($,S,ne,r.cwd);J.debug(`Generated: ${k}`)}return{success:!0,file:$,declarationCount:P,importCount:Z,exportCount:q,validationErrorCount:V}}catch(k){let R=Qa(k,$,S);if(r.plugins&&r.plugins.length>0)await i.runOnError(k instanceof Error?k:Error(String(k)),$,S||"");return{success:!1,file:$,declarationCount:0,importCount:0,exportCount:0,dtsError:R,validationErrorCount:0}}},p=r.parallel||r.parallel!==!1&&f.length>=10,h=As(r.concurrency,pd?.()??8),w=new Map;if(p&&f.length>1){let $=f.map(async(x)=>{try{let S=await ot(x);return{file:x,source:S}}catch{return{file:x,source:null}}});for(let x of await Promise.all($))if(x.source!==null)w.set(x.file,x.source)}let A=($)=>{if(o.filesProcessed++,$.success){if($.cached)a++;else o.filesGenerated++,o.declarationsFound+=$.declarationCount,o.importsProcessed+=$.importCount,o.exportsProcessed+=$.exportCount;if(r.validate){if(o.filesValidated++,$.validationErrorCount)o.validationErrors+=$.validationErrorCount}}else if(o.filesFailed++,$.dtsError){o.errors.push($.dtsError);let x=el($.dtsError);if(r.continueOnError)J.warn(x);else throw J.error(x),Error($.dtsError.message)}};if(p)for(let $=0;$<f.length;$+=h){let x=f.slice($,$+h),S=await Promise.all(x.map((k)=>l(k,w.get(k))));for(let k of S)A(k);if(r.progress){let k=Math.round(o.filesProcessed/f.length*100);J.info(`[${o.filesProcessed}/${f.length}] ${k}%`)}}else for(let $ of f){let x=await l($);if(A(x),r.progress){let S=Math.round(o.filesProcessed/f.length*100),k=x.cached?"[cached]":"";J.info(`[${o.filesProcessed}/${f.length}] ${S}% - ${Ne(r.cwd,$)} ${k}`)}}if(s&&!r.dryRun)s.save(),J.debug("Saved build cache");if(!r.bundle){let $=[];if(u)for(let x of u.unresolved)$.push({from:x.from,specifier:x.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&f.length>0){let x=new Set(f);for(let S of f){let k;try{k=await ot(S)}catch{continue}for(let R of Bi(k)){if(!R.specifier.startsWith("."))continue;let b=Sr(R.specifier,S);if(!b.resolved)$.push({from:S,specifier:R.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(b.resolved)&&!x.has(b.resolved))$.push({from:S,specifier:R.specifier,reason:"not-emitted"})}}}if($.length>0){let x=[];x.push(`Found ${$.length} re-export(s) pointing at siblings that won't be in the output:`);for(let k of $){let R=Ne(r.cwd,k.from);if(k.reason==="missing")x.push(` ${R} \u2192 '${k.specifier}' (path not found on disk)`);else x.push(` ${R} \u2192 '${k.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let S=x.join(`
|
|
212
|
+
`);if(r.failOnUnresolvedReExport)throw Error(S);J.warn(S),J.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(r.bundle&&(o.filesGenerated>0||a>0)&&c.length>0)try{J.debug("Bundling declarations...");let $=new Map,x=async(k)=>{let R=$.get(k);if(R!==void 0)return R;return R=await ot(k),$.set(k,R),R};for(let k of f)await x(k);let S=c.length===1&&!!r.bundleOutput;for(let k of c){let R=await Li([k],{includeImports:!0}),b=new Set;for(let q of R.reachable){if(q.endsWith(".d.ts"))continue;if(q.includes("node_modules"))continue;b.add(q)}let L=f.filter((q)=>b.has(q));if(!L.includes(k))L.push(k);let re=new Map;for(let q of L){let ne=$.get(q)??await x(q);re.set(q,ne)}let P=await io(L,re,r),Z=S?Xe(r.cwd,r.outdir,r.bundleOutput):xr(k,r);if(r.dryRun)J.info(`[dry-run] Would bundle ${P.files.length} files to: ${Ne(r.cwd,Z)}`);else await Hn(vr(Z),{recursive:!0}),await Cr(Z,P.content,r.lineEnding),J.info(`Bundled ${P.files.length} files to: ${Ne(r.cwd,Z)}`);if(S)break}}catch($){let x=$ instanceof Error?$.message:String($);J.error(`Bundle failed: ${x}`)}if(o.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(o,null,2));else{if(J.info(`
|
|
213
|
+
--- Generation Statistics ---`),J.info(`Files processed: ${o.filesProcessed}`),J.info(`Files generated: ${o.filesGenerated}`),a>0)J.info(`Files cached: ${a}`);if(o.filesFailed>0)J.info(`Files failed: ${o.filesFailed}`);if(J.info(`Declarations found: ${o.declarationsFound}`),J.info(`Imports processed: ${o.importsProcessed}`),J.info(`Exports processed: ${o.exportsProcessed}`),o.filesValidated>0){if(J.info(`Files validated: ${o.filesValidated}`),o.validationErrors>0)J.info(`Validation errors: ${o.validationErrors}`)}if(J.info(`Duration: ${o.durationMs}ms`),o.errors.length>0){J.info(`
|
|
214
|
+
Errors:`);for(let $ of o.errors){let x=` - ${$.file}`;if($.location)x+=`:${$.location.line}:${$.location.column}`;if($.code)x+=` [${$.code}]`;if(x+=`: ${$.message}`,J.info(x),$.suggestion)J.info(` Suggestion: ${$.suggestion}`)}}J.info(`-----------------------------
|
|
215
|
+
`)}if(r.plugins&&r.plugins.length>0)await i.runOnEnd(o);return J.debug("DTS generation complete!"),o}async function pl(e){try{return await md(e)}catch{return Xe(e)}}async function Cd(e){let t=Xe(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(Xn(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let n=Xe(t,e.bundleOutput);if(!Ei(n,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===$d(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,i]=await Promise.all([pl(t),pl(Xe(e.cwd,e.root))]);if(Ei(i,r))throw Error("Refusing to clean an outdir that contains the source root")}function bd(e){let t=Ar.get(e);if(!t){if(t=new yl(e),Ar.set(e,t),Ar.size>wd){let r=Ar.keys().next().value;if(r!==void 0)Ar.delete(r)}}return t}async function Ad(e){let t=Xe(e.cwd,e.outdir);async function r(i){let n;try{n=await dd(i,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async(s)=>{let o=Xe(i,s.name);if(s.isDirectory()){await r(o);return}if(s.name.endsWith(".d.ts")||s.name.endsWith(".d.mts")||s.name.endsWith(".d.cts")||s.name.endsWith(".d.ts.map")||s.name.endsWith(".d.mts.map")||s.name.endsWith(".d.cts.map"))await gd(o,{force:!0})}))}await r(t)}function qn(e,t,r){if(!t||t.length===0)return!1;let i=Ne(r,e);for(let n of t){let s=bd(n);if(s.match(i)||s.match(e))return!0}return!1}async function vd(e){let t=[],r=Xe(e.cwd,e.root),i=e.exclude||[],n=[...e.entrypoints,...e.include??[]];for(let s of n)if(Xn(s)&&zn(s)){if(!s.includes("node_modules")){if(!Ei(s,r)&&e.outputStructure!=="flat")J.warn(`Skipping entrypoint outside root: ${Ne(e.cwd,s)}`);else if(!qn(s,i,r))t.push(s)}}else{let o=new yl(s);for await(let a of o.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(zn(a)&&!a.includes("node_modules")){if(!qn(a,i,r))t.push(a)}}return[...new Set(t)].sort()}function Ei(e,t){let r=Ne(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Xn(r)}function xd(e,t){let r=new Map;for(let i of e){let n=xr(i,t),s=r.get(n);if(s&&s!==i)throw Error(`Output path collision: ${Ne(t.cwd,s)} and ${Ne(t.cwd,i)} both emit ${Ne(t.cwd,n)}`);r.set(n,i)}}function zn(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function xr(e,t){let r=Xe(t.cwd,t.root),i=Ne(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue)$/,(n)=>{if(n===".mts"||n===".mjs")return".d.mts";if(n===".cts"||n===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return Xe(t.cwd,t.outdir,i);else{let n=i.split("/").pop();return Xe(t.cwd,t.outdir,n)}}function Ed(e,t,r=""){let i=Ne(vr(e),t).replace(/\\/g,"/");if(i=i.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)i+=r;if(!i.startsWith("."))i=`./${i}`;return i}function Od(e,t,r){let i=xr(t,r),n=(s)=>{let o=Sr(s,t);if(!o.isRelative||!o.resolved)return s;if(/\.d\.(?:ts|mts|cts)$/.test(o.resolved))return s;let a=s.match(/[?#].*$/)?.[0]??"",c=a?s.slice(0,-a.length):s,f=yd(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return Ed(i,xr(o.resolved,r),u)+a};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>{return`${o}${a}${n(c)}${a}`}).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>{return`${o}${a}${n(c)}${a}`}).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>{return`${o}${a}${n(c)}${a}`})}async function kd(e,t,r,i,n){let s=t;if(i)s=await i.runOnBeforeFile(e,t);let o=Ir(s,e,r.keepComments,r.isolatedDeclarations??!1);if(i)o=await i.runOnDeclarations(e,s,o);let a=0,c=0;for(let u=0;u<o.length;u++){let l=o[u];if(l.kind==="import")a++;if(l.kind==="export"||l.isExported)c++}let f=dl(o,{filePath:e,sourceCode:s,declarations:o},r.keepComments,r.importOrder);if(f=Od(f,e,r),n)f=nl(f,n,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=lo(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(i)f=await i.runOnAfterFile(e,s,f);return{content:f,declarationCount:o.length,importCount:a,exportCount:c}}var yl,wd=50,Ar;var wl=ue(()=>{gs();bs();so();co();uo();za();Or();ja();Xa();tl();sl();ml();po();nn();vs();({Glob:yl}=globalThis.Bun);Ar=new Map});var Cl=ue(()=>{wl()});var kl={};Zl(kl,{dtsWatch:()=>Bd,dtsCheck:()=>Ld,dts:()=>es,default:()=>_d,clearCache:()=>jd,PluginErrorCodes:()=>Dd,DtsxPluginError:()=>nr});import{createHash as Td}from"crypto";import{existsSync as Rd,readFileSync as Nd,writeFileSync as Wd}from"fs";import{dirname as Fd,join as Pd,relative as bl,resolve as ir,sep as ki}from"path";import vl from"process";class xl{listeners=new Map;on(e,t){let r=this.listeners.get(e)||[];r.push(t),this.listeners.set(e,r)}async emit(e,t){let r={type:e,timestamp:Date.now(),data:t},i=this.listeners.get(e)||[];for(let n of i)await n(r)}}class Qn{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=Pd(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(Rd(this.manifestPath)){let t=JSON.parse(Nd(this.manifestPath,"utf-8"));if(t.configHash===e&&t.version==="1.0")return t}}catch{}return{version:"1.0",configHash:e,entries:{}}}save(){try{let{mkdirSync:e}=Sd("fs");e(this.cacheDir,{recursive:!0}),Wd(this.manifestPath,JSON.stringify(this.manifest,null,2))}catch{}}getEntry(e){return this.manifest.entries[e]}setEntry(e,t){this.manifest.entries[e]=t}isValid(e,t){return this.getEntry(e)?.hash===t}clear(){this.manifest.entries={},this.save()}}function Md(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return Td("md5").update(JSON.stringify(t)).digest("hex")}function es(e={}){let{onSuccess:t,onError:r,failOnError:i=!0,incremental:n=!1,cacheDir:s=".dtsx-cache",on:o,timeout:a=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,l=new xl;if(o){for(let[p,h]of Object.entries(o))if(h)l.on(p,h)}return{name:"bun-plugin-dtsx",async setup(p){let h=Date.now(),w=null,A=0;try{let $=Ol(u,p),x=Md($);if($.clean){let b=ir($.cwd??vl.cwd(),$.outdir??"./dist");if(Al.has(b))$.clean=!1;else Al.add(b)}if(n)w=new Qn(ir(s),x);if(await l.emit("start",{type:"start",files:$.entrypoints||[],config:$}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),n)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let k=await(async()=>{return new Promise((b,L)=>{let re=setTimeout(()=>{L(new nr(`Generation timed out after ${a}ms`,"TIMEOUT_ERROR",{timeout:a}))},a);Oi($).then((P)=>{clearTimeout(re),b(P)}).catch((P)=>{clearTimeout(re),L(P)})})})(),R=Date.now()-h;if(w)w.save();if(await l.emit("complete",{type:"complete",stats:k,duration:R,fromCache:A}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${R}ms`),A>0)console.log(`[bun-plugin-dtsx] ${A} files served from cache`)}if(t)await t(k)}catch($){let x=El($);if(await l.emit("error",{type:"error",error:x}),r)await r(x);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${x.code}`),console.error(` Message: ${x.message}`),x.context)console.error(` Context: ${JSON.stringify(x.context)}`);if(f&&x.stack)console.error(` Stack: ${x.stack}`)}if(i&&!c)throw x}}}}function El(e){if(e instanceof nr)return e;if(e instanceof Error){let t="GENERATION_ERROR";if(e.message.includes("config")||e.message.includes("Config"))t="CONFIG_ERROR";else if(e.message.includes("file")||e.message.includes("File")||e.message.includes("ENOENT"))t="FILE_ERROR";return new nr(e.message,t,{originalError:e.name},e)}return new nr(String(e),"GENERATION_ERROR")}function Id(e){let t=e.map((i)=>Fd(i).split(ki)),r=t[0];for(let i of t.slice(1)){let n=0;while(n<r.length&&n<i.length&&r[n]===i[n])n++;r=r.slice(0,n)}return r.join(ki)||ki}function Ol(e,t){let r=e.cwd||vl.cwd(),i=t?.config?.entrypoints,n=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",s=e.root||e.build?.config.root||t?.config.root;if(!s&&i?.length){let a=Id(i.map((c)=>ir(r,c)));s=bl(r,a)||"."}s=s||"./src";let o=e.entrypoints;if(!o)if(i?.length){let a=ir(r,s),c=[];for(let f of i){let u=ir(r,f);if(u===a||u.startsWith(a+ki))c.push(bl(a,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${s}": ${f}`)}o=c.length?c:["index.ts"]}else o=["index.ts"];return{...e,cwd:r,root:s,entrypoints:o,outdir:n,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}function Bd(e={}){return es({...e,incremental:!0,verbose:e.verbose??!0})}function Ld(e){return{name:"bun-plugin-dtsx-check",async setup(t){let r=Ol({...e,outdir:""},t);try{await Oi({...r,clean:!1})}catch(i){let n=El(i);if(e.onError)await e.onError(n);if(e.failOnError!==!1)throw n}}}}function jd(e=".dtsx-cache"){new Qn(ir(e),"").clear()}var Sd,Dd,nr,Al,_d;var Sl=ue(()=>{Cl();Sd=import.meta.require,Dd={CONFIG_ERROR:"CONFIG_ERROR",GENERATION_ERROR:"GENERATION_ERROR",FILE_ERROR:"FILE_ERROR",CACHE_ERROR:"CACHE_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"};nr=class nr extends Error{code;context;cause;constructor(e,t,r,i){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=r,this.cause=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};Al=new Set;_d=es});import{mkdir as Zd,stat as Jd}from"fs/promises";import{bold as ts,dim as rs,green as Vd,italic as Tl,log as Yd}from"@stacksjs/cli";import{path as tt}from"@stacksjs/path";import{glob as Rl}from"@stacksjs/storage";async function Kd(e){let t=await Rl([tt.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let i of t){let n=await Bun.file(i).text();try{r.transformSync(n)}catch(s){throw Error(`Invalid declaration generated at ${i}: ${s instanceof Error?s.message:String(s)}`)}}}async function Ny(e){let r=Date.now()-e.startTime,i=e.pkgName??`@stacksjs/${tt.basename(e.dir)}`;if(e.result.errors&&e.result.errors.length>0)throw console.error("Build errors:",e.result.errors),Error(`Build failed with errors: ${JSON.stringify(e.result.errors)}`);else if(e.result.success!==void 0&&!e.result.success){let s=e.result.logs?.[0]||"Unknown build error";throw console.log(s),Error(`Build failed: ${s}`)}await Kd(e.dir);let n=await Rl([tt.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of n){let o=await Jd(s),a;if(o.size<1048576)a=`${(o.size/1024).toFixed(2)}kb`;else a=`${(o.size/1024/1024).toFixed(2)}mb`;let c=tt.relative(e.dir,s).replace("dist/","");console.log(`${ts(rs(`[${a}]`))} ${rs("dist/")}${c}`)}console.log(`${ts(rs(`[${r}ms]`))} Built ${Tl(ts(Vd(i)))}`)}async function Wy(e){let t=e.pkgName??`@stacksjs/${tt.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else Yd.info(`Building ${Tl(t)}...`);return{startTime:Date.now()}}async function Fy(e){let{dts:t}=await Promise.resolve().then(() => (Sl(),kl)),r=tt.resolve(e.dir,"src"),i=tt.resolve(e.dir,"dist"),n=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((o)=>!o.endsWith(".d.ts"));await Bun.build({entrypoints:n.map((o)=>tt.resolve(r,o)),outdir:i,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??Gd(),plugins:[t({root:r,outdir:i})]});let s=new Bun.Transpiler({loader:"ts",target:"bun"});for(let o of n){let a=s.transformSync(await Bun.file(tt.resolve(r,o)).text());a=a.replace(/(['"])(\.\.?\/[^'"]+?)\.tsx?\1/g,"$1$2.js$1");let c=tt.resolve(i,o.replace(/\.ts$/,".js"));await Zd(tt.dirname(c),{recursive:!0}),await Bun.write(c,a)}}function Gd(e=[]){let t=[];try{let r=Ye("fs"),i=JSON.parse(r.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(i.dependencies??{}),...Object.keys(i.peerDependencies??{}),...Object.keys(i.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{Kd as validateDeclarations,Fy as transpilePackage,Ny as outro,Wy as intro,Gd as frameworkExternal};
|