@stacksjs/build 0.75.478 → 0.75.482
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 +186 -186
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1,80 +1,55 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var he=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var
|
|
3
|
-
`,r)+1,i=
|
|
4
|
-
`,f+2);f=l===-1?e.length:l+1;continue}if(h===47&&e.charCodeAt(f+1)===42){let l=e.indexOf("*/",f+2);f=l===-1?e.length:l+2;continue}if(h===39||h===34){let l=h;f++;while(f<e.length){let y=e.charCodeAt(f++);if(y===92)f++;else if(y===l)break}u("literal");continue}if(h===96){
|
|
5
|
-
`;r++}r=Math.min(r+2,e.length);continue}if(i===44){let
|
|
6
|
-
`||u==="\r"?u:" ":u;continue}if(c===
|
|
7
|
-
`||e[i]==="\r"?e[i]:" ",i++;if(i<r)n+=" ",i+=2;continue}if(Hr(e,i)){let a=gr(e,i);n+=e.slice(i,a).replace(/[^\r\n]/g," "),i=a;continue}}n+=e[i++]}return n}function
|
|
2
|
+
var he=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var lf=import.meta.require;import{readFile as df,stat as Vp,writeFile as mf}from"fs/promises";async function ds(e,t){if(Vr)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await mf(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function Pt(e){if(Vr)return globalThis.Bun.file(e).text();return df(e,"utf-8")}var Vr,Up;var Ur=he(()=>{Vr=typeof globalThis.Bun<"u",Up=!Vr&&typeof process<"u"&&!!process.versions?.node});function Ht(e){return ms[e]>=ms[Kr]}function yf(){if(!gf)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Cf(e,t){let r=yf();if(e||r)return[`${r}${e}`,...t];return t}function zt(e,t,r){let n=Cf(t,r);if(ps){ps(e,...n);return}switch(e){case"debug":console.debug(...n);break;case"info":console.log(...n);break;case"warn":console.warn(...n);break;case"error":console.error(...n);break}}function gs(e){return{debug:(...t)=>{if(Ht("debug"))zt("debug",e,t)},info:(...t)=>{if(Ht("info"))zt("info",e,t)},warn:(...t)=>{if(Ht("warn"))zt("warn",e,t)},error:(...t)=>{if(Ht("error"))zt("error",e,t)},setLevel:(t)=>{Kr=t},getLevel:()=>Kr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return gs(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(Ht("debug"))zt("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Ht("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else zt("info",e,[t])}}}function fn(e){Kr=e}var ms,Kr="info",pf="[dtsx]",gf=!1,ps=null,Y;var un=he(()=>{ms={debug:0,info:1,warn:2,error:3,silent:4};Y=gs(pf)});function yt(e){return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36||e>127}function Ue(e){return yt(e)||e>=48&&e<=57}function ys(e,t){let r=t;for(;;){while(r>=0&&(e.charCodeAt(r)===32||e.charCodeAt(r)===9||e.charCodeAt(r)===10||e.charCodeAt(r)===13))r--;if(r<0)return-1;if(e.charCodeAt(r)===47&&r>0&&e.charCodeAt(r-1)===42){let o=e.lastIndexOf("/*",r-2);if(o===-1)return-1;r=o-1;continue}let n=e.lastIndexOf(`
|
|
3
|
+
`,r)+1,i=wf(e,n,r);if(i!==-1){r=i-1;continue}return r}}function wf(e,t,r){let n=0;for(let i=t;i<=r;i++){let o=e.charCodeAt(i);if(n){if(o===92){i++;continue}if(o===n)n=0;continue}if(o===39||o===34||o===96){n=o;continue}if(o===47&&i+1<=r&&e.charCodeAt(i+1)===47)return i}return-1}function Cs(e){return e===61||e===40||e===91||e===33||e===38||e===124||e===63||e===58||e===44||e===59||e===123||e===125||e===94||e===126||e===43||e===45||e===42||e===37||e===60||e===62}function ws(e){return e==="return"||e==="typeof"||e==="void"||e==="delete"||e==="throw"||e==="new"||e==="in"||e==="of"||e==="case"||e==="instanceof"||e==="yield"||e==="await"||e==="else"||e==="do"}function vf(e,t){let r=[],n=[],i=0,o=!1,s="",a="",c=!0,f=0,u=(h,l=!1)=>{a=s,s=h,c=l};while(f<=t){let h=e.charCodeAt(f);if(o){if(h===92){f+=2;continue}if(h===96)o=!1,u("literal");else if(h===36&&e.charCodeAt(f+1)===123)n.push(i++),o=!1,u("{",!0),f++;f++;continue}if(h===32||h===9||h===10||h===13){f++;continue}if(h===47&&e.charCodeAt(f+1)===47){let l=e.indexOf(`
|
|
4
|
+
`,f+2);f=l===-1?e.length:l+1;continue}if(h===47&&e.charCodeAt(f+1)===42){let l=e.indexOf("*/",f+2);f=l===-1?e.length:l+2;continue}if(h===39||h===34){let l=h;f++;while(f<e.length){let y=e.charCodeAt(f++);if(y===92)f++;else if(y===l)break}u("literal");continue}if(h===96){o=!0,f++;continue}if(yt(h)||h===35&&yt(e.charCodeAt(f+1))){let l=f++;while(Ue(e.charCodeAt(f)))f++;let y=e.slice(l,f);u(y,s!=="."&&ws(y));continue}if(h===40){let l=a!=="."&&(s==="if"||s==="while"||s==="for"||s==="with"||s==="switch"||s==="catch"||s==="await"&&a==="for");r.push(l),u("(",!0)}else if(h===41){let l=r.pop()??!1;if(f===t)return l;u(")",l)}else if(h===47&&c){f=gr(e,f),u("literal");continue}else{if(h===123)i++;else if(h===125){if(i--,n.at(-1)===i)n.pop(),o=!0}u(e[f],h===47||Cs(h))}f++}return!1}function Hr(e,t){let r=ys(e,t-1);if(r<0)return!0;let n=e.charCodeAt(r);if(n===41)return vf(e,r);if(Cs(n))return!0;if(Ue(n)){let i=r;while(i>=0&&Ue(e.charCodeAt(i)))i--;let o=e.charCodeAt(ys(e,i));if(o===46||o===35)return!1;return ws(e.slice(i+1,r+1))}return!1}function gr(e,t){let r=t,n=e.length;r++;let i=!1;while(r<n){let o=e.charCodeAt(r);if(o===92){r+=2;continue}if(i){if(o===93)i=!1;r++;continue}if(o===91){i=!0,r++;continue}if(o===47){r++;break}if(o===10||o===13)break;r++}while(r<n&&Ue(e.charCodeAt(r)))r++;return r}var hn=()=>{};function vs(e){let t="",r=0,n=0;while(r<e.length){let i=e.charCodeAt(r);if(n){if(t+=e[r],i===92&&r+1<e.length){t+=e[r+1],r+=2;continue}if(i===n)n=0;r++;continue}if(i===34){n=i,t+=e[r++];continue}if(i===47&&e.charCodeAt(r+1)===47){r+=2;while(r<e.length&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13)r++;continue}if(i===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+=`
|
|
5
|
+
`;r++}r=Math.min(r+2,e.length);continue}if(i===44){let o=r+1;while(o<e.length){while(o<e.length&&e.charCodeAt(o)<=32)o++;if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===47){o+=2;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===42){o+=2;while(o+1<e.length&&!(e.charCodeAt(o)===42&&e.charCodeAt(o+1)===47))o++;o=Math.min(o+2,e.length);continue}break}let s=e.charCodeAt(o);if(s===93||s===125){r++;continue}}t+=e[r++]}return t}var bs=()=>{};import{readFileSync as bf,statSync as Ef}from"fs";import{readFile as Sf}from"fs/promises";import{createRequire as $f}from"module";import{dirname as yr,isAbsolute as Af,join as dn,resolve as mn}from"path";function Jt(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(dn(e,"tsconfig.json"));for(let r of t)try{if(Ef(r).isFile())return r}catch{}return null}function xf(e,t){if(Af(e)||e.startsWith("."))return Jt(mn(yr(t),e));let r=$f(t),n=e.startsWith("@")?/^@[^/]+\/[^/]+/.exec(e)?.[0]:e.split("/")[0];if(n)for(let i of r.resolve.paths(n)??[]){let o=Jt(dn(i,n,"package.json"));if(!o)continue;let s=JSON.parse(bf(o,"utf8"));if(e===n){if(s.tsconfig!==void 0){if(typeof s.tsconfig!=="string")throw Error(`Invalid tsconfig field in ${o}`);let c=Jt(mn(yr(o),s.tsconfig));if(!c)throw Error(`Cannot resolve tsconfig ${JSON.stringify(s.tsconfig)} from ${o}`);return c}let a=Jt(dn(yr(o),"tsconfig.json"));if(a)return a}break}for(let i of[`${e}/tsconfig.json`,e])try{let o=r.resolve(i),s=o.endsWith(".json")?Jt(o):null;if(s)return s}catch{}return null}async function Cr(e,t={},r=new Set){let n=Jt(e);if(!n)return;if(r.has(n)){if(t.allowCircular)return;throw Error(`Circular tsconfig extends: ${n}`)}let i=new Set(r).add(n),o=JSON.parse(vs(await Sf(n,"utf8"))),s=typeof o.extends==="string"?[o.extends]:o.extends??[];if(!Array.isArray(s)||s.some((f)=>typeof f!=="string"))throw Error(`Invalid tsconfig extends in ${n}`);let a={};for(let f of s){let u=xf(f,n);if(!u)throw Error(`Cannot resolve tsconfig extends ${JSON.stringify(f)} from ${n}`);a={...a,...await Cr(u,t,i)}}let c=o.compilerOptions??{};if(c.isolatedDeclarations!==void 0)a.isolatedDeclarations=c.isolatedDeclarations;if(c.baseUrl!==void 0){if(typeof c.baseUrl!=="string")throw Error(`Invalid baseUrl in ${n}`);a.baseUrl=mn(yr(n),c.baseUrl)}if(c.paths!==void 0){if(!c.paths||typeof c.paths!=="object"||Array.isArray(c.paths))throw Error(`Invalid paths in ${n}`);for(let[f,u]of Object.entries(c.paths))if(f.split("*").length>2||!Array.isArray(u)||u.length===0||u.some((h)=>typeof h!=="string"||h.split("*").length>2))throw Error(`Invalid path mapping ${JSON.stringify(f)} in ${n}`);a.paths=c.paths,a.pathsBasePath=yr(n)}return a}var pn=he(()=>{bs()});import{existsSync as yn,readFileSync as Es,realpathSync as wr,statSync as Tf}from"fs";import{builtinModules as Of}from"module";import{dirname as Cn,extname as Rf,isAbsolute as wn,join as Os,relative as Rs,resolve as qt}from"path";function zr(e){try{return Tf(e).isFile()}catch{return!1}}function Yt(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!wn(r))return{resolved:null,isRelative:!1};let n=Cn(t),i=qt(n,r);if(zr(i))return{resolved:i,isRelative:!0};let o=Rf(i),s=Pf[o];if(s){let a=i.slice(0,-o.length);for(let c of s){let f=a+c;if(zr(f))return{resolved:f,isRelative:!0}}}for(let a of Ss){let c=i+a;if(zr(c))return{resolved:c,isRelative:!0}}if(yn(i))for(let a of Ss){let c=Os(i,`index${a}`);if(zr(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function Ps(e,t){let r=e.indexOf("*");return r===-1?t===e:t.startsWith(e.slice(0,r))&&t.endsWith(e.slice(r+1))&&t.length>=e.length-1}function ks(e,t){if(Object.hasOwn(e,t))return e[t]!==null;let r=Object.keys(e).filter((n)=>n.includes("*")&&Ps(n,t)).sort((n,i)=>i.indexOf("*")-n.indexOf("*")||i.length-n.length)[0];return r!==void 0&&e[r]!==null}function $s(e,t){if(!e.name||t!==e.name&&!t.startsWith(`${e.name}/`))return!1;if(e.exports===void 0)return!0;let r=t===e.name?".":`.${t.slice(e.name.length)}`;if(typeof e.exports==="string"||Array.isArray(e.exports))return r===".";if(!e.exports||typeof e.exports!=="object")return!1;let n=e.exports;if(!Object.keys(n).some((i)=>i.startsWith(".")))return r===".";return ks(n,r)}function gn(e,t){let r=Rs(e,t);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!wn(r)}async function Ms(e){let t=await Cr(qt(e.cwd,e.tsconfigPath||"tsconfig.json")),r=Object.entries(t?.paths??{});if(r.length===0)return Yt;let n=t?.baseUrl??t?.pathsBasePath??e.cwd,i=qt(e.cwd,e.root),o=new Map,s=new Set([...Of,"bun"]),a=(f)=>{let u=Cn(f),h=[];while(!0){if(o.has(u)){let C=o.get(u);for(let S of h)o.set(S,C);return C}h.push(u);let l=Os(u,"package.json");if(yn(l)){let C={...JSON.parse(Es(l,"utf8")),directory:wr(u)};for(let S of h)o.set(S,C);return C}let y=Cn(u);if(y===u)return;u=y}},c=(f,u)=>{if(f.startsWith(".")||wn(f))return Yt(f,u);if(f.startsWith("node:")||f.startsWith("bun:")||s.has(f))return{resolved:null,isRelative:!1};let h=a(u),l=f.startsWith("@")?/^@[^/]+\/[^/]+/.exec(f)?.[0]:f.split("/")[0];if(h&&($s(h,f)||ks(h.imports??{},f)||l&&[h.dependencies,h.devDependencies,h.peerDependencies,h.optionalDependencies].some((G)=>Object.hasOwn(G??{},l))))return{resolved:null,isRelative:!1};let y=r.filter(([G])=>Ps(G,f)).sort(([G],[L])=>{if(!G.includes("*"))return-1;if(!L.includes("*"))return 1;return L.indexOf("*")-G.indexOf("*")})[0];if(!y)return{resolved:null,isRelative:!1};let[C,S]=y,x=C.indexOf("*"),v=x===-1?"":f.slice(x,f.length-(C.length-x-1));for(let G of S){let L=qt(n,G.replace("*",v)),P=a(L);if(P&&$s(P,f)&&!P.private&&P.directory!==h?.directory)return{resolved:null,isRelative:!1};let F=Yt(L,u);if(!F.resolved)continue;let I=wr(F.resolved),k=e.outputStructure==="flat"||yn(i)&&gn(wr(i),I);if(!h||!gn(h.directory,I)||!k||a(I)?.directory!==h.directory||/\.d\.(?:ts|mts|cts)$/.test(I))throw Error(`Local alias ${JSON.stringify(f)} from ${u} resolves outside its emitted package source: ${I}`);return Y.debug(`Resolved local declaration alias ${f} from ${u} to ${I}`),{resolved:e.outputStructure==="flat"?F.resolved:qt(i,Rs(wr(i),I)),isRelative:!0,isAlias:!0,suffix:L.match(/[?#].*$/)?.[0]??""}}throw Error(`Cannot resolve local alias ${JSON.stringify(f)} from ${u} using ${e.tsconfigPath||"tsconfig.json"} (${JSON.stringify(C)})`)};return c.isPackageLocal=(f,u)=>{let h=a(f);return!!h&&a(u)?.directory===h.directory&&gn(h.directory,wr(u))},c.cacheKey=(f)=>{let u=f.map((l)=>({file:l,references:Jr(Es(l,"utf8"),{includeImports:!0}).map((y)=>({specifier:y.specifier,resolution:c(y.specifier,l)}))})),h=[...new Set(o.values())].filter((l)=>l!==void 0).sort((l,y)=>l.directory.localeCompare(y.directory));return JSON.stringify({root:i,compilerOptions:t,packages:h,edges:u})},c}function Ds(e,t=[]){let r=e.length,n="",i=0;while(i<r){let o=e.charCodeAt(i);if(o===34||o===39||o===96){let s=o,a=i;n+=e[i++];while(i<r){let c=e.charCodeAt(i),f=e[i++];if(n+=s===96&&c!==s?c===10||c===13?f:" ":f,c===92&&i<r){let u=e[i++];n+=s===96?u===`
|
|
6
|
+
`||u==="\r"?u:" ":u;continue}if(c===s)break}t.push({start:a,end:i});continue}if(o===47&&i+1<r){let s=e.charCodeAt(i+1);if(s===47){n+=" ",i+=2;while(i<r&&e.charCodeAt(i)!==10)n+=" ",i++;continue}if(s===42){n+=" ",i+=2;while(i<r&&!(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47))n+=e[i]===`
|
|
7
|
+
`||e[i]==="\r"?e[i]:" ",i++;if(i<r)n+=" ",i+=2;continue}if(Hr(e,i)){let a=gr(e,i);n+=e.slice(i,a).replace(/[^\r\n]/g," "),i=a;continue}}n+=e[i++]}return n}function Jr(e,t={}){let r=[],n=[],i=Ds(e,n),o=(a)=>n.some((c)=>a>c.start&&a<c.end);As.lastIndex=0;let s;while((s=As.exec(i))!==null){if(o(s.index))continue;let a=!!s[1],c=s[3],f=s[0],u;if(f.includes("* as "))u="export-star-as";else if(f.includes("*"))u="export-star";else u="export-named";r.push({specifier:c,kind:u,isTypeOnly:a})}if(t.includeImports){Ts.lastIndex=0;while((s=Ts.exec(i))!==null){if(o(s.index))continue;r.push({specifier:s[3],kind:"import",isTypeOnly:!!s[1]})}}if(t.includeImports){xs.lastIndex=0;while((s=xs.exec(i))!==null)if(!o(s.index))r.push({specifier:s[2],kind:"import",isTypeOnly:!1})}return r}function Is(e,t){let r=[],n=Ds(e,r),i=/\b(?:from\s*|import\s*(?:\(\s*)?)(['"])([^'"]+)\1/g,o=[],s;while((s=i.exec(n))!==null){if(r.some((u)=>s.index>u.start&&s.index<u.end))continue;let c=s.index+s[0].lastIndexOf(`${s[1]}${s[2]}${s[1]}`)+1,f=t(s[2]);if(f!==s[2])o.push({start:c,end:c+s[2].length,value:f})}let a=e;for(let c of o.reverse())a=a.slice(0,c.start)+c.value+a.slice(c.end);return a}async function vn(e,t={}){let r=new Set,n=new Map,i=[],o=[];for(let s of e){let a=qt(s);if(!r.has(a))r.add(a),o.push(a)}while(o.length>0){let s=o.shift(),a;try{a=await Pt(s)}catch{continue}let c=Jr(a,t);n.set(s,c);for(let f of c){let u=(t.resolveSpecifier??Yt)(f.specifier,s);if(!u.isRelative)continue;if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),o.push(u.resolved)}else i.push({from:s,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:r,reExports:n,unresolved:i}}var Ss,Pf,As,xs,Ts;var bn=he(()=>{Ur();un();hn();pn();Ss=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],Pf={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};As=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,xs=/\bimport\s*\(\s*(['"])([^'"]+)\1/g,Ts=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";]+?\s+from\s+)?(['"])([^'"]+)\2/g});import{relative as Wt}from"path";function kf(e){let t=[],r=[],n=0,i=0,o=[],s=!1,a=0,c=e.length,f=(u)=>{let h=e.slice(n,u).trim();if(n=u,!h)return;if(Mf(h)){r.push(h);return}t.push({text:h,comments:r}),r=[]};while(a<c){let u=e[a];if(s){if(u==="\\"){a+=2;continue}if(u==="`"){s=!1,a++;continue}if(u==="$"&&e[a+1]==="{"){o.push(i),i++,s=!1,a+=2;continue}a++;continue}if(u==="/"&&e[a+1]==="*"){let h=e.indexOf("*/",a+2);a=h===-1?c:h+2;continue}if(u==="/"&&e[a+1]==="/"){let h=e.indexOf(`
|
|
8
8
|
`,a);a=h===-1?c:h;continue}if(u==="'"||u==='"'){a++;while(a<c&&e[a]!==u&&e[a]!==`
|
|
9
|
-
`){if(e[a]==="\\")a++;a++}a++;continue}if(u==="`"){
|
|
10
|
-
`){let h=e[a+1];if(h!==void 0&&/[\w$@/]/.test(h))f(a+1);a++;continue}a++}return f(c),t}function
|
|
11
|
-
`,t);t=r===-1?e.length:r;continue}if(e.startsWith("/*",t)){let r=e.indexOf("*/",t+2);if(r===-1)return!0;t=r+2;continue}return!1}return!0}function
|
|
12
|
-
`).map((f)=>f.trim()).filter((f)=>f.startsWith("///"))),!1;return!0});let
|
|
13
|
-
`;while(n<i){let
|
|
14
|
-
`,n),c=a===-1?i:a;r+=e.slice(n,c),n=c;continue}if(
|
|
15
|
-
`){if(e[a]==="\\")a++;a++}r+=e.slice(n,a+1),n=a+1,s
|
|
16
|
-
`||!/\s/.test(
|
|
9
|
+
`){if(e[a]==="\\")a++;a++}a++;continue}if(u==="`"){s=!0,a++;continue}if(u==="("||u==="["||u==="{"){i++,a++;continue}if(u===")"||u==="]"||u==="}"){if(i--,o.length>0&&u==="}"&&i===o[o.length-1])o.pop(),s=!0;a++;continue}if(i===0&&u===";"){f(a+1),a++;continue}if(i===0&&u===`
|
|
10
|
+
`){let h=e[a+1];if(h!==void 0&&/[\w$@/]/.test(h))f(a+1);a++;continue}a++}return f(c),t}function Mf(e){let t=0;while(t<e.length){while(t<e.length&&/\s/.test(e[t]))t++;if(t>=e.length)return!0;if(e.startsWith("//",t)){let r=e.indexOf(`
|
|
11
|
+
`,t);t=r===-1?e.length:r;continue}if(e.startsWith("/*",t)){let r=e.indexOf("*/",t+2);if(r===-1)return!0;t=r+2;continue}return!1}return!0}function En(e){let t=[];for(let r of e.split(",")){let n=r.replace(/\/\*[\s\S]*?\*\//g,"").trim().replace(/^type\s+/,"");if(!n)continue;let i=n.match(/^([\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!i)continue;t.push({local:i[1],exported:i[2]??i[1]})}return t}function Df(e){let t={named:[]},r=e.trim().replace(/^type\s+/,""),n=r.match(/\{([\s\S]*)\}/);if(n){for(let s of En(n[1]))t.named.push({imported:s.local,local:s.exported});r=r.replace(n[0],"")}let i=r.match(/\*\s*as\s+([\w$]+)/);if(i)t.namespaceName=i[1],r=r.replace(i[0],"");let o=r.replace(/,/g,"").trim();if(o&&Ns.test(o))t.defaultName=o;return t}function Ff(e,t){let r=e.replace(/^export\s+/,""),n=/^default\s+/.test(r);if(r=r.replace(/^default\s+/,""),n)r=r.replace(/^((?:declare\s+)?(?:abstract\s+)?(?:class|function\s*\*?|async\s+function\s*\*?))\s*(?=[(<{])/,(i,o)=>`${o.trimEnd()} ${t}`);if(/^(?:interface|type)\b/.test(r)||/^declare\b/.test(r))return r;return`declare ${r}`}function Nf(e,t){let r={file:e,declarations:[],declared:new Set,imports:new Map,localExports:new Map,namedReExports:[],starReExports:[],namespaceReExports:[],verbatim:[],directives:[]},n=kf(t);for(let i of n){i.comments=i.comments.filter((c)=>{if(/^\/\/\/\s*</.test(c))return r.directives.push(...c.split(`
|
|
12
|
+
`).map((f)=>f.trim()).filter((f)=>f.startsWith("///"))),!1;return!0});let o=i.text.replace(/;\s*$/,"").trim(),s=o.match(/^import\s+(type\s+)?([\s\S]+?)\s+from\s+(['"])([^'"]+)\3/);if(s){let c=Df(s[2]),f=s[4];if(c.defaultName)r.imports.set(c.defaultName,{specifier:f,imported:"default"});if(c.namespaceName)r.imports.set(c.namespaceName,{specifier:f,imported:"*"});for(let u of c.named)r.imports.set(u.local,{specifier:f,imported:u.imported});continue}if(/^import\s+['"]/.test(o)){r.verbatim.push(i);continue}if(s=o.match(/^export\s+(?:type\s+)?\*\s+as\s+([\w$]+)\s+from\s+(['"])([^'"]+)\2/),s){r.namespaceReExports.push({specifier:s[3],exported:s[1]});continue}if(s=o.match(/^export\s+(?:type\s+)?\*\s+from\s+(['"])([^'"]+)\1/),s){r.starReExports.push(s[2]);continue}if(s=o.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}\s+from\s+(['"])([^'"]+)\2/),s){for(let c of En(s[1]))r.namedReExports.push({specifier:s[3],imported:c.local,exported:c.exported});continue}if(s=o.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}$/),s){for(let c of En(s[1]))r.localExports.set(c.exported,c.local);continue}if(s=o.match(/^export\s+default\s+([\w$]+)$/),s&&Ns.test(s[1])){r.localExports.set("default",s[1]);continue}if(/^export\s+as\s+namespace\b/.test(o)||/^(?:export\s+)?declare\s+(?:global\b|module\s+['"])/.test(o)){r.verbatim.push(i);continue}let a=o.match(If);if(a){let c=!!a[1],f=a[4]??(c?"_default":null);if(f){if(r.declared.add(f),/^export\s/.test(o))r.localExports.set(c?"default":f,f);r.declarations.push({statement:i,name:f,emit:Ff(i.text,f)});continue}}r.declarations.push({statement:i,name:null,emit:i.text})}return r}function Fs(e,t){if(t.size===0)return e;let r="",n=0,i=e.length,o=`
|
|
13
|
+
`;while(n<i){let s=e[n];if(s==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2),c=a===-1?i:a+2;r+=e.slice(n,c),n=c;continue}if(s==="/"&&e[n+1]==="/"){let a=e.indexOf(`
|
|
14
|
+
`,n),c=a===-1?i:a;r+=e.slice(n,c),n=c;continue}if(s==="'"||s==='"'){let a=n+1;while(a<i&&e[a]!==s&&e[a]!==`
|
|
15
|
+
`){if(e[a]==="\\")a++;a++}r+=e.slice(n,a+1),n=a+1,o=s;continue}if(/[A-Z_$]/i.test(s)){let a=n+1;while(a<i&&/[\w$]/.test(e[a]))a++;let c=e.slice(n,a),f=t.get(c);if(f!==void 0&&o!=="."){let u=a;while(u<i&&(e[u]===" "||e[u]==="\t"))u++;let h=(e[u]===":"||e[u]==="?"&&e[u+1]===":")&&/[{;,(\n]/.test(o);r+=h?c:f}else r+=c;o="a",n=a;continue}if(r+=s,s===`
|
|
16
|
+
`||!/\s/.test(s))o=s;n++}return r}function Ls(e,t,r,n){let i=[],o=new Map,s=[e,...t.filter((W)=>W!==e)];for(let W of s){let K=r.get(W);if(K===void 0){i.push(`No declarations were generated for ${Wt(n.cwd,W)}; it is left out of the bundle`);continue}o.set(W,Nf(W,K))}let a=(W,K)=>{if(!W.startsWith(".")&&!W.startsWith("/"))return null;let q=Yt(W,K).resolved;return q&&o.has(q)?q:null},c=(W)=>W.startsWith(".")||W.startsWith("/"),f=new Set,u=(W)=>{let K=W;for(let q=1;f.has(K);q++)K=`${W}_${q}`;return f.add(K),K},h=new Map;for(let[W,K]of o){let q=new Map;for(let Z of K.declared)q.set(Z,u(Z));h.set(W,q)}let l=new Map,y=(W,K,q)=>{let Z=`${W}\x00${K}`,te=l.get(Z);if(!te)te=u(q),l.set(Z,te);return te},C=new Map,S=new Map,x=new Set,v=(W,K,q)=>{let Z=a(K,W.file);if(Z){if(q==="*")return{kind:"namespace",file:Z};let te=L(Z).get(q);if(!te)i.push(`${Wt(n.cwd,W.file)}: '${q}' is not exported by '${K}'`);return te??null}if(c(K))return i.push(`${Wt(n.cwd,W.file)}: '${K}' is not part of the bundle`),null;return q==="*"?{kind:"external-namespace",source:K}:{kind:"external",source:K,imported:q}},G=(W,K)=>{if(W.declared.has(K))return{kind:"local",name:h.get(W.file).get(K)};let q=W.imports.get(K);if(q)return v(W,q.specifier,q.imported);return i.push(`${Wt(n.cwd,W.file)}: cannot resolve exported name '${K}'`),null};function L(W){let K=C.get(W);if(K)return K;let q=new Map,Z=o.get(W);if(!Z||x.has(W))return q;x.add(W);let te=new Set;for(let[X,oe]of Z.localExports){let Ge=G(Z,oe);if(Ge)q.set(X,Ge)}for(let X of Z.namedReExports){let oe=v(Z,X.specifier,X.imported);if(oe)q.set(X.exported,oe)}for(let X of Z.namespaceReExports){let oe=v(Z,X.specifier,"*");if(oe)q.set(X.exported,oe)}for(let X of Z.starReExports){let oe=a(X,W);if(oe){for(let[Ge,Ve]of L(oe))if(Ge!=="default"&&!q.has(Ge))q.set(Ge,Ve);for(let Ge of S.get(oe)??[])te.add(Ge)}else if(c(X))i.push(`${Wt(n.cwd,W)}: '${X}' is not part of the bundle`);else te.add(X)}return x.delete(W),C.set(W,q),S.set(W,te),q}let P=new Map,F=[],I=(W,K)=>{switch(W.kind){case"local":return W.name;case"external":return y(W.source,W.imported,W.imported==="default"?K:W.imported);case"external-namespace":return y(W.source,"*",K);case"namespace":return k(W.file,K)}};function k(W,K){let q=P.get(W);if(q)return q;let Z=u(K);P.set(W,Z);let te=[];for(let[X,oe]of L(W)){if(X==="default")continue;let Ge=I(oe,X);te.push(Ge===X?X:`${Ge} as ${X}`)}if(S.get(W)?.size)i.push(`${Wt(n.cwd,W)}: 'export * from' an external module cannot be expressed inside namespace '${Z}'`);return F.push(`declare namespace ${Z} {
|
|
17
17
|
export { ${te.join(", ")} };
|
|
18
|
-
}`),
|
|
19
|
-
${
|
|
20
|
-
`)}`)}let
|
|
18
|
+
}`),Z}let U=[],H=[],O=new Set;for(let[W,K]of o){for(let te of K.directives)O.add(te);let q=new Map;for(let[te,X]of h.get(W))if(te!==X)q.set(te,X);for(let[te,X]of K.imports){if(K.declared.has(te))continue;let oe=v(K,X.specifier,X.imported);if(!oe)continue;let Ge=I(oe,te);if(Ge!==te)q.set(te,Ge)}let Z=[];for(let te of K.declarations){if(n.keepComments)Z.push(...te.statement.comments);let X=Fs(te.emit,q);if(!/[;}]$/.test(X))X+=";";Z.push(X)}for(let te of K.verbatim){if(n.keepComments)H.push(...te.comments);H.push(Fs(te.text,q))}if(Z.length>0)U.push(`// From: ${Wt(n.cwd,W)}
|
|
19
|
+
${Z.join(`
|
|
20
|
+
`)}`)}let z=L(e),pe=[],Oe=[];for(let[W,K]of z){if(K.kind==="external"){Oe.push(`export { ${K.imported===W?W:`${K.imported} as ${W}`} } from '${K.source}';`);continue}if(K.kind==="external-namespace"){Oe.push(`export * as ${W} from '${K.source}';`);continue}let q=I(K,W==="default"?"_default":W);pe.push(q===W?W:`${q} as ${W}`)}for(let W of S.get(e)??[])Oe.push(`export * from '${W}';`);let ie=new Map;for(let[W,K]of l){let[q,Z]=W.split("\x00"),te=ie.get(q)??{named:[],defaults:[],namespaces:[]};if(ie.set(q,te),Z==="*")te.namespaces.push(K);else if(Z==="default")te.defaults.push(K);else te.named.push(Z===K?K:`${Z} as ${K}`)}let ne=[];for(let[W,K]of[...ie].sort(([q],[Z])=>q.localeCompare(Z))){for(let q of K.defaults)ne.push(`import ${q} from '${W}';`);for(let q of K.namespaces)ne.push(`import * as ${q} from '${W}';`);if(K.named.length>0)ne.push(`import { ${K.named.join(", ")} } from '${W}';`)}let ue=[];if(O.size>0)ue.push([...O].join(`
|
|
21
21
|
`));if(ue.push(`/**
|
|
22
22
|
* Bundled TypeScript declarations
|
|
23
|
-
* Generated from ${
|
|
23
|
+
* Generated from ${o.size} source files
|
|
24
24
|
*/`),ne.length>0)ue.push(ne.join(`
|
|
25
|
-
`));if(ue.push(...
|
|
26
|
-
`));if(
|
|
27
|
-
`));let
|
|
25
|
+
`));if(ue.push(...U),F.length>0)ue.push(F.join(`
|
|
26
|
+
`));if(H.length>0)ue.push(H.join(`
|
|
27
|
+
`));let se=[];if(pe.length>0)se.push(`export { ${pe.join(", ")} };`);if(se.push(...Oe),se.length===0)se.push("export {};");return ue.push(se.join(`
|
|
28
28
|
`)),{content:`${ue.join(`
|
|
29
29
|
|
|
30
30
|
`)}
|
|
31
|
-
`,files:[...
|
|
32
|
-
`)!==-1)r=r.replace(/\r\n/g,`
|
|
33
|
-
`);if(r.indexOf("\r")!==-1)r=r.replace(/\r/g,`
|
|
34
|
-
`)}if(t==="crlf")r=r.replace(/\n/g,`\r
|
|
35
|
-
`);return r}function Gf(e){return e.split(`
|
|
36
|
-
`).map((t)=>t.replace(/[\t ]+$/,"")).join(`
|
|
37
|
-
`)}function Bf(e,t){let r=new RegExp(`\\n{${t+2},}`,"g");return e.replace(r,`
|
|
38
|
-
`.repeat(t+1))}function _f(e){return`${e.replace(/\s+$/,"")}
|
|
39
|
-
`}function Uf(e,t){let{style:r="spaces",size:n=2}=t,i=r==="tabs"?"\t":" ".repeat(n),s=e.split(`
|
|
40
|
-
`),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 h=f.replace(/\t/g," "),l=Math.floor(h.length/2);o.push(i.repeat(l)+u)}return o.join(`
|
|
41
|
-
`)}function Vf(e,t){let{groups:r=Wf,separateGroups:n=!0,alphabetize:i=!0}=t,s=e.split(`
|
|
42
|
-
`),o=[],a=[],c=-1;for(let C=0;C<s.length;C++){let S=s[C],x=Wo(S);if(x)o.push({line:S,source:x.source,group:x.group,isType:x.isType}),c=C;else if(o.length>0&&S.trim()==="")continue;else if(o.length>0||S.trim()!==""){if(o.length===0||C>c+1)a.push(S)}}if(o.length===0)return e;let f=new Map;for(let C of r)f.set(C,[]);for(let C of o)(f.get(C.group)||f.get("external")||[]).push(C);if(i)for(let[,C]of f)C.sort((S,x)=>{if(S.isType!==x.isType)return S.isType?1:-1;return S.source.localeCompare(x.source)});let u=[],h=null;for(let C of r){let S=f.get(C)||[];if(S.length===0)continue;if(n&&h!==null)u.push("");for(let x of S)u.push(x.line);h=C}let l=s.slice(0,s.findIndex((C)=>Wo(C)!==null)),y=a;while(y.length>0&&y[0].trim()==="")y.shift();return[...l,...u,"",...y].join(`
|
|
43
|
-
`)}function Wo(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:Lo(s[1]),isType:!1};return null}let n=!!r[1],i=r[2];return{source:i,group:n?"type":Lo(i),isType:n}}function Lo(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 Hf(e,t){let{kinds:r=Nf,alphabetize:n=!1,groupExports:i=!0}=t,s=e.split(`
|
|
44
|
-
`),o=[],a=[],c=[],f=null,u=0,h=!0,l=!1,y=[];for(let x=0;x<s.length;x++){let v=s[x],B=v.trim(),W=u,P=B.startsWith("///"),F=W===0&&!P&&(B.startsWith("//")||B.startsWith("/*"));if(l||F){if(y.push(v),!l&&B.startsWith("/*")&&!B.includes("*/"))l=!0;else if(l&&B.includes("*/"))l=!1;continue}if(W===0&&y.length>0&&B===""){y.push(v);continue}u+=(v.match(/\{/g)||[]).length,u-=(v.match(/\}/g)||[]).length;let I=Kf(B);if(h&&I&&I.kind!=="import"&&!B.startsWith("//")&&!B.startsWith("/*"))h=!1;if(h){if(y.length>0){if(I?.kind==="import"||!I)a.push(...y),y.length=0}a.push(v);continue}if(I&&u<=1){if(f)o.push(f);f={lines:y.length>0?[...y,v]:[v],kind:I.kind,name:I.name,isExport:I.isExport},y.length=0}else if(f)f.lines.push(v);else{if(B==="")continue;c.push(v)}}if(f)o.push(f);if(y.length>0)c.push(...y);o.sort((x,v)=>{if(i&&x.isExport!==v.isExport)return x.isExport?-1:1;let B=r.indexOf(x.kind),W=r.indexOf(v.kind),P=B>=0?B:r.length,F=W>=0?W:r.length;if(P!==F)return P-F;if(n)return x.name.localeCompare(v.name);return 0});let C=[...a],S=null;for(let x of o){if(S!==null&&x.kind!==S)C.push("");C.push(...x.lines),S=x.kind}if(c.length>0)C.push(""),C.push(...c);return C.join(`
|
|
45
|
-
`)}function Kf(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 Nf,Wf;var Bo=he(()=>{Nf=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],Wf=["builtin","external","scoped","internal","parent","sibling","index","type"]});async function jf(){if(Zr!==null)return Zr;try{return Mt=await import("prettier"),Zr=!0,!0}catch{return Zr=!1,!1}}async function Zf(e,t){if(!Mt)return null;try{if(t&&Mt.resolveConfig){let r=await Mt.resolveConfig(t);if(r)return r}if(e&&Mt.resolveConfig){let r=await Mt.resolveConfig(e);if(r)return r}return null}catch{return null}}async function Yf(e,t){if(!Mt)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return Mt.format(e,r)}function Jf(e,t={}){let{indentSize:r=2,useTabs:n=!1,maxLineWidth:i=100,trailingNewline:s=!0,normalizeWhitespace:o=!0,sortImports:a=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(r);if(f.indexOf(`\r
|
|
46
|
-
`)!==-1)f=f.replace(/\r\n/g,`
|
|
47
|
-
`);if(o){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
|
|
48
|
-
|
|
31
|
+
`,files:[...o.keys()],exportCount:z.size,warnings:i}}var Ns,If;var Ws=he(()=>{bn();Ns=/^[A-Z_$][\w$]*$/i;If=/^(?:export\s+)?(default\s+)?(?:declare\s+)?(abstract\s+)?(class|interface|type|function\s*\*?|enum|const\s+enum|namespace|module|const|let|var|async\s+function)\b\s*([\w$]+)?/});function vr(e){if(Lf)return Bun.hash(e);let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);t=(t<<5)-t+n,t=t&t}return t}var Lf;var Sn=he(()=>{Lf=typeof globalThis.Bun?.hash==="function"});import{existsSync as br,mkdirSync as Wf,readFileSync as An,renameSync as Bf,rmSync as Bs,statSync as Gs,writeFileSync as js}from"fs";import{join as _s,relative as qr,resolve as Gf}from"path";class xn{cacheDir;manifestPath;manifest=null;configHash;constructor(e,t){this.cacheDir=Gf(e.cwd,Yr),this.manifestPath=_s(this.cacheDir,jf),this.configHash=this.hashConfig(e,t)}hashConfig(e,t){let r={resolutionContext: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((n)=>({pattern:typeof n.pattern==="string"?{kind:"string",value:n.pattern}:{kind:"regex",source:n.pattern.source,flags:n.pattern.flags},replacement:n.replacement,global:n.global,priority:n.priority,hasCondition:Boolean(n.condition)}))}:void 0,lineEnding:e.lineEnding,normalizeOutput:e.normalizeOutput,declarationOrder:e.declarationOrder,plugins:e.plugins?.map((n)=>({name:n.name,version:n.version,cacheKey:n.cacheKey}))};return String(vr(JSON.stringify(r)))}hashString(e){return String(vr(e))}load(){try{if(!br(this.manifestPath))return!1;let e=An(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==$n)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:$n,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!br(this.cacheDir))Wf(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{js(e,JSON.stringify(this.manifest,null,2)),Bf(e,this.manifestPath)}finally{if(br(e))Bs(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=qr(t,e),n=this.manifest.entries[r];if(!n)return null;if(typeof n.dtsContent!=="string"||typeof n.dtsHash!=="string"||n.configHash!==this.configHash||this.hashString(n.dtsContent)!==n.dtsHash)return null;try{let i=Gs(e),{mtimeMs:o,ctimeMs:s}=i;if(i.size!==n.sourceSize)return null;if(o!==n.sourceMtime||s!==n.sourceCtime){let a=An(e,"utf-8");if(this.hashString(a)!==n.sourceHash)return null;n.sourceMtime=o,n.sourceCtime=s}return n.dtsContent}catch{return null}}update(e,t,r,n){if(!this.manifest)this.manifest={version:$n,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=qr(n,e),o,s,a;try{let c=Gs(e);o=c.mtimeMs,s=c.ctimeMs,a=c.size}catch{o=Date.now(),s=o,a=Buffer.byteLength(t)}this.manifest.entries[i]={sourcePath:i,sourceHash:this.hashString(t),sourceMtime:o,sourceCtime:s,sourceSize:a,dtsContent:r,dtsHash:this.hashString(r),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let r=qr(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(br(this.manifestPath))Bs(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,n=new Set(Array.from(e).map((i)=>qr(t,i)));for(let i of Object.keys(this.manifest.entries))if(!n.has(i))delete this.manifest.entries[i],r++;return r}}function Vs(e){let t=_s(e,".gitignore");try{let r="";if(br(t))r=An(t,"utf-8");if(!r.split(/\r?\n/).some((n)=>n.trim()===Yr||n.trim()===`${Yr}/`)){let n=r.trimEnd(),i=`${n}${n?`
|
|
49
32
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
`);f=qf(f,u)}if(a||c)f=zf(f,{sort:a,group:c});if(i>0)f=Qf(f,i,u);if(s&&!f.endsWith(`
|
|
53
|
-
`))
|
|
54
|
-
`;return f}function qf(e,t){let r=e.split(`
|
|
55
|
-
`),n=[];for(let i of r){let s=i.match(/^(\s*)(.*)$/);if(!s){n.push(i);continue}let[,o,a]=s;if(!a){n.push("");continue}let c=o.replace(/\t/g," ").length,f=Math.floor(c/2);n.push(t.repeat(f)+a)}return n.join(`
|
|
56
|
-
`)}function zf(e,t){let r=e.split(`
|
|
57
|
-
`),n=[],i=[],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 h=u[1];n.push({line:f,source:u[2],isType:h.startsWith("import type ")||h.startsWith("import type\t")})}else if(s&&f.trim()==="")continue;else{if(s)s=!1;i.push(f)}}if(n.length===0)return e;if(t.sort)n.sort((c,f)=>{if(c.isType!==f.isType)return c.isType?1:-1;return Xf(c.source,f.source)});let a;if(t.group){let c=[],f=[],u=[],h=[],l=[];for(let y=0;y<n.length;y++){let C=n[y],S=C.source;if(S.charCodeAt(0)===46)l.push(C);else if(S.startsWith("node:"))c.push(C);else if(S.charCodeAt(0)===64)h.push(C);else if(S.includes("/"))u.push(C);else f.push(C)}a=[...c.map((y)=>y.line),...c.length>0&&f.length>0?[""]:[],...f.map((y)=>y.line),...(c.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((y)=>y.line),...h.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...h.map((y)=>y.line),...l.length>0?[""]:[],...l.map((y)=>y.line)]}else a=n.map((c)=>c.line);return[...a,"",...i].join(`
|
|
58
|
-
`)}function Xf(e,t){let r=e.startsWith("node:"),n=t.startsWith("node:");if(r!==n)return r?-1:1;let i=e.startsWith("."),s=t.startsWith(".");if(i!==s)return i?1:-1;return e.localeCompare(t)}function Qf(e,t,r){let n=e.split(`
|
|
59
|
-
`),i=[];for(let s of n){if(s.length<=t){i.push(s);continue}if(s.trimStart().startsWith("import ")){i.push(s);continue}let o=s.match(/^(\s*)/)?.[1]||"",a=o+r,c=tu(s,o,a);if(c){i.push(...c);continue}if(s.includes("{")&&s.includes("}")){let f=ru(s,t,o,a);i.push(...f);continue}if(s.includes(" | ")){let f=iu(s,t,o,a);i.push(...f);continue}i.push(s)}return i.join(`
|
|
60
|
-
`)}function tu(e,t,r){let n=e.match(eu);if(!n)return null;let[,i,s,o,a]=n,c=o.split(",").map((h)=>h.trim()).filter(Boolean);if(c.length<=1)return[e];let f=`${t}${i}${s??""} {`,u=a?`${t}} ${a};`:`${t}};`;return[f,...c.map((h)=>`${r}${h},`),u]}function ru(e,t,r,n){let i=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!i)return[e];let[,,s,o,a,c]=i,f=a.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${r}${s}${o}`,...f.map((u)=>`${n}${u.trim()};`),`${r}${c.trim()}`]}function iu(e,t,r,n){let i=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!i)return[e];let[,,s,o]=i,a=o.split(/\s*\|\s*/).filter((c)=>c.trim());if(a.length<=2)return[e];return[`${r}${s}`,...a.map((c,f)=>`${n}${f>0?"| ":" "}${c.trim()}`)]}async function _o(e,t={},r){let n=[];if(t.usePrettier!==!1){if(await jf())try{let i={...await Zf(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await Yf(e,i),usedPrettier:!0}}catch(i){n.push(`Prettier formatting failed: ${i}. Using built-in formatter.`)}else if(t.usePrettier===!0)n.push("Prettier requested but not available. Using built-in formatter.")}return{content:Jf(e,t.builtIn),usedPrettier:!1,warnings:n.length>0?n:void 0}}var Zr=null,Mt=null,eu;var Uo=he(()=>{eu=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/});import nu from"process";import{existsSync as Vo,statSync as Ho}from"fs";import{existsSync as su,mkdirSync as mg,readdirSync as gg,readFileSync as ou,writeFileSync as yg}from"fs";import{homedir as Xt}from"os";import{dirname as $g,resolve as at}from"path";import Ti from"process";import{existsSync as Ko,statSync as jo}from"fs";import{existsSync as Un,mkdirSync as au,readdirSync as lu,writeFileSync as cu}from"fs";import{homedir as Qt}from"os";import{dirname as Zo,resolve as Xe}from"path";import Gt from"process";import{join as fu,relative as uu,resolve as Yo}from"path";import di from"process";import{existsSync as Ra,mkdirSync as Pg,readdirSync as kg,writeFileSync as Mg}from"fs";import{homedir as En}from"os";import{dirname as Fg,resolve as ze}from"path";import vr from"process";import{join as hu,relative as du,resolve as Jo}from"path";import pi from"process";import{existsSync as Pa,mkdirSync as Bg,readdirSync as _g,writeFileSync as Ug}from"fs";import{dirname as Hg,resolve as mi}from"path";import Vn from"process";import{Buffer as Dt}from"buffer";import{createCipheriv as pu,createDecipheriv as mu,randomBytes as Sn}from"crypto";import{closeSync as An,createReadStream as qo,createWriteStream as gu,existsSync as xn,fsyncSync as zo,openSync as Xo,writeFileSync as yu}from"fs";import{access as Cu,constants as Qo,mkdir as wu,readdir as Yr,rename as ea,stat as er,unlink as Jr,writeFile as Tn}from"fs/promises";import{join as tr}from"path";import je from"process";import{pipeline as $u}from"stream/promises";import{createGzip as ta}from"zlib";import rr from"process";import bt from"process";import{Buffer as wt}from"buffer";import{createCipheriv as vu,createDecipheriv as bu,randomBytes as On}from"crypto";import{closeSync as Rn,createReadStream as ra,createWriteStream as Eu,existsSync as qr,fsyncSync as ia,openSync as na,writeFileSync as Su}from"fs";import{access as Au,constants as sa,mkdir as xu,readdir as zr,rename as oa,stat as ir,unlink as Xr,writeFile as Pn}from"fs/promises";import{isAbsolute as Tu,join as nr,resolve as Ou}from"path";import ge from"process";import{pipeline as Ru}from"stream/promises";import{createGzip as aa}from"zlib";import sr from"process";import Et from"process";import Qr from"process";import{existsSync as ei}from"fs";import{resolve as kn}from"path";import{existsSync as Pu}from"fs";import{existsSync as ku,readdirSync as Mu}from"fs";import{extname as Mn,resolve as la}from"path";import Du from"process";import{join as Iu,relative as Fu,resolve as ca}from"path";import gi from"process";import{Buffer as $t}from"buffer";import{createCipheriv as Nu,createDecipheriv as Wu,randomBytes as Dn}from"crypto";import{closeSync as In,createReadStream as fa,createWriteStream as Lu,existsSync as ti,fsyncSync as ua,openSync as ha,writeFileSync as Gu}from"fs";import{access as Bu,constants as da,mkdir as _u,readdir as ri,rename as pa,stat as or,unlink as ii,writeFile as Fn}from"fs/promises";import{isAbsolute as Uu,join as ar,resolve as Vu}from"path";import ye from"process";import{pipeline as Hu}from"stream/promises";import{createGzip as ma}from"zlib";import lr from"process";import St from"process";import ni from"process";import{existsSync as si}from"fs";import{resolve as Nn}from"path";import{existsSync as Ku}from"fs";class ka{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Vo(e))return!0;return Ho(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Vo(r)?Ho(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Ma{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Yu(e,t){this[e]=Zu.bind(null,t)}class ts{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Ko(e))return!0;return jo(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Ko(r)?jo(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class rs{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function zu(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function Xu(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Qu(e){return e.getStats().size*2}function is(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Te(t[0])&&"id"in t[0]&&t[0].id===3&&Te(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Te(t)&&Te(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(Te(e)&&"arr"in e&&Array.isArray(e.arr)&&Te(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Te(t[0])&&Te(e[0])){let n=[...t];for(let i of e)if(Te(i)&&"name"in i){if(!n.find((s)=>Te(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Te(i)&&"path"in i){if(!n.find((s)=>Te(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>Ci(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Te(t)||!Te(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Te(i)&&Te(r[n]))r[n]=is(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Te(i[0])&&Te(r[n][0])){let s=[...i];for(let o of r[n])if(Te(o)&&"name"in o){if(!s.find((a)=>Te(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(Te(o)&&"path"in o){if(!s.find((a)=>Te(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>Ci(a,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function Ci(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(!Ci(e[r],t[r]))return!1;return!0}if(Te(e)&&Te(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Ci(e[i],t[i]))return!1}return!0}return!1}function Te(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function eh(e,t){if(!Pa(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return is(t,n)}catch{return null}}catch{return null}}async function th({name:e="",cwd:t,defaultConfig:r}){let n=t||Vn.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let a of i){let c=mi(n,`${o}${a}`),f=await eh(c,r);if(f!==null)return f}try{let o=mi(n,"package.json");if(Pa(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return is(r,a)}catch{}}}catch{}return r}function rh(e,t={}){let r=pi.cwd();while(r.includes("storage"))r=Jo(r,"..");let n=Jo(r,e||"");if(t?.relative)return du(pi.cwd(),n);return n}async function ih(){try{let e=await th({name:"clarity",defaultConfig:ci,cwd:pi.cwd(),endpoint:"",headers:{}});return{...ci,...e}}catch{return ci}}function Pe(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nh(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bt<"u"){let e=bt.type;if(e==="renderer"||e==="worker")return!1;return!!(bt.versions&&(bt.versions.node||bt.versions.bun))}return!1}class Ia{async format(e){let t=await nh(),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:rr.pid,hostname:t(),environment:rr.env.NODE_ENV||"development",platform:rr.platform,version:rr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:rr.env.NODE_ENV||rr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class wi{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={...Kn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ia,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??je.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...fi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...fi};return{...fi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Kn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await Cu(this.config.logDirectory,Qo.F_OK|Qo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await wu(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:Dt.from(e);try{if(!xn(this.currentLogFile))await Tn(this.currentLogFile,"",{mode:420});if(n=Xo(this.currentLogFile,"a",420),yu(n,a,{flag:"a"}),zo(n),n!==void 0)An(n),n=void 0;if((await er(this.currentLogFile)).size===0){if(await Tn(this.currentLogFile,a,{flag:"w",mode:420}),(await er(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(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let h=o*2**i;await new Promise((l)=>setTimeout(l,h)),i++;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(n!==void 0)try{An(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===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}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 tr(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 tr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return tr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Pe())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((n)=>{console.error("Error rotating keys:",n)})},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 n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return Sn(16).toString("hex")}generateKey(){return Sn(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=Sn(16),n=pu("aes-256-gcm",t,r),i=Dt.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:Dt.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ta(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Dt.from(Dt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Pe())return;let e=await er(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Yr(this.config.logDirectory),s=i.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 er(r).catch(()=>null))try{if(await ea(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Jr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Tn(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 i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await er(r).catch(()=>null))await ea(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Yr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Jr(tr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=qo(e),n=gu(t),i=ta();await $u(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),xn(this.currentLogFile))try{let e=Xo(this.currentLogFile,"r+");zo(e),An(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(!Pe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Yr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Jr(tr(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?be.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(o)y.push(t);if(s==="warning")y.push("WARN");else if(s==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let c=je.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${be.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,h=a(t).length,l=Math.max(1,c-2-u-h);return`${f.trim()}${" ".repeat(l)}${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,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];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(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!Pe()){let f=Ha[e],u=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:be.gray(o),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:be.green(o),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(h),a){let l=a.split(`
|
|
61
|
-
`);for(let y of l)if(y.trim()&&!y.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:be.gray(` ${y}`),level:e,showTimestamp:!1}))}break}}else if(!Pe()){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}
|
|
33
|
+
`:""}# dtsx cache
|
|
34
|
+
${Yr}/
|
|
35
|
+
`;js(t,i)}}catch{}}var $n=3,Yr=".dtsx-cache",jf="manifest.json";var Us=he(()=>{Sn()});function Ks(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 Hs=()=>{};import _f from"process";import{existsSync as zs,statSync as Js}from"fs";import{existsSync as Vf,mkdirSync as bg,readdirSync as Eg,readFileSync as Uf,writeFileSync as Sg}from"fs";import{homedir as Zt}from"os";import{dirname as xg,resolve as st}from"path";import Pi from"process";import{existsSync as qs,statSync as Ys}from"fs";import{existsSync as Hn,mkdirSync as Kf,readdirSync as Hf,writeFileSync as zf}from"fs";import{homedir as Xt}from"os";import{dirname as Zs,resolve as Ze}from"path";import Bt from"process";import{join as Jf,relative as qf,resolve as Xs}from"path";import gi from"process";import{existsSync as Da,mkdirSync as Ng,readdirSync as Lg,writeFileSync as Wg}from"fs";import{homedir as Tn}from"os";import{dirname as jg,resolve as Ye}from"path";import Sr from"process";import{join as Yf,relative as Zf,resolve as Qs}from"path";import yi from"process";import{existsSync as Ia,mkdirSync as Hg,readdirSync as zg,writeFileSync as Jg}from"fs";import{dirname as Yg,resolve as Ci}from"path";import zn from"process";import{Buffer as kt}from"buffer";import{createCipheriv as Xf,createDecipheriv as Qf,randomBytes as On}from"crypto";import{closeSync as Rn,createReadStream as ea,createWriteStream as eu,existsSync as Pn,fsyncSync as ta,openSync as ra,writeFileSync as tu}from"fs";import{access as ru,constants as ia,mkdir as iu,readdir as Zr,rename as na,stat as Qt,unlink as Xr,writeFile as kn}from"fs/promises";import{join as er}from"path";import Ke from"process";import{pipeline as nu}from"stream/promises";import{createGzip as oa}from"zlib";import tr from"process";import bt from"process";import{Buffer as Ct}from"buffer";import{createCipheriv as ou,createDecipheriv as su,randomBytes as Mn}from"crypto";import{closeSync as Dn,createReadStream as sa,createWriteStream as au,existsSync as Qr,fsyncSync as aa,openSync as la,writeFileSync as lu}from"fs";import{access as cu,constants as ca,mkdir as fu,readdir as ei,rename as fa,stat as rr,unlink as ti,writeFile as In}from"fs/promises";import{isAbsolute as uu,join as ir,resolve as hu}from"path";import ge from"process";import{pipeline as du}from"stream/promises";import{createGzip as ua}from"zlib";import nr from"process";import Et from"process";import ri from"process";import{existsSync as ii}from"fs";import{resolve as Fn}from"path";import{existsSync as mu}from"fs";import{existsSync as pu,readdirSync as gu}from"fs";import{extname as Nn,resolve as ha}from"path";import yu from"process";import{join as Cu,relative as wu,resolve as da}from"path";import wi from"process";import{Buffer as wt}from"buffer";import{createCipheriv as vu,createDecipheriv as bu,randomBytes as Ln}from"crypto";import{closeSync as Wn,createReadStream as ma,createWriteStream as Eu,existsSync as ni,fsyncSync as pa,openSync as ga,writeFileSync as Su}from"fs";import{access as $u,constants as ya,mkdir as Au,readdir as oi,rename as Ca,stat as or,unlink as si,writeFile as Bn}from"fs/promises";import{isAbsolute as xu,join as sr,resolve as Tu}from"path";import ye from"process";import{pipeline as Ou}from"stream/promises";import{createGzip as wa}from"zlib";import ar from"process";import St from"process";import ai from"process";import{existsSync as li}from"fs";import{resolve as Gn}from"path";import{existsSync as Ru}from"fs";class Fa{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!zs(e))return!0;return Js(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=zs(r)?Js(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Na{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Mu(e,t){this[e]=ku.bind(null,t)}class oo{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!qs(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,n){try{let i=qs(r)?Ys(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class so{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Fu(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function Nu(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Lu(e){return e.getStats().size*2}function ao(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Te(t[0])&&"id"in t[0]&&t[0].id===3&&Te(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Te(t)&&Te(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(Te(e)&&"arr"in e&&Array.isArray(e.arr)&&Te(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Te(t[0])&&Te(e[0])){let n=[...t];for(let i of e)if(Te(i)&&"name"in i){if(!n.find((o)=>Te(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(Te(i)&&"path"in i){if(!n.find((o)=>Te(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((o)=>bi(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Te(t)||!Te(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Te(i)&&Te(r[n]))r[n]=ao(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Te(i[0])&&Te(r[n][0])){let o=[...i];for(let s of r[n])if(Te(s)&&"name"in s){if(!o.find((a)=>Te(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(Te(s)&&"path"in s){if(!o.find((a)=>Te(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>bi(a,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function bi(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(!bi(e[r],t[r]))return!1;return!0}if(Te(e)&&Te(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!bi(e[i],t[i]))return!1}return!0}return!1}function Te(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Wu(e,t){if(!Ia(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return ao(t,n)}catch{return null}}catch{return null}}async function Bu({name:e="",cwd:t,defaultConfig:r}){let n=t||zn.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let a of i){let c=Ci(n,`${s}${a}`),f=await Wu(c,r);if(f!==null)return f}try{let s=Ci(n,"package.json");if(Ia(s)){let a=(await import(s))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return ao(r,a)}catch{}}}catch{}return r}function Gu(e,t={}){let r=yi.cwd();while(r.includes("storage"))r=Qs(r,"..");let n=Qs(r,e||"");if(t?.relative)return Zf(yi.cwd(),n);return n}async function ju(){try{let e=await Bu({name:"clarity",defaultConfig:hi,cwd:yi.cwd(),endpoint:"",headers:{}});return{...hi,...e}}catch{return hi}}function Pe(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _u(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bt<"u"){let e=bt.type;if(e==="renderer"||e==="worker")return!1;return!!(bt.versions&&(bt.versions.node||bt.versions.bun))}return!1}class Wa{async format(e){let t=await _u(),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:tr.pid,hostname:t(),environment:tr.env.NODE_ENV||"development",platform:tr.platform,version:tr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tr.env.NODE_ENV||tr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ei{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={...qn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Wa,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??Ke.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...di,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...di};return{...di,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:qn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let n,i=0,o=3,s=1000;while(i<o)try{try{try{await ru(this.config.logDirectory,ia.F_OK|ia.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await iu(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:kt.from(e);try{if(!Pn(this.currentLogFile))await kn(this.currentLogFile,"",{mode:420});if(n=ra(this.currentLogFile,"a",420),tu(n,a,{flag:"a"}),ta(n),n!==void 0)Rn(n),n=void 0;if((await Qt(this.currentLogFile)).size===0){if(await kn(this.currentLogFile,a,{flag:"w",mode:420}),(await Qt(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(i<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let h=s*2**i;await new Promise((l)=>setTimeout(l,h)),i++;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(n!==void 0)try{Rn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 er(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 er(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return er(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Pe())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((n)=>{console.error("Error rotating keys:",n)})},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 n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return On(16).toString("hex")}generateKey(){return On(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=On(16),n=Xf("aes-256-gcm",t,r),i=kt.concat([n.update(e,"utf8"),n.final()]),o=n.getAuthTag();return{encrypted:kt.concat([r,i,o]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=oa(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(kt.from(kt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Pe())return;let e=await Qt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Zr(this.config.logDirectory),o=i.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}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await Qt(r).catch(()=>null))try{if(await na(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Xr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await kn(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 i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await Qt(r).catch(()=>null))await na(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await Zr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await Xr(er(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=ea(e),n=eu(t),i=oa();await nu(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Pn(this.currentLogFile))try{let e=ra(this.currentLogFile,"r+");ta(e),Rn(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(!Pe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Zr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Xr(er(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?Ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,a=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(t);if(o==="warning")y.push("WARN");else if(o==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let c=Ke.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${Ee.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,h=a(t).length,l=Math.max(1,c-2-u-h);return`${f.trim()}${" ".repeat(l)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){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 o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);if(this.fancy&&!Pe()){let f=Ja[e],u=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ee.gray(s),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ee.green(s),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.error(h),a){let l=a.split(`
|
|
36
|
+
`);for(let y of l)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:Ee.gray(` ${y}`),level:e,showTimestamp:!1}))}break}}else if(!Pe()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}if(!this.shouldLog(e))return;let c=`${o} ${this.environment}.${e.toUpperCase()}: ${s}
|
|
62
37
|
`;if(a)c+=`${a}
|
|
63
|
-
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!Pe()){let r=this.options.showTags!==!1&&this.name?
|
|
64
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!Pe()){let f=this.options.showTags!==!1&&this.name?
|
|
65
|
-
`),
|
|
66
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(Pe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${
|
|
67
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||Pe()||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:(n,i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Pe())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,n)),i!==void 0)this.activeProgressBar.message=i;let
|
|
68
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Pe()||!je.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(Pe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Yr(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=tr(this.config.logDirectory,n);if(e.before)try{if((await er(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Jr(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function li(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Ce(t[0])&&"id"in t[0]&&t[0].id===3&&Ce(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Ce(t)&&Ce(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(Ce(e)&&"arr"in e&&Array.isArray(e.arr)&&Ce(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Ce(t[0])&&Ce(e[0])){let n=[...t];for(let i of e)if(Ce(i)&&"name"in i){if(!n.find((s)=>Ce(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Ce(i)&&"path"in i){if(!n.find((s)=>Ce(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>$i(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Ce(t)||!Ce(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Ce(i)&&Ce(r[n]))r[n]=li(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Ce(i[0])&&Ce(r[n][0])){let s=[...i];for(let o of r[n])if(Ce(o)&&"name"in o){if(!s.find((a)=>Ce(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(Ce(o)&&"path"in o){if(!s.find((a)=>Ce(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>$i(a,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function ns(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:li(e,t);if(Array.isArray(e))return r==="replace"?t:li(e,t);if(!Ce(t)||!Ce(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=li(o,s);else if(Ce(s)&&Ce(o))n[i]=ns(o,s,r);else n[i]=s}return n}function $i(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(!$i(e[r],t[r]))return!1;return!0}if(Ce(e)&&Ce(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!$i(e[i],t[i]))return!1}return!0}return!1}function Ce(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function oi(e,t,r="replace"){if(!Ra(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return ns(t,i,r)}catch{return null}}catch{return null}}function sh(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let h=[...a,f],l=(S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${n}_${h.map(l).join("_")}`,C=`${n}_${h.map((S)=>S.toUpperCase()).join("_")}`;if(r)Ye.info(`Checking environment variable ${y} for config ${e}.${h.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,h);else{let S=vr.env[y]||vr.env[C];if(S!==void 0){if(r)Ye.info(`Using environment variable ${S?y:C} for config ${e}.${h.join(".")}`);if(typeof u==="number")c[f]=Number(S);else if(typeof u==="boolean")c[f]=S.toLowerCase()==="true";else if(Array.isArray(u))try{let x=JSON.parse(S);if(Array.isArray(x))c[f]=x;else c[f]=S.split(",").map((v)=>v.trim())}catch{c[f]=S.split(",").map((x)=>x.trim())}else c[f]=S}}}return c}return s(i)}async function oh({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:a="replace"}){let c=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?sh(e,i,s):i,f=r||vr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Ye.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let h=[e,`.${e}`].filter(Boolean),l=[`${e}.config`,`.${e}.config`].filter(Boolean),y=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],S=Array.from(new Set([f,ze(f,"config"),ze(f,".config"),n?ze(f,n):void 0].filter(Boolean)));for(let x of S){if(s)Ye.info(`Searching for configuration in: ${x}`);let v=[ze(f,"config"),ze(f,".config")].concat(n?[ze(f,n)]:[]).includes(x)?[...h,...l,...y,...C]:[...l,...h,...C,...y];for(let B of v)for(let W of u){let P=ze(x,`${B}${W}`),F=await oi(P,c,a);if(F!==null){if(s)Ye.success(`Configuration loaded from: ${P}`);return F}}}if(e){let x=ze(En(),".config",e),v=["config",`${e}.config`];if(t)v.push(`${t}.config`);if(s)Ye.info(`Checking user config directory: ${x}`);for(let B of v)for(let W of u){let P=ze(x,`${B}${W}`),F=await oi(P,c,a);if(F!==null){if(s)Ye.success(`Configuration loaded from user config directory: ${P}`);return F}}}if(e){let x=ze(En(),".config"),v=[`.${e}.config`];if(t)v.push(`.${t}.config`);if(s)Ye.info(`Checking user config directory for dotfile configs: ${x}`);for(let B of v)for(let W of u){let P=ze(x,`${B}${W}`),F=await oi(P,c,a);if(F!==null){if(s)Ye.success(`Configuration loaded from user config directory dotfile: ${P}`);return F}}}if(e){let x=En(),v=[`.${e}.config`,`.${e}`];if(t)v.push(`.${t}.config`),v.push(`.${t}`);if(s)Ye.info(`Checking user home directory for dotfile configs: ${x}`);for(let B of v)for(let W of u){let P=ze(x,`${B}${W}`),F=await oi(P,c,a);if(F!==null){if(s)Ye.success(`Configuration loaded from user home directory: ${P}`);return F}}}try{let x=ze(f,"package.json");if(Ra(x)){let v=await import(x),B=v[e];if(!B&&t){if(B=v[t],B&&s)Ye.success(`Using alias "${t}" configuration from package.json`)}if(B&&typeof B==="object"&&!Array.isArray(B))try{if(s)Ye.success(`Configuration loaded from package.json: ${B===v[e]?e:t}`);return ns(c,B,a)}catch(W){if(s)Ye.warn("Failed to merge package.json config:",W)}}}catch(x){if(s)Ye.warn("Failed to load package.json:",x)}if(s)Ye.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function ah(e,t={}){let r=di.cwd();while(r.includes("storage"))r=Yo(r,"..");let n=Yo(r,e||"");if(t?.relative)return uu(di.cwd(),n);return n}async function lh(){try{let e=await oh({name:"clarity",alias:"logging",defaultConfig:ui,cwd:di.cwd()});return{...ui,...e||{}}}catch{return ui}}function Ne(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ch(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Et<"u"){let e=Et.type;if(e==="renderer"||e==="worker")return!1;return!!(Et.versions&&(Et.versions.node||Et.versions.bun))}return!1}class Fa{async format(e){let t=await ch(),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:sr.pid,hostname:t(),environment:sr.env.NODE_ENV||"development",platform:sr.platform,version:sr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:sr.env.NODE_ENV||sr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class vi{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={...jn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Fa,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??ge.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...hi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...hi};return{...hi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:jn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ne()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await Au(this.config.logDirectory,sa.F_OK|sa.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await xu(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:wt.from(e);try{if(!qr(this.currentLogFile))await Pn(this.currentLogFile,"",{mode:420});if(n=na(this.currentLogFile,"a",420),Su(n,a,{flag:"a"}),ia(n),n!==void 0)Rn(n),n=void 0;if((await ir(this.currentLogFile)).size===0){if(await Pn(this.currentLogFile,a,{flag:"w",mode:420}),(await ir(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(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let h=o*2**i;await new Promise((l)=>setTimeout(l,h)),i++;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(n!==void 0)try{Rn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===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}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 nr(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 nr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return nr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ne())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((n)=>{console.error("Error rotating keys:",n)})},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 n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return On(16).toString("hex")}generateKey(){return On(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=On(16),n=vu("aes-256-gcm",t,r),i=wt.isBuffer(e)?e:wt.from(e,"utf8"),s=n.update(i),o=n.final(),a=s.length+o.length,c=n.getAuthTag(),f=wt.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 n=aa(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(wt.from(wt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ne())return;if(!this.shouldWriteToFile())return;let e=await ir(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await zr(this.config.logDirectory),s=i.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 ir(r).catch(()=>null))try{if(await oa(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Xr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Pn(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 i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await ir(r).catch(()=>null))await oa(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await zr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Xr(nr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=ra(e),n=Eu(t),i=aa();await Ru(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),qr(this.currentLogFile))try{let e=na(this.currentLogFile,"r+");ia(e),Rn(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(!Ne()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await zr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Xr(nr(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()?ce.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ne())return!1;let e=typeof ge.env.NO_COLOR<"u",t=ge.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ge.stderr<"u"&&ge.stderr.isTTY||typeof ge.stdout<"u"&&ge.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(o)y.push(t);if(s==="warning")y.push("WARN");else if(s==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let c=ge.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${ce.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,h=a(t).length,l=Math.max(1,c-2-u-h);return`${f.trim()}${" ".repeat(l)}${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,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];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(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=ce.underline(ce.blue(n)),o=this.toAbsoluteFilePath(i);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;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>ce.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>ce.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>ce.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>ce.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>ce.strikethrough(n)),t}supportsHyperlinks(){if(Ne())return!1;let e=ge.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=ge.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Tu(t)||t.startsWith("./")||t.startsWith("../"))t=Ou(t);else return null;return qr(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,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 h=this.options.showIcons===!1?"":Ka[e],l=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:ce.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:ce.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.error(y),a){let C=a.split(`
|
|
69
|
-
`);for(let S of C)if(S.trim()&&!S.includes(
|
|
38
|
+
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!Pe()){let r=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:Ee.blue("\u25D0"),tag:r,message:`${Ee.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
39
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!Pe()){let f=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:Ee.green("\u2713"),tag:f,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Pe())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 Ei(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(Pe())throw Error("createReadStream is not supported in browser environments");if(!Pn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ea(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=kt.isBuffer(e)?e:kt.from(e,"base64"),i=n.slice(0,16),o=n.slice(-16),s=n.slice(16,-16),a=Qf("aes-256-gcm",r,i);return a.setAuthTag(o),kt.concat([a.update(s),a.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Pe()}isServerMode(){return!Pe()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!Pe()){let o=e.split(`
|
|
40
|
+
`),s=Math.max(...o.map((u)=>u.length))+2,a=`\u250C${"\u2500".repeat(s)}\u2510`,c=`\u2514${"\u2500".repeat(s)}\u2518`,f=o.map((u)=>{let h=" ".repeat(s-u.length-2);return`\u2502 ${u}${h} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:Ee.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Ee.cyan(a)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:Ee.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:Ee.cyan(c),showTimestamp:!1}))}else if(!Pe())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
41
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(Pe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ee.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Ke.stdin.removeListener("data",r);try{if(typeof Ke.stdin.setRawMode==="function")Ke.stdin.setRawMode(!1)}catch{}Ke.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Ke.stdin.setRawMode==="function")Ke.stdin.setRawMode(!0)}catch{}Ke.stdin.resume(),Ke.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 i=/%([sdijfo%])/g,o=0;if(r=e.replace(i,(s,a)=>{if(a==="%")return"%";if(o>=t.length)return s;let c=t[o++];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 s}}),o<t.length)r+=` ${t.slice(o).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!Pe()){let i=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",o=Ee.blue("\u25D0");console.error(`${o} ${i} ${Ee.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
42
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||Pe()||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:(n,i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Pe())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,n)),i!==void 0)this.activeProgressBar.message=i;let o=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,o)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Pe())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,i="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Pe())return;Ke.stdout.write(`${"\r".padEnd(Ke.stdout.columns||80)}\r`),this.log(i,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||Pe()||!Ke.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=Ee.green("\u2501".repeat(n)),s=Ee.gray("\u2501".repeat(i)),a=`[${o}${s}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||r===100?Ee.green("\u2713"):Ee.blue("\u25B6"),h=this.options.showTags!==!1&&this.name?` ${Ee.gray(this.formatTag(this.name))}`:"",l=`\r${u}${h} ${a} ${c}${f}`,y=Ke.stdout.columns||80,C=" ".repeat(Math.max(0,y-l.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${l}${C}`,Ke.stdout.write(e.lastRenderedLine),t)Ke.stdout.write(`
|
|
43
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Pe()||!Ke.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(Pe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Zr(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=er(this.config.logDirectory,n);if(e.before)try{if((await Qt(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Xr(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ui(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Ce(t[0])&&"id"in t[0]&&t[0].id===3&&Ce(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Ce(t)&&Ce(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(Ce(e)&&"arr"in e&&Array.isArray(e.arr)&&Ce(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Ce(t[0])&&Ce(e[0])){let n=[...t];for(let i of e)if(Ce(i)&&"name"in i){if(!n.find((o)=>Ce(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(Ce(i)&&"path"in i){if(!n.find((o)=>Ce(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((o)=>Si(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Ce(t)||!Ce(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Ce(i)&&Ce(r[n]))r[n]=ui(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Ce(i[0])&&Ce(r[n][0])){let o=[...i];for(let s of r[n])if(Ce(s)&&"name"in s){if(!o.find((a)=>Ce(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(Ce(s)&&"path"in s){if(!o.find((a)=>Ce(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>Si(a,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function lo(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ui(e,t);if(Array.isArray(e))return r==="replace"?t:ui(e,t);if(!Ce(t)||!Ce(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let o=t[i],s=n[i];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(s))if(r==="replace")n[i]=o;else n[i]=ui(s,o);else if(Ce(o)&&Ce(s))n[i]=lo(s,o,r);else n[i]=o}return n}function Si(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(!Si(e[r],t[r]))return!1;return!0}if(Ce(e)&&Ce(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Si(e[i],t[i]))return!1}return!0}return!1}function Ce(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ci(e,t,r="replace"){if(!Da(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return lo(t,i,r)}catch{return null}}catch{return null}}function Vu(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let h=[...a,f],l=(S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${n}_${h.map(l).join("_")}`,C=`${n}_${h.map((S)=>S.toUpperCase()).join("_")}`;if(r)ze.info(`Checking environment variable ${y} for config ${e}.${h.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=o(u,h);else{let S=Sr.env[y]||Sr.env[C];if(S!==void 0){if(r)ze.info(`Using environment variable ${S?y:C} for config ${e}.${h.join(".")}`);if(typeof u==="number")c[f]=Number(S);else if(typeof u==="boolean")c[f]=S.toLowerCase()==="true";else if(Array.isArray(u))try{let x=JSON.parse(S);if(Array.isArray(x))c[f]=x;else c[f]=S.split(",").map((v)=>v.trim())}catch{c[f]=S.split(",").map((x)=>x.trim())}else c[f]=S}}}return c}return o(i)}async function Uu({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:o=!1,checkEnv:s=!0,arrayStrategy:a="replace"}){let c=s&&typeof i==="object"&&i!==null&&!Array.isArray(i)?Vu(e,i,o):i,f=r||Sr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)ze.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let h=[e,`.${e}`].filter(Boolean),l=[`${e}.config`,`.${e}.config`].filter(Boolean),y=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],S=Array.from(new Set([f,Ye(f,"config"),Ye(f,".config"),n?Ye(f,n):void 0].filter(Boolean)));for(let x of S){if(o)ze.info(`Searching for configuration in: ${x}`);let v=[Ye(f,"config"),Ye(f,".config")].concat(n?[Ye(f,n)]:[]).includes(x)?[...h,...l,...y,...C]:[...l,...h,...C,...y];for(let G of v)for(let L of u){let P=Ye(x,`${G}${L}`),F=await ci(P,c,a);if(F!==null){if(o)ze.success(`Configuration loaded from: ${P}`);return F}}}if(e){let x=Ye(Tn(),".config",e),v=["config",`${e}.config`];if(t)v.push(`${t}.config`);if(o)ze.info(`Checking user config directory: ${x}`);for(let G of v)for(let L of u){let P=Ye(x,`${G}${L}`),F=await ci(P,c,a);if(F!==null){if(o)ze.success(`Configuration loaded from user config directory: ${P}`);return F}}}if(e){let x=Ye(Tn(),".config"),v=[`.${e}.config`];if(t)v.push(`.${t}.config`);if(o)ze.info(`Checking user config directory for dotfile configs: ${x}`);for(let G of v)for(let L of u){let P=Ye(x,`${G}${L}`),F=await ci(P,c,a);if(F!==null){if(o)ze.success(`Configuration loaded from user config directory dotfile: ${P}`);return F}}}if(e){let x=Tn(),v=[`.${e}.config`,`.${e}`];if(t)v.push(`.${t}.config`),v.push(`.${t}`);if(o)ze.info(`Checking user home directory for dotfile configs: ${x}`);for(let G of v)for(let L of u){let P=Ye(x,`${G}${L}`),F=await ci(P,c,a);if(F!==null){if(o)ze.success(`Configuration loaded from user home directory: ${P}`);return F}}}try{let x=Ye(f,"package.json");if(Da(x)){let v=await import(x),G=v[e];if(!G&&t){if(G=v[t],G&&o)ze.success(`Using alias "${t}" configuration from package.json`)}if(G&&typeof G==="object"&&!Array.isArray(G))try{if(o)ze.success(`Configuration loaded from package.json: ${G===v[e]?e:t}`);return lo(c,G,a)}catch(L){if(o)ze.warn("Failed to merge package.json config:",L)}}}catch(x){if(o)ze.warn("Failed to load package.json:",x)}if(o)ze.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Ku(e,t={}){let r=gi.cwd();while(r.includes("storage"))r=Xs(r,"..");let n=Xs(r,e||"");if(t?.relative)return qf(gi.cwd(),n);return n}async function Hu(){try{let e=await Uu({name:"clarity",alias:"logging",defaultConfig:mi,cwd:gi.cwd()});return{...mi,...e||{}}}catch{return mi}}function Ne(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zu(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Et<"u"){let e=Et.type;if(e==="renderer"||e==="worker")return!1;return!!(Et.versions&&(Et.versions.node||Et.versions.bun))}return!1}class Ba{async format(e){let t=await zu(),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:nr.pid,hostname:t(),environment:nr.env.NODE_ENV||"development",platform:nr.platform,version:nr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:nr.env.NODE_ENV||nr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $i{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??ge.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,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{...pi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...pi};return{...pi,...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(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ne()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,o=3,s=1000;while(i<o)try{try{try{await cu(this.config.logDirectory,ca.F_OK|ca.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await fu(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(!Qr(this.currentLogFile))await In(this.currentLogFile,"",{mode:420});if(n=la(this.currentLogFile,"a",420),lu(n,a,{flag:"a"}),aa(n),n!==void 0)Dn(n),n=void 0;if((await rr(this.currentLogFile)).size===0){if(await In(this.currentLogFile,a,{flag:"w",mode:420}),(await rr(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(i<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let h=s*2**i;await new Promise((l)=>setTimeout(l,h)),i++;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(n!==void 0)try{Dn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 ir(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 ir(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ir(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ne())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((n)=>{console.error("Error rotating keys:",n)})},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 n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Mn(16).toString("hex")}generateKey(){return Mn(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=Mn(16),n=ou("aes-256-gcm",t,r),i=Ct.isBuffer(e)?e:Ct.from(e,"utf8"),o=n.update(i),s=n.final(),a=o.length+s.length,c=n.getAuthTag(),f=Ct.allocUnsafe(16+a+16);return r.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ua(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Ct.from(Ct.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ne())return;if(!this.shouldWriteToFile())return;let e=await rr(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ei(this.config.logDirectory),o=i.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}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await rr(r).catch(()=>null))try{if(await fa(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await ti(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await In(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 i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await rr(r).catch(()=>null))await fa(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await ei(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await ti(ir(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=sa(e),n=au(t),i=ua();await du(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Qr(this.currentLogFile))try{let e=la(this.currentLogFile,"r+");aa(e),Dn(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(!Ne()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ei(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await ti(ir(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()?ce.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ne())return!1;let e=typeof ge.env.NO_COLOR<"u",t=ge.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ge.stderr<"u"&&ge.stderr.isTTY||typeof ge.stdout<"u"&&ge.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,a=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(t);if(o==="warning")y.push("WARN");else if(o==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let c=ge.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${ce.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,h=a(t).length,l=Math.max(1,c-2-u-h);return`${f.trim()}${" ".repeat(l)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){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 o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=ce.underline(ce.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>ce.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>ce.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>ce.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>ce.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>ce.strikethrough(n)),t}supportsHyperlinks(){if(Ne())return!1;let e=ge.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=ge.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(uu(t)||t.startsWith("./")||t.startsWith("../"))t=hu(t);else return null;return Qr(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":qa[e],l=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:ce.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:ce.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.error(y),a){let C=a.split(`
|
|
44
|
+
`);for(let S of C)if(S.trim()&&!S.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:ce.gray(` ${S}`),level:e,showTimestamp:!1}))}break}}else if(!Ne()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}if(!this.shouldLog(e))return;let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
70
45
|
`;if(a)u+=`${a}
|
|
71
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,
|
|
72
|
-
`);if(this[
|
|
73
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":ce.green("\u2713"),tag:f,message:`${
|
|
74
|
-
`),c=Math.max(...a.map((l)=>l.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,h=a.map((l)=>this.formatConsoleMessage({timestamp:r,message:ce.cyan(l),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:ce.cyan(f),showTimestamp:!1})),h.forEach((l)=>console.error(l)),console.error(this.formatConsoleMessage({timestamp:r,message:ce.cyan(u),showTimestamp:!1}))}else if(!Ne())console.error(`${n} ${this.environment}.INFO: [BOX] ${
|
|
75
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
76
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
77
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ne()||!ge.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(Ne()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await
|
|
46
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,o)=>{},finish:(i)=>{},interrupt:(i,o)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ne()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!Ne()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,o="info")=>{if(!Ne()&&ge.stdout.isTTY)ge.stdout.write(`
|
|
47
|
+
`);if(this[o==="warning"?"warn":o](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Ne()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":ce.blue("\u25D0"),tag:r,message:`${ce.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
48
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":ce.green("\u2713"),tag:f,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ne())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 $i(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(Ne())throw Error("createReadStream is not supported in browser environments");if(!Qr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return sa(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Ct.isBuffer(e)?e:Ct.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),a=su("aes-256-gcm",r,i);a.setAuthTag(o);let c=a.update(s),f=a.final(),u=c.length+f.length,h=Ct.allocUnsafe(u);return c.copy(h,0),f.copy(h,c.length),h.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ne()}isServerMode(){return!Ne()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=i.split(`
|
|
49
|
+
`),c=Math.max(...a.map((l)=>l.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,h=a.map((l)=>this.formatConsoleMessage({timestamp:r,message:ce.cyan(l),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:ce.cyan(f),showTimestamp:!1})),h.forEach((l)=>console.error(l)),console.error(this.formatConsoleMessage({timestamp:r,message:ce.cyan(u),showTimestamp:!1}))}else if(!Ne())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
|
|
50
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(Ne())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ce.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();ge.stdin.removeListener("data",r);try{if(typeof ge.stdin.setRawMode==="function")ge.stdin.setRawMode(!1)}catch{}ge.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof ge.stdin.setRawMode==="function")ge.stdin.setRawMode(!0)}catch{}ge.stdin.resume(),ge.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 s=/%([sdijfo%])/g,a=0;if(r=e.replace(s,(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:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${ce.blue("\u25D0")} `;console.error(`${a}${s} ${ce.cyan(n)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
51
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ge.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=ce.green("\u2501".repeat(n)),s=ce.gray("\u2501".repeat(i)),a=`[${o}${s}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?ce.green("\u2713"):ce.blue("\u25B6"),h=this.options.showTags!==!1&&this.name?` ${ce.gray(this.formatTag(this.name))}`:"",l=`\r${u}${h} ${a} ${c}${f}`,y=ge.stdout.columns||80,C=" ".repeat(Math.max(0,y-l.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${l}${C}`,ge.stdout.write(e.lastRenderedLine),t)ge.stdout.write(`
|
|
52
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ne()||!ge.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(Ne()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ei(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=ir(this.config.logDirectory,n);if(e.before)try{if((await rr(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await ti(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Ga(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(s=c instanceof Error?c:Error(String(c)),a===r||!i(s))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function ja(e){return e instanceof rt}function Ju(e){return e instanceof Ai}function qu(e){if(ja(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 ki{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:a=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),h={...t};return this.processObject(h,[],u,{useCamelCase:i,useBackwardCompatibility:o,customParsers:s,verbose:a,configName:e}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return xr.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,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],a=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${a.join("_")}`,f=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,r,n);else{let u=ri.env[c]||(f?ri.env[f]:void 0);if(u!==void 0){if(n.verbose){let h=ri.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof o,c,n.customParsers,n.configName)}catch(h){if(h instanceof xi)throw h;throw Mt.envVar(c,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw Mt.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(ri.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],a=`${r}_${s.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,r,n);else n.push({key:a,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}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}:
|
|
78
53
|
|
|
79
54
|
`;for(let n of e)r+=`${n.key}
|
|
80
55
|
`,r+=` Type: ${n.type}
|
|
@@ -86,25 +61,25 @@ ${z.join(`
|
|
|
86
61
|
`;r+=`| Variable | Type | Description | Example |
|
|
87
62
|
`,r+=`|----------|------|-------------|----------|
|
|
88
63
|
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
89
|
-
`;return r}}function hh(e,t){let r=Ua("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function La(e,t,r={}){return Ga(e,t,r,new WeakMap)}function Ga(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Ba(e,t,i,n);if(!lt(t)||!lt(e))return t;return gh(e,t,r,n)}function Ba(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return dh(e,t);case"smart":return ph(e,t,n);default:return t}return t}function dh(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Hn(i,n)))r.push(n);return r}function ph(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(lt(t[0])&<(e[0]))return mh(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function mh(e,t,r){let n=[...t];for(let i of e){if(!lt(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in i){if(n.find((c)=>lt(c)&&(a in c)&&c[a]===i[a])){o=!0;break}}if(!o)n.push(i)}return n}function gh(e,t,r,n){let i=t;if(lt(i)&&n.has(i))return n.get(i);let s={...e};if(lt(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let a=i[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(lt(a)&<(c))s[o]=Ga(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))s[o]=Ba(c,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function ss(e,t,r="replace"){return La(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Hn(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(!Hn(e[r],t[r]))return!1;return!0}if(lt(e)&<(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Hn(e[i],t[i]))return!1}return!0}return!1}function lt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ri{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(i){let f=cr.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ei(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),h=u.default||u,l="default"in u,y=Object.keys(u).length>0;if(!l&&!y)throw new br(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new br(e,Error("Configuration must export a valid object"),"unknown");let C={config:ss(t,h,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)cr.setWithFileCheck("file",C,e,s);return C}catch(f){throw f instanceof Error?It.configLoad(e,f):It.configLoad(e,Error(String(f)))}};if(o)return Sr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(kn(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Na(async()=>ei(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ei(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let a=kn(e,`${s}${o}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=kn(e,o);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!ei(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class os{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],h=[],l={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,l);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],l);else return this.validateWithJSONSchema(e,t,l)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:h}}};if(a)return await Sr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Pu(t))throw new Er(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Er(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(n.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(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(n.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,n,i,s),s.stopOnFirstError&&n.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))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Za},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class as{fileLoader=new Ri;envProcessor=new Oi;validator=new os;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,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"),h=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),l=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(l||u))throw c;if(h&&(!f||!l))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(i||s)await this.validateConfiguration(a.config,i,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)ht.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw ht.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,h=s||Gt.cwd(),l=[],y=await this.loadLocalConfiguration(n,i,h,o,a,f,u,c,r);if(y)return l.push(...this.getLocalSearchPaths(n,i,h,o)),this.finalizeResult(y,l,c,n,u);let C=await this.loadHomeConfiguration(n,i,a,f,u,c);if(C)return l.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(C,l,c,n,u);let S=await this.loadPackageJsonConfiguration(n,i,h,a,f,u,c);if(S)return l.push(Xe(h,"package.json")),this.finalizeResult(S,l,c,n,u);if(l.push(...this.getAllSearchPaths(n,i,h,o)),t)throw It.configNotFound(n,l,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,a,c){let f=a?$r(e,i,o):i,u=this.getLocalDirectories(r,n);for(let h of u){if(o)ht.info(`Searching for configuration in: ${h}`);let l=this.fileLoader.generateConfigPaths(e,h,t),y=await this.fileLoader.tryLoadFromPaths(l,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(o)ht.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?$r(e,r,i):r,a=[Xe(Qt(),".config",e),Xe(Qt(),".config"),Qt()];for(let c of a){if(i)ht.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,o,{arrayStrategy:n,verbose:i});if(u){if(i)ht.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let a=o?$r(e,n,s):n;try{let c=Xe(r,"package.json");if(!Un(c))return null;let f=await import(c),u=f[e],h=e;if(!u&&t)u=f[t],h=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)ht.success(`Configuration loaded from package.json: ${h}`);return{config:ss(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)ht.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:$r(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw It.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return cr.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);cr.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Xe(e,"config"),Xe(e,".config"),t?Xe(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(Xe(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Xe(Qt(),".config",e),Xe(Qt(),".config"),Qt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ga(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 yh(e){return At.loadConfig({...e,__strictErrorHandling:!0})}async function _a(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await At.loadConfig(e);else n=await At.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)ht.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);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 At.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function Ch(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await At.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"&&ga(r)))return(await At.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await At.loadConfig({...e,cwd:e.cwd||Gt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&ga(t)))return(await At.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function wh(e,t,r="replace"){let n=new Ri;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function $r(e,t,r=!1){let n=new Oi,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let h=[...a,f],l=[`${i}_${h.join("_").toUpperCase()}`,`${i}_${h.map((S)=>S.toUpperCase()).join("")}`,`${i}_${h.map((S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,C;for(let S of l)if(y=Gt.env[S],y!==void 0){C=S;break}if(y!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let S=Number(y);if(!Number.isNaN(S))c[f]=S}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((S)=>S.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,h)}return c}return s(t)}function $h(e){let t=Xe(Gt.cwd(),e.configDir),r=Xe(Gt.cwd(),e.generatedDir),n=Xe(r,"config-types.ts");if(!Un(Zo(n)))au(Zo(n),{recursive:!0,mode:511});let i=Un(t)?lu(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${Jh}
|
|
64
|
+
`;return r}}function Yu(e,t){let r=Ha("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function _a(e,t,r={}){return Va(e,t,r,new WeakMap)}function Va(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let a=s(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Ua(e,t,i,n);if(!at(t)||!at(e))return t;return eh(e,t,r,n)}function Ua(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Zu(e,t);case"smart":return Xu(e,t,n);default:return t}return t}function Zu(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Jn(i,n)))r.push(n);return r}function Xu(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(at(t[0])&&at(e[0]))return Qu(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Qu(e,t,r){let n=[...t];for(let i of e){if(!at(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in i){if(n.find((c)=>at(c)&&(a in c)&&c[a]===i[a])){s=!0;break}}if(!s)n.push(i)}return n}function eh(e,t,r,n){let i=t;if(at(i)&&n.has(i))return n.get(i);let o={...e};if(at(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let a=i[s],c=o[s];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(at(a)&&at(c))o[s]=Va(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))o[s]=Ua(c,a,r.arrayMergeMode||"smart",n);else o[s]=a}return o}function co(e,t,r="replace"){return _a(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Jn(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(!Jn(e[r],t[r]))return!1;return!0}if(at(e)&&at(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Jn(e[i],t[i]))return!1}return!0}return!1}function at(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Mi{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1}=r;if(i){let f=lr.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ii(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),h=u.default||u,l="default"in u,y=Object.keys(u).length>0;if(!l&&!y)throw new $r(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new $r(e,Error("Configuration must export a valid object"),"unknown");let C={config:co(t,h,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)lr.setWithFileCheck("file",C,e,o);return C}catch(f){throw f instanceof Error?Mt.configLoad(e,f):Mt.configLoad(e,Error(String(f)))}};if(s)return xr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let o of n)for(let s of this.extensions)i.push(Fn(t,`${o}${s}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Ga(async()=>ii(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ii(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let a=Fn(e,`${o}${s}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=Fn(e,s);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!ii(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class fo{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],h=[],l={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,l);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],l);else return this.validateWithJSONSchema(e,t,l)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:h}}};if(a)return await xr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!mu(t))throw new Ar(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Ar(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(s)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${s}`,expected:a.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let a=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let a of t.required)if(!(a in s)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in s){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],c,f,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}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 uo{fileLoader=new Mi;envProcessor=new ki;validator=new fo;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(s,!0,r)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.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"),h=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),l=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(l||u))throw c;if(h&&(!f||!l))a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||o)await this.validateConfiguration(a.config,i,o,s.name);if(r?.enabled&&a)this.cacheResult(s.name||"",a,r,s);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)ut.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);a.metrics=c}return a}catch(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:n="",alias:i,cwd:o,configDir:s,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,h=o||Bt.cwd(),l=[],y=await this.loadLocalConfiguration(n,i,h,s,a,f,u,c,r);if(y)return l.push(...this.getLocalSearchPaths(n,i,h,s)),this.finalizeResult(y,l,c,n,u);let C=await this.loadHomeConfiguration(n,i,a,f,u,c);if(C)return l.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(C,l,c,n,u);let S=await this.loadPackageJsonConfiguration(n,i,h,a,f,u,c);if(S)return l.push(Ze(h,"package.json")),this.finalizeResult(S,l,c,n,u);if(l.push(...this.getAllSearchPaths(n,i,h,s)),t)throw Mt.configNotFound(n,l,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,a,c){let f=a?Er(e,i,s):i,u=this.getLocalDirectories(r,n);for(let h of u){if(s)ut.info(`Searching for configuration in: ${h}`);let l=this.fileLoader.generateConfigPaths(e,h,t),y=await this.fileLoader.tryLoadFromPaths(l,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(s)ut.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?Er(e,r,i):r,a=[Ze(Xt(),".config",e),Ze(Xt(),".config"),Xt()];for(let c of a){if(i)ut.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:n,verbose:i});if(u){if(i)ut.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let a=s?Er(e,n,o):n;try{let c=Ze(r,"package.json");if(!Hn(c))return null;let f=await import(c),u=f[e],h=e;if(!u&&t)u=f[t],h=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)ut.success(`Configuration loaded from package.json: ${h}`);return{config:co(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)ut.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Er(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw Mt.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return lr.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);lr.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ze(e,"config"),Ze(e,".config"),t?Ze(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(Ze(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ze(Xt(),".config",e),Ze(Xt(),".config"),Xt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function va(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 th(e){return $t.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 n;if(r)n=await $t.loadConfig(e);else n=await $t.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)ut.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let s=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await $t.applyEnvironmentVariables(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function rh(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await $t.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"&&va(r)))return(await $t.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await $t.loadConfig({...e,cwd:e.cwd||Bt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&va(t)))return(await $t.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function ih(e,t,r="replace"){let n=new Mi;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Er(e,t,r=!1){let n=new ki,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let h=[...a,f],l=[`${i}_${h.join("_").toUpperCase()}`,`${i}_${h.map((S)=>S.toUpperCase()).join("")}`,`${i}_${h.map((S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,C;for(let S of l)if(y=Bt.env[S],y!==void 0){C=S;break}if(y!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let S=Number(y);if(!Number.isNaN(S))c[f]=S}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((S)=>S.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,h)}return c}return o(t)}function nh(e){let t=Ze(Bt.cwd(),e.configDir),r=Ze(Bt.cwd(),e.generatedDir),n=Ze(r,"config-types.ts");if(!Hn(Zs(n)))Kf(Zs(n),{recursive:!0,mode:511});let i=Hn(t)?Hf(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${Dh}
|
|
90
65
|
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
91
|
-
`;
|
|
92
|
-
${i.map((c)=>{let f=
|
|
66
|
+
`;zf(n,o,{mode:438})}function oh(e){let t=null,r=null,n=()=>{if(!r)r=Ka(e).then((o)=>(t=o,o),(o)=>{let s="defaultConfig"in e?e.defaultConfig:{};if(t=s,"verbose"in e&&e.verbose)ut.warn("Config loading failed, using defaults:",[o instanceof Error?o:Error(String(o))]);return s});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(o,s){if(t)return t[s];let a=i[s];return n(),a},has(o,s){return s in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(o,s){return Object.getOwnPropertyDescriptor(t||i,s)},set(o,s,a){if(!t)t={...i};return t[s]=a,!0}})}function sh(e){let t=ha(yu.cwd(),e?.configDir||"./config");function r(){if(!pu(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),o=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=gu(t).filter((c)=>i.has(Nn(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 s){let u=Nn(f).toLowerCase(),h=a.get(c);if(!h){a.set(c,f);continue}let l=Nn(h).toLowerCase();if(o.indexOf(u)<o.indexOf(l))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 n(){let i=r(),o=i.map((c)=>c.base),s=o.length?o.map((c)=>`'${c}'`).join(" | "):"string",a=i.length?`{
|
|
67
|
+
${i.map((c)=>{let f=ha(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
|
|
93
68
|
`)}
|
|
94
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
69
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
95
70
|
export type ConfigByName = ${a}
|
|
96
71
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
97
72
|
export type ConfigOf = Config
|
|
98
|
-
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function zh(e,t={}){let r=gi.cwd();while(r.includes("storage"))r=ca(r,"..");let n=ca(r,e||"");if(t?.relative)return Fu(gi.cwd(),n);return n}function Le(){if(St.env.NODE_ENV==="test"||St.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Qh(){if(St.env.NODE_ENV==="test"||St.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof St<"u"){let e=St.type;if(e==="renderer"||e==="worker")return!1;return!!(St.versions&&(St.versions.node||St.versions.bun))}return!1}class za{async format(e){let t=await Qh(),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:lr.pid,hostname:t(),environment:lr.env.NODE_ENV||"development",platform:lr.platform,version:lr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:lr.env.NODE_ENV||lr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Pi{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={...Si},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new za,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??ye.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{..._n,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{..._n};return{..._n,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Si.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Le()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await Bu(this.config.logDirectory,da.F_OK|da.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await _u(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:$t.from(e);try{if(!ti(this.currentLogFile))await Fn(this.currentLogFile,"",{mode:420});if(n=ha(this.currentLogFile,"a",420),Gu(n,a,{flag:"a"}),ua(n),n!==void 0)In(n),n=void 0;if((await or(this.currentLogFile)).size===0){if(await Fn(this.currentLogFile,a,{flag:"w",mode:420}),(await or(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(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let h=o*2**i;await new Promise((l)=>setTimeout(l,h)),i++;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(n!==void 0)try{In(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===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}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 ar(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 ar(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ar(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Le())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((n)=>{console.error("Error rotating keys:",n)})},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 n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return Dn(16).toString("hex")}generateKey(){return Dn(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=Dn(16),n=Nu("aes-256-gcm",t,r),i=$t.isBuffer(e)?e:$t.from(e,"utf8"),s=n.update(i),o=n.final(),a=s.length+o.length,c=n.getAuthTag(),f=$t.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 n=ma(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t($t.from($t.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Le())return;if(!this.shouldWriteToFile())return;let e=await or(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ri(this.config.logDirectory),s=i.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 or(r).catch(()=>null))try{if(await pa(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await ii(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.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 i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await or(r).catch(()=>null))await pa(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await ri(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await ii(ar(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=fa(e),n=Lu(t),i=ma();await Hu(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ti(this.currentLogFile))try{let e=ha(this.currentLogFile,"r+");ua(e),In(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(!Le()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ri(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await ii(ar(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()?de.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Le())return!1;let e=typeof ye.env.NO_COLOR<"u",t=ye.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ye.stderr<"u"&&ye.stderr.isTTY||typeof ye.stdout<"u"&&ye.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(o)y.push(t);if(s==="warning")y.push("WARN");else if(s==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let c=ye.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${de.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,h=a(t).length,l=Math.max(1,c-2-u-h);return`${f.trim()}${" ".repeat(l)}${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,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];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(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=de.underline(de.blue(n)),o=this.toAbsoluteFilePath(i);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;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>de.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>de.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>de.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>de.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>de.strikethrough(n)),t}supportsHyperlinks(){if(Le())return!1;let e=ye.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=ye.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Uu(t)||t.startsWith("./")||t.startsWith("../"))t=Vu(t);else return null;return ti(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,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 h=this.options.showIcons===!1?"":nd[e],l=this.options.showTags!==!1&&this.name?de.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:de.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:de.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.error(y),a){let C=a.split(`
|
|
99
|
-
`);for(let S of C)if(S.trim()&&!S.includes(
|
|
73
|
+
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function Fh(e,t={}){let r=wi.cwd();while(r.includes("storage"))r=da(r,"..");let n=da(r,e||"");if(t?.relative)return wu(wi.cwd(),n);return n}function We(){if(St.env.NODE_ENV==="test"||St.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Lh(){if(St.env.NODE_ENV==="test"||St.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof St<"u"){let e=St.type;if(e==="renderer"||e==="worker")return!1;return!!(St.versions&&(St.versions.node||St.versions.bun))}return!1}class tl{async format(e){let t=await Lh(),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:ar.pid,hostname:t(),environment:ar.env.NODE_ENV||"development",platform:ar.platform,version:ar.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ar.env.NODE_ENV||ar.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={...Ti},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new tl,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??ye.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,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{...Kn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Kn};return{...Kn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ti.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!We()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,o=3,s=1000;while(i<o)try{try{try{await $u(this.config.logDirectory,ya.F_OK|ya.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:wt.from(e);try{if(!ni(this.currentLogFile))await Bn(this.currentLogFile,"",{mode:420});if(n=ga(this.currentLogFile,"a",420),Su(n,a,{flag:"a"}),pa(n),n!==void 0)Wn(n),n=void 0;if((await or(this.currentLogFile)).size===0){if(await Bn(this.currentLogFile,a,{flag:"w",mode:420}),(await or(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(i<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let h=s*2**i;await new Promise((l)=>setTimeout(l,h)),i++;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(n!==void 0)try{Wn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 sr(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 sr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return sr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(We())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((n)=>{console.error("Error rotating keys:",n)})},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 n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Ln(16).toString("hex")}generateKey(){return Ln(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=Ln(16),n=vu("aes-256-gcm",t,r),i=wt.isBuffer(e)?e:wt.from(e,"utf8"),o=n.update(i),s=n.final(),a=o.length+s.length,c=n.getAuthTag(),f=wt.allocUnsafe(16+a+16);return r.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=wa(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(wt.from(wt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(We())return;if(!this.shouldWriteToFile())return;let e=await or(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await oi(this.config.logDirectory),o=i.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}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await or(r).catch(()=>null))try{if(await Ca(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await si(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Bn(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 i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await or(r).catch(()=>null))await Ca(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await oi(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await si(sr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=ma(e),n=Eu(t),i=wa();await Ou(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ni(this.currentLogFile))try{let e=ga(this.currentLogFile,"r+");pa(e),Wn(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(!We()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await oi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await si(sr(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()?de.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||We())return!1;let e=typeof ye.env.NO_COLOR<"u",t=ye.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ye.stderr<"u"&&ye.stderr.isTTY||typeof ye.stdout<"u"&&ye.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,a=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(t);if(o==="warning")y.push("WARN");else if(o==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let c=ye.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${de.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,h=a(t).length,l=Math.max(1,c-2-u-h);return`${f.trim()}${" ".repeat(l)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){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 o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=de.underline(de.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>de.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>de.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>de.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>de.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>de.strikethrough(n)),t}supportsHyperlinks(){if(We())return!1;let e=ye.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=ye.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(xu(t)||t.startsWith("./")||t.startsWith("../"))t=Tu(t);else return null;return ni(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":_h[e],l=this.options.showTags!==!1&&this.name?de.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:de.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:de.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.error(y),a){let C=a.split(`
|
|
74
|
+
`);for(let S of C)if(S.trim()&&!S.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:de.gray(` ${S}`),level:e,showTimestamp:!1}))}break}}else if(!We()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
100
75
|
`;if(a)u+=`${a}
|
|
101
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,
|
|
102
|
-
`);if(this[
|
|
103
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?de.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":de.green("\u2713"),tag:f,message:`${
|
|
104
|
-
`),c=Math.max(...a.map((l)=>l.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,h=a.map((l)=>this.formatConsoleMessage({timestamp:r,message:de.cyan(l),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:de.cyan(f),showTimestamp:!1})),h.forEach((l)=>console.error(l)),console.error(this.formatConsoleMessage({timestamp:r,message:de.cyan(u),showTimestamp:!1}))}else if(!
|
|
105
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
106
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
107
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
76
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,o)=>{},finish:(i)=>{},interrupt:(i,o)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!We()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!We()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,o="info")=>{if(!We()&&ye.stdout.isTTY)ye.stdout.write(`
|
|
77
|
+
`);if(this[o==="warning"?"warn":o](i),this.activeProgressBar&&this.shouldStyleConsole()&&!We()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?de.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":de.blue("\u25D0"),tag:r,message:`${de.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
78
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?de.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":de.green("\u2713"),tag:f,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!We())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(We())throw Error("createReadStream is not supported in browser environments");if(!ni(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ma(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=wt.isBuffer(e)?e:wt.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),a=bu("aes-256-gcm",r,i);a.setAuthTag(o);let c=a.update(s),f=a.final(),u=c.length+f.length,h=wt.allocUnsafe(u);return c.copy(h,0),f.copy(h,c.length),h.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return We()}isServerMode(){return!We()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=i.split(`
|
|
79
|
+
`),c=Math.max(...a.map((l)=>l.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,h=a.map((l)=>this.formatConsoleMessage({timestamp:r,message:de.cyan(l),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:de.cyan(f),showTimestamp:!1})),h.forEach((l)=>console.error(l)),console.error(this.formatConsoleMessage({timestamp:r,message:de.cyan(u),showTimestamp:!1}))}else if(!We())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
|
|
80
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(We())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${de.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();ye.stdin.removeListener("data",r);try{if(typeof ye.stdin.setRawMode==="function")ye.stdin.setRawMode(!1)}catch{}ye.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof ye.stdin.setRawMode==="function")ye.stdin.setRawMode(!0)}catch{}ye.stdin.resume(),ye.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 s=/%([sdijfo%])/g,a=0;if(r=e.replace(s,(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:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?de.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${de.blue("\u25D0")} `;console.error(`${a}${s} ${de.cyan(n)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
81
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ye.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=de.green("\u2501".repeat(n)),s=de.gray("\u2501".repeat(i)),a=`[${o}${s}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?de.green("\u2713"):de.blue("\u25B6"),h=this.options.showTags!==!1&&this.name?` ${de.gray(this.formatTag(this.name))}`:"",l=`\r${u}${h} ${a} ${c}${f}`,y=ye.stdout.columns||80,C=" ".repeat(Math.max(0,y-l.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${l}${C}`,ye.stdout.write(e.lastRenderedLine),t)ye.stdout.write(`
|
|
82
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||We()||!ye.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(We()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await oi(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=sr(this.config.logDirectory,n);if(e.before)try{if((await or(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await si(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Vh(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(s=c instanceof Error?c:Error(String(c)),a===r||!i(s))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class mo{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:a=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),h={...t};return this.processObject(h,[],u,{useCamelCase:i,useBackwardCompatibility:o,customParsers:s,verbose:a,configName:e}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return no.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,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],a=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${a.join("_")}`,f=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,r,n);else{let u=ai.env[c]||(f?ai.env[f]:void 0);if(u!==void 0){if(n.verbose){let h=ai.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof o,c,n.customParsers,n.configName)}catch(h){if(h instanceof ho)throw h;throw cr.envVar(c,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw cr.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(ai.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],a=`${r}_${s.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,r,n);else n.push({key:a,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}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}:
|
|
108
83
|
|
|
109
84
|
`;for(let n of e)r+=`${n.key}
|
|
110
85
|
`,r+=` Type: ${n.type}
|
|
@@ -116,70 +91,138 @@ export type ConfigOf = Config
|
|
|
116
91
|
`;r+=`| Variable | Type | Description | Example |
|
|
117
92
|
`,r+=`|----------|------|-------------|----------|
|
|
118
93
|
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
119
|
-
`;return r}}function od(e,t,r={}){return sl(e,t,r,new WeakMap)}function sl(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return ol(e,t,i,n);if(!ct(t)||!ct(e))return t;return fd(e,t,r,n)}function ol(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return ad(e,t);case"smart":return ld(e,t,n);default:return t}return t}function ad(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Qn(i,n)))r.push(n);return r}function ld(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(ct(t[0])&&ct(e[0]))return cd(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function cd(e,t,r){let n=[...t];for(let i of e){if(!ct(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in i){if(n.find((c)=>ct(c)&&(a in c)&&c[a]===i[a])){o=!0;break}}if(!o)n.push(i)}return n}function fd(e,t,r,n){let i=t;if(ct(i)&&n.has(i))return n.get(i);let s={...e};if(ct(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let a=i[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(ct(a)&&ct(c))s[o]=sl(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))s[o]=ol(c,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function al(e,t,r="replace"){return od(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Qn(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(!Qn(e[r],t[r]))return!1;return!0}if(ct(e)&&ct(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Qn(e[i],t[i]))return!1}return!0}return!1}function ct(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ll{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(i){let f=yi.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!si(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),h=u.default||u,l="default"in u,y=Object.keys(u).length>0;if(!l&&!y)throw new Ai(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new Ai(e,Error("Configuration must export a valid object"),"unknown");let C={config:al(t,h,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)yi.setWithFileCheck("file",C,e,s);return C}catch(f){throw f instanceof Error?fr.configLoad(e,f):fr.configLoad(e,Error(String(f)))}};if(o)return es.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(Nn(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of n){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let i=new Set;return r.filter((s)=>{if(!s||i.has(s))return!1;return i.add(s),!0})}checkFileAccess(e){return sd(async()=>si(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!si(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let a=Nn(e,`${s}${o}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=Nn(e,o);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!si(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class cl{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],h=[],l={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,l);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],l);else return this.validateWithJSONSchema(e,t,l)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:h}}};if(a)return await es.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Ku(t))throw new xi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new xi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(n.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(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(n.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,n,i,s),s.stopOnFirstError&&n.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))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ud},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function hd(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 fl{fileLoader=new ll;envProcessor=new cs;validator=new cl;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,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"),h=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),l=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(l||u))throw c;if(h&&(!f||!l))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(i||s)await this.validateConfiguration(a.config,i,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)vt.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 vt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,h=s||Ti.cwd(),l=[],y=await this.loadLocalConfiguration(n,i,h,o,a,f,u,c,r);if(y)return l.push(...this.getLocalSearchPaths(n,i,h,o)),this.finalizeResult(y,l,c,n,u);let C=await this.loadHomeConfiguration(n,i,a,f,u,c);if(C)return l.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(C,l,c,n,u);let S=await this.loadPackageJsonConfiguration(n,i,h,a,f,u,c);if(S)return l.push(at(h,"package.json")),this.finalizeResult(S,l,c,n,u);if(l.push(...this.getAllSearchPaths(n,i,h,o)),t)throw fr.configNotFound(n,l,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${hd(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,a,c){let f=a?ai(e,i,o):i,u=this.getLocalDirectories(r,n);for(let h of u){if(o)vt.info(`Searching for configuration in: ${h}`);let l=this.fileLoader.generateConfigPaths(e,h,t),y=await this.fileLoader.tryLoadFromPaths(l,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(o)vt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?ai(e,r,i):r,a=[at(Xt(),".config",e),at(Xt(),".config"),Xt()];for(let c of a){if(i)vt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,o,{arrayStrategy:n,verbose:i});if(u){if(i)vt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let a=o?ai(e,n,s):n;try{let c=at(r,"package.json");if(!su(c))return null;let f={};try{f=JSON.parse(ou(c,"utf8"))}catch(l){if(s)vt.warn("Failed to parse package.json:",[l instanceof Error?l:Error(String(l))]);return null}let u=f[e],h=e;if(!u&&t){let l=Array.isArray(t)?t:[t];for(let y of l){if(!y)continue;if(f[y]){u=f[y],h=y;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)vt.success(`Configuration loaded from package.json: ${h}`);return{config:al(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)vt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ai(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw fr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return yi.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);yi.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}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,at(e,"config"),at(e,".config"),t?at(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(at(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[at(Xt(),".config",e),at(Xt(),".config"),Xt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ai(e,t,r=!1){let n=new cs,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let h=[...a,f],l=[`${i}_${h.join("_").toUpperCase()}`,`${i}_${h.map((S)=>S.toUpperCase()).join("")}`,`${i}_${h.map((S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,C;for(let S of l)if(y=Ti.env[S],y!==void 0){C=S;break}if(y!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let S=Number(y);if(!Number.isNaN(S))c[f]=S}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((S)=>S.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,h)}return c}return s(t)}var yi,es,ju,Zu=(e)=>e,Ju=(e,t)=>{for(var r in t)ju(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Yu.bind(t,r)})},qu=(e,t)=>()=>(e&&(t=e(e=0)),t),Da,Ua,cr,Sr,Va,Eh,Sh,ya,ci,Kn,Ze,be,Ah,Ca,xh,wa,Th,Oh,Wn,Rh,$a,va,Ln,Ph,kh,Mh,Dh,fi,Ha,Ih,Ye,Fh,Nh,ba,ui,jn,We,ce,Wh,Ea,Lh,Sa,Gh,Bh,Gn,_h,Aa,xa,Uh,Bn,Vh,Hh,Kh,jh,Zh,hi,Ka,Yh,Jh="0.15.6",rt,bi,br,Zn,Yn,Ei,Jn,qn,Er,zn,Xn,It,ja,Za,ht,At,Ya,Ja,qh,Xh,qa,Si,Fy,_e,de,Ny,ed,Wy,td,Ly,Gy,Ta,By,rd,id,_y,Oa,Uy,Vy,Hy,Ky,jy,_n,nd,Zy,dt,Xa,Ai,Qa,el,ls,tl,rl,xi,il,nl,fr,ud,vt,Yy,Jy,qy,dd,ul;var hl=he(()=>{yi=new ka,es=new Ma,ju=Object.defineProperty;Da={};Ju(Da,{withErrorRecovery:()=>Na,tryLoadConfig:()=>wh,loadConfigWithResult:()=>yh,loadConfig:()=>_a,isRetryableError:()=>uh,isConfigNotFoundError:()=>fh,isBunfigError:()=>Wa,globalPerformanceMonitor:()=>Sr,globalCache:()=>cr,getEnvOrDefault:()=>hh,generateConfigTypes:()=>$h,defaultGeneratedDir:()=>Ja,defaultConfigDir:()=>Ya,deepMergeWithArrayStrategy:()=>ss,deepMerge:()=>La,createLibraryConfig:()=>vh,config:()=>Ch,bunfigPlugin:()=>bh,applyEnvVarsToConfig:()=>$r,TypeGenerationError:()=>qn,SchemaValidationError:()=>Er,PluginError:()=>Xn,PerformanceMonitor:()=>rs,FileSystemError:()=>Jn,ErrorFactory:()=>It,EnvVarError:()=>Ei,EnvProcessor:()=>Oi,ConfigValidator:()=>os,ConfigValidationError:()=>Zn,ConfigNotFoundError:()=>bi,ConfigMergeError:()=>Yn,ConfigLoader:()=>as,ConfigLoadError:()=>br,ConfigFileLoader:()=>Ri,ConfigCache:()=>ts,CacheUtils:()=>Va,BunfigError:()=>rt,BrowserConfigError:()=>zn,ArrayMergeStrategies:()=>ja});qh=qu(async()=>{Ua=import.meta.require,cr=new ts,Sr=new rs,Va={createKey:zu,isEquivalent:Xu,estimateMemoryUsage:Qu},Eh=mi(Vn.cwd(),"config"),Sh=mi(Vn.cwd(),"src/generated"),ya=pi.env.CLARITY_LOG_DIR||hu(rh(),"logs"),ci={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ya,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Kn=await ih(),Ze={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"},be=Ze,Ah=Ze.red,Ca=Ze.green,xh=Ze.yellow,wa=Ze.blue,Th=Ze.magenta,Oh=Ze.cyan,Wn=Ze.white,Rh=Ze.gray,$a=Ze.bgRed,va=Ze.bgYellow,Ln=Ze.bold,Ph=Ze.dim,kh=Ze.italic,Mh=Ze.underline,Dh=Ze.reset,fi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ha={debug:"\uD83D\uDD0D",info:wa("\u2139"),success:Ca("\u2713"),warning:va(Wn(Ln(" WARN "))),error:$a(Wn(Ln(" ERROR ")))},Ih=new wi("stacks"),Ye=new wi("bunfig",{showTags:!0}),Fh=ze(vr.cwd(),"config"),Nh=ze(vr.cwd(),"src/generated"),ba=di.env.CLARITY_LOG_DIR||fu(ah(),"logs"),ui={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,writeToFile:!1},jn=await lh(),We={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"},ce=We,Wh=We.red,Ea=We.green,Lh=We.yellow,Sa=We.blue,Gh=We.magenta,Bh=We.cyan,Gn=We.white,_h=We.gray,Aa=We.bgRed,xa=We.bgYellow,Uh=We.bgGray,Bn=We.bold,Vh=We.dim,Hh=We.italic,Kh=We.underline,jh=We.strikethrough,Zh=We.reset,hi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ka={debug:"\uD83D\uDD0D",info:Sa("\u2139"),success:Ea("\u2713"),warning:xa(Gn(Bn(" WARN "))),error:Aa(Gn(Bn(" ERROR ")))},Yh=new vi("stacks"),rt=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}`}},bi=class extends rt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},br=class extends rt{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}},Zn=class extends rt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Yn=class extends rt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Ei=class extends rt{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}},Jn=class extends rt{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}},qn=class extends rt{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}},Er=class extends rt{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})}},zn=class extends rt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}},Xn=class extends rt{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}},It={configNotFound(e,t,r){return new bi(e,t,r)},configLoad(e,t,r){return new br(e,t,r)},configValidation(e,t,r){return new Zn(e,t,r)},configMerge(e,t,r,n){return new Yn(e,t,r,n)},envVar(e,t,r,n){return new Ei(e,t,r,n)},fileSystem(e,t,r){return new Jn(e,t,r)},typeGeneration(e,t,r){return new qn(e,t,r)},schemaValidation(e,t,r){return new Er(e,t,r)},browserConfig(e,t,r,n){return new zn(e,t,r,n)},plugin(e,t,r){return new Xn(e,t,r)}},ja={replace:"replace",concat:"concat",smart:"smart"},Za=/^https?:\/\//,ht=new vi("bunfig",{showTags:!0}),At=new as,Ya=Xe(Gt.cwd(),"config"),Ja=Xe(Gt.cwd(),"src/generated")});Xh=gi.env.CLARITY_LOG_DIR||Iu(zh(),"logs"),qa={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Xh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Si={...qa},Fy=(async()=>{try{let{loadConfig:e}=await qh().then(()=>Da),t=await e({name:"clarity",alias:"logging",defaultConfig:qa,cwd:gi.cwd()});if(t)Object.assign(Si,t)}catch{}return Si})();_e={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"},de=_e,Ny=_e.red,ed=_e.green,Wy=_e.yellow,td=_e.blue,Ly=_e.magenta,Gy=_e.cyan,Ta=_e.white,By=_e.gray,rd=_e.bgRed,id=_e.bgYellow,_y=_e.bgGray,Oa=_e.bold,Uy=_e.dim,Vy=_e.italic,Hy=_e.underline,Ky=_e.strikethrough,jy=_e.reset,_n={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nd={debug:"\uD83D\uDD0D",info:td("\u2139"),success:ed("\u2713"),warning:id(Ta(Oa(" WARN "))),error:rd(Ta(Oa(" ERROR ")))};Zy=new Pi("stacks");dt=class dt 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}`}};Xa=class Xa extends dt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};Ai=class Ai extends dt{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}};Qa=class Qa extends dt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};el=class el extends dt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};ls=class ls extends dt{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};tl=class tl extends dt{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}};rl=class rl extends dt{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}};xi=class xi extends dt{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})}};il=class il extends dt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};nl=class nl extends dt{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}};fr={configNotFound(e,t,r){return new Xa(e,t,r)},configLoad(e,t,r){return new Ai(e,t,r)},configValidation(e,t,r){return new Qa(e,t,r)},configMerge(e,t,r,n){return new el(e,t,r,n)},envVar(e,t,r,n){return new ls(e,t,r,n)},fileSystem(e,t,r){return new tl(e,t,r)},typeGeneration(e,t,r){return new rl(e,t,r)},schemaValidation(e,t,r){return new xi(e,t,r)},browserConfig(e,t,r,n){return new il(e,t,r,n)},plugin(e,t,r){return new nl(e,t,r)}};ud=/^https?:\/\//;vt=new Pi("bunfig",{showTags:!0});Yy=new fl;Jy=at(Ti.cwd(),"config"),qy=at(Ti.cwd(),"src/generated"),dd={cwd:nu.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},ul=dd});function Ft(e,t){let r=1,n=1;for(let i=0;i<t;i++)if(e.charCodeAt(i)===10)r++,n=1;else n++;return{line:r,column:n}}function pl(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},s=0,o=0,a=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),h=e.charCodeAt(f+1);if(a!==-1){if(u===42&&h===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&&h===42){a=f,f++;continue}if(u===47&&h===47){let y=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:y,end:f});continue}if(u===39||u===34||u===96){s=u,o=f;continue}let l=e[f];if(l==="("||l==="["||l==="{")n.push({char:l,offset:f});else if(i[l]){let y=n.pop();if(!y||y.char!==i[l])t.push({...Ft(e,f),message:`Unexpected closing delimiter ${l}`,code:"DTSX1004"})}}if(s)t.push({...Ft(e,o),message:"Unterminated string literal",code:"DTSX1002"});if(a!==-1)t.push({...Ft(e,a),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...Ft(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 h of e.matchAll(f)){if(r.some((l)=>h.index>=l.start&&h.index<l.end))continue;t.push({...Ft(e,h.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((h)=>f.index>=h.start&&f.index<h.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...Ft(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...md(e,r)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function md(e,t){let r=[],n=(i)=>t.some((s)=>i>=s.start&&i<s.end);for(let i of e.matchAll(/\b(import|export)\s+(?:type\s+)?\{/g)){let s=i.index;if(n(s))continue;let o=s+i[0].length-1,a=-1;for(let u=o+1;u<e.length;u++){if(n(u))continue;let h=e[u];if(h==="{"){a=-2;break}if(h==="}"){a=u;break}}if(a<0)continue;let c=e.slice(o+1,a);if(!c.trim())continue;let f=o+1;for(let u of c.split(",")){let h=u.trim();if(h){let l=f+u.indexOf(h);if(h.includes(";"))r.push({...Ft(e,l),message:`Unexpected ';' in ${i[1]} clause \u2014 specifiers are separated by ','`,code:"DTSX1006"});else if(!pd.test(h))r.push({...Ft(e,l),message:`Invalid ${i[1]} specifier '${h}'`,code:"DTSX1006"})}f+=u.length+1}}return r}var dl,pd;var ml=he(()=>{dl=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,pd=new RegExp(`^(?:type\\s+)?${dl}(?:\\s+as\\s+${dl})?$`,"u")});var gl;var yl=he(()=>{gl=new Set(["ANGLE_instanced_arrays","ARIAMixin","AacBitstreamFormat","AacEncoderConfig","AbortController","AbortSignal","AbortSignalEventMap","AbstractRange","AbstractWorker","AbstractWorkerEventMap","ActiveXObject","AddEventListenerOptions","AddressErrors","AddressType","AddressValue","AesCbcParams","AesCtrParams","AesDerivedKeyParams","AesGcmParams","AesKeyAlgorithm","AesKeyGenParams","AggregateError","AggregateErrorConstructor","Algorithm","AlgorithmIdentifier","AlignSetting","AllAcceptedCredentialsOptions","AllowSharedBufferSource","AlphaOption","AnalyserNode","AnalyserOptions","Animatable","Animation","AnimationEffect","AnimationEvent","AnimationEventInit","AnimationEventMap","AnimationFrameProvider","AnimationPlayState","AnimationPlaybackEvent","AnimationPlaybackEventInit","AnimationReplaceState","AnimationTimeline","AppendMode","Array","ArrayBuffer","ArrayBufferConstructor","ArrayBufferLike","ArrayBufferTypes","ArrayBufferView","ArrayConstructor","ArrayIterator","ArrayLike","AssignedNodesOptions","AsyncDisposable","AsyncDisposableStack","AsyncDisposableStackConstructor","AsyncGenerator","AsyncGeneratorFunction","AsyncGeneratorFunctionConstructor","AsyncIterable","AsyncIterableIterator","AsyncIterator","AsyncIteratorObject","Atomics","AttestationConveyancePreference","Attr","Audio","AudioBuffer","AudioBufferOptions","AudioBufferSourceNode","AudioBufferSourceOptions","AudioConfiguration","AudioContext","AudioContextLatencyCategory","AudioContextOptions","AudioContextState","AudioData","AudioDataCopyToOptions","AudioDataInit","AudioDataOutputCallback","AudioDecoder","AudioDecoderConfig","AudioDecoderEventMap","AudioDecoderInit","AudioDecoderSupport","AudioDestinationNode","AudioEncoder","AudioEncoderConfig","AudioEncoderEventMap","AudioEncoderInit","AudioEncoderSupport","AudioListener","AudioNode","AudioNodeOptions","AudioParam","AudioParamMap","AudioProcessingEvent","AudioProcessingEventInit","AudioSampleFormat","AudioScheduledSourceNode","AudioScheduledSourceNodeEventMap","AudioTimestamp","AudioWorklet","AudioWorkletNode","AudioWorkletNodeEventMap","AudioWorkletNodeOptions","AuthenticationExtensionsClientInputs","AuthenticationExtensionsClientInputsJSON","AuthenticationExtensionsClientOutputs","AuthenticationExtensionsClientOutputsJSON","AuthenticationExtensionsLargeBlobInputs","AuthenticationExtensionsLargeBlobInputsJSON","AuthenticationExtensionsLargeBlobOutputs","AuthenticationExtensionsLargeBlobOutputsJSON","AuthenticationExtensionsPRFInputs","AuthenticationExtensionsPRFInputsJSON","AuthenticationExtensionsPRFOutputs","AuthenticationExtensionsPRFOutputsJSON","AuthenticationExtensionsPRFValues","AuthenticationExtensionsPRFValuesJSON","AuthenticationResponseJSON","AuthenticatorAssertionResponse","AuthenticatorAssertionResponseJSON","AuthenticatorAttachment","AuthenticatorAttestationResponse","AuthenticatorAttestationResponseJSON","AuthenticatorResponse","AuthenticatorSelectionCriteria","AuthenticatorTransport","AutoFill","AutoFillAddressKind","AutoFillBase","AutoFillContactField","AutoFillContactKind","AutoFillCredentialField","AutoFillField","AutoFillNormalField","AutoFillSection","AutoKeyword","AutomationRate","AvcBitstreamFormat","AvcEncoderConfig","Awaited","BarProp","Base64URLString","BaseAudioContext","BaseAudioContextEventMap","BeforeUnloadEvent","BigInt","BigInt64Array","BigInt64ArrayConstructor","BigIntConstructor","BigIntToLocaleStringOptions","BigInteger","BigUint64Array","BigUint64ArrayConstructor","BinaryType","BiquadFilterNode","BiquadFilterOptions","BiquadFilterType","BitrateMode","Blob","BlobCallback","BlobEvent","BlobEventInit","BlobPart","BlobPropertyBag","Body","BodyInit","Boolean","BooleanConstructor","BroadcastChannel","BroadcastChannelEventMap","Buffer","BufferEncoding","BufferSource","BuiltinIteratorReturn","Bun","BunFile","ByteLengthQueuingStrategy","CDATASection","COSEAlgorithmIdentifier","CSS","CSSAnimation","CSSConditionRule","CSSContainerRule","CSSCounterStyleRule","CSSFontFaceRule","CSSFontFeatureValuesRule","CSSFontPaletteValuesRule","CSSGroupingRule","CSSImageValue","CSSImportRule","CSSKeyframeRule","CSSKeyframesRule","CSSKeywordValue","CSSKeywordish","CSSLayerBlockRule","CSSLayerStatementRule","CSSMathClamp","CSSMathInvert","CSSMathMax","CSSMathMin","CSSMathNegate","CSSMathOperator","CSSMathProduct","CSSMathSum","CSSMathValue","CSSMatrixComponent","CSSMatrixComponentOptions","CSSMediaRule","CSSNamespaceRule","CSSNestedDeclarations","CSSNumberish","CSSNumericArray","CSSNumericBaseType","CSSNumericType","CSSNumericValue","CSSPageDescriptors","CSSPageRule","CSSPerspective","CSSPerspectiveValue","CSSPositionTryDescriptors","CSSPositionTryRule","CSSPropertyRule","CSSRotate","CSSRule","CSSRuleList","CSSScale","CSSScopeRule","CSSSkew","CSSSkewX","CSSSkewY","CSSStartingStyleRule","CSSStyleDeclaration","CSSStyleDeclarationBase","CSSStyleProperties","CSSStyleRule","CSSStyleSheet","CSSStyleSheetInit","CSSStyleValue","CSSSupportsRule","CSSTransformComponent","CSSTransformValue","CSSTransition","CSSTranslate","CSSUnitValue","CSSUnparsedSegment","CSSUnparsedValue","CSSVariableReferenceValue","CSSViewTransitionRule","Cache","CacheQueryOptions","CacheStorage","CalendarLike","CallableFunction","CanPlayTypeResult","CanvasCaptureMediaStreamTrack","CanvasCompositing","CanvasDirection","CanvasDrawImage","CanvasDrawPath","CanvasFillRule","CanvasFillStrokeStyles","CanvasFilters","CanvasFontKerning","CanvasFontStretch","CanvasFontVariantCaps","CanvasGradient","CanvasImageData","CanvasImageSmoothing","CanvasImageSource","CanvasLineCap","CanvasLineJoin","CanvasPath","CanvasPathDrawingStyles","CanvasPattern","CanvasRect","CanvasRenderingContext2D","CanvasRenderingContext2DSettings","CanvasSettings","CanvasShadowStyles","CanvasState","CanvasText","CanvasTextAlign","CanvasTextBaseline","CanvasTextDrawingStyles","CanvasTextRendering","CanvasTransform","CanvasUserInterface","Capitalize","CaretPosition","CaretPositionFromPointOptions","ChannelCountMode","ChannelInterpretation","ChannelMergerNode","ChannelMergerOptions","ChannelSplitterNode","ChannelSplitterOptions","CharacterData","CheckVisibilityOptions","ChildNode","ClassAccessorDecoratorContext","ClassAccessorDecoratorResult","ClassAccessorDecoratorTarget","ClassDecorator","ClassDecoratorContext","ClassFieldDecoratorContext","ClassGetterDecoratorContext","ClassMemberDecoratorContext","ClassMethodDecoratorContext","ClassSetterDecoratorContext","Client","ClientQueryOptions","ClientRect","ClientTypes","Clients","Clipboard","ClipboardEvent","ClipboardEventInit","ClipboardItem","ClipboardItemData","ClipboardItemOptions","ClipboardItems","CloseEvent","CloseEventInit","CodecState","Collator","CollatorConstructor","CollatorOptions","ColorGamut","ColorSpaceConversion","CommandEvent","CommandEventInit","Comment","CompileError","CompositeOperation","CompositeOperationOrAuto","CompositionEvent","CompositionEventInit","CompressionFormat","CompressionStream","ComputedEffectTiming","ComputedKeyframe","ConcatArray","Console","ConstantSourceNode","ConstantSourceOptions","ConstrainBoolean","ConstrainBooleanOrDOMString","ConstrainBooleanOrDOMStringParameters","ConstrainBooleanParameters","ConstrainDOMString","ConstrainDOMStringParameters","ConstrainDouble","ConstrainDoubleRange","ConstrainULong","ConstrainULongRange","ConstructorParameters","ContentVisibilityAutoStateChangeEvent","ContentVisibilityAutoStateChangeEventInit","ConvolverNode","ConvolverOptions","CookieChangeEvent","CookieChangeEventInit","CookieInit","CookieList","CookieListItem","CookieSameSite","CookieStore","CookieStoreDeleteOptions","CookieStoreEventMap","CookieStoreGetOptions","CookieStoreManager","CountQueuingStrategy","Credential","CredentialCreationOptions","CredentialMediationRequirement","CredentialPropertiesOutput","CredentialRequestOptions","CredentialsContainer","Crypto","CryptoKey","CryptoKeyPair","CurrentUserDetailsOptions","CustomElementConstructor","CustomElementRegistry","CustomEvent","CustomEventInit","CustomStateSet","DOMException","DOMHighResTimeStamp","DOMImplementation","DOMMatrix","DOMMatrix2DInit","DOMMatrixInit","DOMMatrixReadOnly","DOMParser","DOMParserSupportedType","DOMPoint","DOMPointInit","DOMPointReadOnly","DOMQuad","DOMQuadInit","DOMRect","DOMRectInit","DOMRectList","DOMRectReadOnly","DOMStringList","DOMStringMap","DOMTokenList","DataTransfer","DataTransferItem","DataTransferItemList","DataView","DataViewConstructor","Date","DateConstructor","DateLikeObject","DateTimeFormat","DateTimeFormatConstructor","DateTimeFormatOptions","DateTimeFormatPart","DateTimeFormatPartTypes","DateTimeFormatPartTypesRegistry","DateTimeLikeObject","DateTimeRangeFormatPart","DateUnit","DecodeErrorCallback","DecodeSuccessCallback","DecompressionStream","DecoratorContext","DecoratorMetadata","DecoratorMetadataObject","DedicatedWorkerGlobalScope","DedicatedWorkerGlobalScopeEventMap","DelayNode","DelayOptions","DeviceMotionEvent","DeviceMotionEventAcceleration","DeviceMotionEventAccelerationInit","DeviceMotionEventInit","DeviceMotionEventRotationRate","DeviceMotionEventRotationRateInit","DeviceOrientationEvent","DeviceOrientationEventInit","DigitalCredential","DirectionSetting","Dirent","DisambiguationOptions","DisplayCaptureSurfaceType","DisplayMediaStreamOptions","DisplayNames","DisplayNamesFallback","DisplayNamesLanguageDisplay","DisplayNamesOptions","DisplayNamesType","Disposable","DisposableStack","DisposableStackConstructor","DistanceModelType","Document","DocumentEventMap","DocumentFragment","DocumentOrShadowRoot","DocumentReadyState","DocumentTimeline","DocumentTimelineOptions","DocumentType","DocumentVisibilityState","DoubleRange","DragEvent","DragEventInit","Duration","DurationConstructor","DurationFormat","DurationFormatDisplayOption","DurationFormatLocaleMatcher","DurationFormatOptions","DurationFormatPart","DurationFormatStyle","DurationFormatUnit","DurationFormatUnitSingular","DurationLike","DurationLikeObject","DurationRelativeToOptions","DurationRoundingOptions","DurationToStringOptions","DurationTotalOptions","DynamicsCompressorNode","DynamicsCompressorOptions","EXT_blend_minmax","EXT_color_buffer_float","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_sRGB","EXT_shader_texture_lod","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","EXT_texture_norm16","EcKeyAlgorithm","EcKeyGenParams","EcKeyImportParams","EcdhKeyDeriveParams","EcdsaParams","EffectTiming","Element","ElementCSSInlineStyle","ElementContentEditable","ElementCreationOptions","ElementDefinitionOptions","ElementEventMap","ElementInternals","ElementTagNameMap","EncodedAudioChunk","EncodedAudioChunkInit","EncodedAudioChunkMetadata","EncodedAudioChunkOutputCallback","EncodedAudioChunkType","EncodedVideoChunk","EncodedVideoChunkInit","EncodedVideoChunkMetadata","EncodedVideoChunkOutputCallback","EncodedVideoChunkType","EndOfStreamError","EndingType","Enumerator","EnumeratorConstructor","EpochTimeStamp","Error","ErrorCallback","ErrorConstructor","ErrorEvent","ErrorEventInit","ErrorOptions","EvalError","EvalErrorConstructor","Event","EventCounts","EventInit","EventListener","EventListenerObject","EventListenerOptions","EventListenerOrEventListenerObject","EventModifierInit","EventSource","EventSourceEventMap","EventSourceInit","EventTarget","Exception","ExceptionOptions","Exclude","ExportValue","Exports","ExtendableCookieChangeEvent","ExtendableCookieChangeEventInit","ExtendableEvent","ExtendableEventInit","ExtendableMessageEvent","ExtendableMessageEventInit","External","Extract","FetchEvent","FetchEventInit","File","FileCallback","FileList","FilePropertyBag","FileReader","FileReaderEventMap","FileReaderSync","FileSink","FileSystem","FileSystemCreateWritableOptions","FileSystemDirectoryEntry","FileSystemDirectoryHandle","FileSystemDirectoryHandleAsyncIterator","FileSystemDirectoryReader","FileSystemEntriesCallback","FileSystemEntry","FileSystemEntryCallback","FileSystemFileEntry","FileSystemFileHandle","FileSystemFlags","FileSystemGetDirectoryOptions","FileSystemGetFileOptions","FileSystemHandle","FileSystemHandleKind","FileSystemReadWriteOptions","FileSystemRemoveOptions","FileSystemSyncAccessHandle","FileSystemWritableFileStream","FileSystemWriteChunkType","FillLightMode","FillMode","FinalizationRegistry","FinalizationRegistryConstructor","FlatArray","Float16Array","Float16ArrayConstructor","Float32Array","Float32ArrayConstructor","Float32List","Float64Array","Float64ArrayConstructor","FocusEvent","FocusEventInit","FocusOptions","FontDisplay","FontFace","FontFaceDescriptors","FontFaceLoadStatus","FontFaceSet","FontFaceSetEventMap","FontFaceSetLoadEvent","FontFaceSetLoadEventInit","FontFaceSetLoadStatus","FontFaceSource","FormData","FormDataEntryValue","FormDataEvent","FormDataEventInit","FormDataIterator","FormattableTemporalObject","FragmentDirective","FrameRequestCallback","FrameType","FullscreenNavigationUI","FullscreenOptions","Function","FunctionConstructor","FunctionStringCallback","GLbitfield","GLboolean","GLclampf","GLenum","GLfloat","GLint","GLint64","GLintptr","GLsizei","GLsizeiptr","GLuint","GLuint64","GPU","GPUAdapter","GPUAdapterInfo","GPUAddressMode","GPUAutoLayoutMode","GPUBindGroup","GPUBindGroupDescriptor","GPUBindGroupEntry","GPUBindGroupLayout","GPUBindGroupLayoutDescriptor","GPUBindGroupLayoutEntry","GPUBindingCommandsMixin","GPUBindingResource","GPUBlendComponent","GPUBlendFactor","GPUBlendOperation","GPUBlendState","GPUBuffer","GPUBufferBinding","GPUBufferBindingLayout","GPUBufferBindingType","GPUBufferDescriptor","GPUBufferDynamicOffset","GPUBufferMapState","GPUBufferUsageFlags","GPUCanvasAlphaMode","GPUCanvasConfiguration","GPUCanvasContext","GPUCanvasToneMapping","GPUCanvasToneMappingMode","GPUColor","GPUColorDict","GPUColorTargetState","GPUColorWriteFlags","GPUCommandBuffer","GPUCommandBufferDescriptor","GPUCommandEncoder","GPUCommandEncoderDescriptor","GPUCompareFunction","GPUCompilationInfo","GPUCompilationMessage","GPUCompilationMessageType","GPUComputePassDescriptor","GPUComputePassEncoder","GPUComputePassTimestampWrites","GPUComputePipeline","GPUComputePipelineDescriptor","GPUCopyExternalImageDestInfo","GPUCopyExternalImageSource","GPUCopyExternalImageSourceInfo","GPUCullMode","GPUDebugCommandsMixin","GPUDepthBias","GPUDepthStencilState","GPUDevice","GPUDeviceDescriptor","GPUDeviceEventMap","GPUDeviceLostInfo","GPUDeviceLostReason","GPUError","GPUErrorFilter","GPUExtent3D","GPUExtent3DDict","GPUExternalTexture","GPUExternalTextureBindingLayout","GPUExternalTextureDescriptor","GPUFeatureName","GPUFilterMode","GPUFlagsConstant","GPUFragmentState","GPUFrontFace","GPUIndex32","GPUIndexFormat","GPUIntegerCoordinate","GPUIntegerCoordinateOut","GPUInternalError","GPULoadOp","GPUMapModeFlags","GPUMipmapFilterMode","GPUMultisampleState","GPUObjectBase","GPUObjectDescriptorBase","GPUOrigin2D","GPUOrigin2DDict","GPUOrigin3D","GPUOrigin3DDict","GPUOutOfMemoryError","GPUPipelineBase","GPUPipelineConstantValue","GPUPipelineDescriptorBase","GPUPipelineError","GPUPipelineErrorInit","GPUPipelineErrorReason","GPUPipelineLayout","GPUPipelineLayoutDescriptor","GPUPowerPreference","GPUPrimitiveState","GPUPrimitiveTopology","GPUProgrammableStage","GPUQuerySet","GPUQuerySetDescriptor","GPUQueryType","GPUQueue","GPUQueueDescriptor","GPURenderBundle","GPURenderBundleDescriptor","GPURenderBundleEncoder","GPURenderBundleEncoderDescriptor","GPURenderCommandsMixin","GPURenderPassColorAttachment","GPURenderPassDepthStencilAttachment","GPURenderPassDescriptor","GPURenderPassEncoder","GPURenderPassLayout","GPURenderPassTimestampWrites","GPURenderPipeline","GPURenderPipelineDescriptor","GPURequestAdapterOptions","GPUSampleMask","GPUSampler","GPUSamplerBindingLayout","GPUSamplerBindingType","GPUSamplerDescriptor","GPUShaderModule","GPUShaderModuleDescriptor","GPUShaderStageFlags","GPUSignedOffset32","GPUSize32","GPUSize32Out","GPUSize64","GPUSize64Out","GPUStencilFaceState","GPUStencilOperation","GPUStencilValue","GPUStorageTextureAccess","GPUStorageTextureBindingLayout","GPUStoreOp","GPUSupportedFeatures","GPUSupportedLimits","GPUTexelCopyBufferInfo","GPUTexelCopyBufferLayout","GPUTexelCopyTextureInfo","GPUTexture","GPUTextureAspect","GPUTextureBindingLayout","GPUTextureDescriptor","GPUTextureDimension","GPUTextureFormat","GPUTextureSampleType","GPUTextureUsageFlags","GPUTextureView","GPUTextureViewDescriptor","GPUTextureViewDimension","GPUUncapturedErrorEvent","GPUUncapturedErrorEventInit","GPUValidationError","GPUVertexAttribute","GPUVertexBufferLayout","GPUVertexFormat","GPUVertexState","GPUVertexStepMode","GainNode","GainOptions","Gamepad","GamepadButton","GamepadEffectParameters","GamepadEvent","GamepadEventInit","GamepadHapticActuator","GamepadHapticEffectType","GamepadHapticsResult","GamepadMappingType","Generator","GeneratorFunction","GeneratorFunctionConstructor","GenericTransformStream","Geolocation","GeolocationCoordinates","GeolocationPosition","GeolocationPositionError","GetAnimationsOptions","GetComposedRangesOptions","GetHTMLOptions","GetNotificationOptions","GetRootNodeOptions","Global","GlobalCompositeOperation","GlobalDescriptor","GlobalEventHandlers","GlobalEventHandlersEventMap","HTMLAllCollection","HTMLAnchorElement","HTMLAreaElement","HTMLAudioElement","HTMLBRElement","HTMLBaseElement","HTMLBodyElement","HTMLBodyElementEventMap","HTMLButtonElement","HTMLCanvasElement","HTMLCollection","HTMLCollectionBase","HTMLCollectionOf","HTMLDListElement","HTMLDataElement","HTMLDataListElement","HTMLDetailsElement","HTMLDialogElement","HTMLDirectoryElement","HTMLDivElement","HTMLDocument","HTMLElement","HTMLElementDeprecatedTagNameMap","HTMLElementEventMap","HTMLElementTagNameMap","HTMLEmbedElement","HTMLFieldSetElement","HTMLFontElement","HTMLFormControlsCollection","HTMLFormElement","HTMLFrameElement","HTMLFrameSetElement","HTMLFrameSetElementEventMap","HTMLHRElement","HTMLHeadElement","HTMLHeadingElement","HTMLHtmlElement","HTMLHyperlinkElementUtils","HTMLIFrameElement","HTMLImageElement","HTMLInputElement","HTMLLIElement","HTMLLabelElement","HTMLLegendElement","HTMLLinkElement","HTMLMapElement","HTMLMarqueeElement","HTMLMediaElement","HTMLMediaElementEventMap","HTMLMenuElement","HTMLMetaElement","HTMLMeterElement","HTMLModElement","HTMLOListElement","HTMLObjectElement","HTMLOptGroupElement","HTMLOptionElement","HTMLOptionsCollection","HTMLOrSVGElement","HTMLOrSVGImageElement","HTMLOrSVGScriptElement","HTMLOutputElement","HTMLParagraphElement","HTMLParamElement","HTMLPictureElement","HTMLPreElement","HTMLProgressElement","HTMLQuoteElement","HTMLScriptElement","HTMLSelectElement","HTMLSlotElement","HTMLSourceElement","HTMLSpanElement","HTMLStyleElement","HTMLTableCaptionElement","HTMLTableCellElement","HTMLTableColElement","HTMLTableDataCellElement","HTMLTableElement","HTMLTableHeaderCellElement","HTMLTableRowElement","HTMLTableSectionElement","HTMLTemplateElement","HTMLTextAreaElement","HTMLTimeElement","HTMLTitleElement","HTMLTrackElement","HTMLUListElement","HTMLUnknownElement","HTMLVideoElement","HTMLVideoElementEventMap","HardwareAcceleration","HashAlgorithmIdentifier","HashChangeEvent","HashChangeEventInit","HdrMetadataType","Headers","HeadersInit","HeadersIterator","Highlight","HighlightRegistry","HighlightType","History","HkdfParams","HmacImportParams","HmacKeyAlgorithm","HmacKeyGenParams","IArguments","IDBCursor","IDBCursorDirection","IDBCursorWithValue","IDBDatabase","IDBDatabaseEventMap","IDBDatabaseInfo","IDBFactory","IDBIndex","IDBIndexParameters","IDBKeyRange","IDBObjectStore","IDBObjectStoreParameters","IDBOpenDBRequest","IDBOpenDBRequestEventMap","IDBRequest","IDBRequestEventMap","IDBRequestReadyState","IDBTransaction","IDBTransactionDurability","IDBTransactionEventMap","IDBTransactionMode","IDBTransactionOptions","IDBValidKey","IDBVersionChangeEvent","IDBVersionChangeEventInit","IIRFilterNode","IIRFilterOptions","ITextWriter","IdleDeadline","IdleRequestCallback","IdleRequestOptions","Image","ImageBitmap","ImageBitmapOptions","ImageBitmapRenderingContext","ImageBitmapRenderingContextSettings","ImageBitmapSource","ImageBufferSource","ImageCapture","ImageData","ImageDataArray","ImageDataPixelFormat","ImageDataSettings","ImageDecodeOptions","ImageDecodeResult","ImageDecoder","ImageDecoderInit","ImageEncodeOptions","ImageOrientation","ImageSmoothingQuality","ImageTrack","ImageTrackList","Immediate","ImportAssertions","ImportAttributes","ImportCallOptions","ImportExportKind","ImportMeta","ImportNodeOptions","ImportValue","Imports","Infinity","InputDeviceInfo","InputEvent","InputEventInit","InsertPosition","Instance","InstanceType","Instant","InstantConstructor","InstantLike","InstantToStringOptions","Int16Array","Int16ArrayConstructor","Int32Array","Int32ArrayConstructor","Int32List","Int8Array","Int8ArrayConstructor","IntersectionObserver","IntersectionObserverCallback","IntersectionObserverEntry","IntersectionObserverInit","Intl","Iterable","IterableIterator","IterationCompositeOperation","Iterator","IteratorConstructor","IteratorObject","IteratorObjectConstructor","IteratorResult","IteratorReturnResult","IteratorYieldResult","JSON","JsonWebKey","KHR_parallel_shader_compile","KeyAlgorithm","KeyFormat","KeySystemTrackConfiguration","KeyType","KeyUsage","KeyboardEvent","KeyboardEventInit","Keyframe","KeyframeAnimationOptions","KeyframeEffect","KeyframeEffectOptions","LDMLPluralRule","LargestContentfulPaint","LatencyMode","LineAlignSetting","LineAndPositionSetting","LinkError","LinkStyle","ListFormat","ListFormatLocaleMatcher","ListFormatOptions","ListFormatStyle","ListFormatType","Locale","LocaleCollationCaseFirst","LocaleHourCycleKey","LocaleOptions","LocalesArgument","Location","Lock","LockGrantedCallback","LockInfo","LockManager","LockManagerSnapshot","LockMode","LockOptions","LoginStatus","Lowercase","MIDIAccess","MIDIAccessEventMap","MIDIConnectionEvent","MIDIConnectionEventInit","MIDIInput","MIDIInputEventMap","MIDIInputMap","MIDIMessageEvent","MIDIMessageEventInit","MIDIOptions","MIDIOutput","MIDIOutputMap","MIDIPort","MIDIPortConnectionState","MIDIPortDeviceState","MIDIPortEventMap","MIDIPortType","Map","MapConstructor","MapIterator","Math","MathMLElement","MathMLElementEventMap","MathMLElementTagNameMap","MediaCapabilities","MediaCapabilitiesDecodingInfo","MediaCapabilitiesEncodingInfo","MediaCapabilitiesInfo","MediaCapabilitiesKeySystemConfiguration","MediaConfiguration","MediaDecodingConfiguration","MediaDecodingType","MediaDeviceInfo","MediaDeviceKind","MediaDevices","MediaDevicesEventMap","MediaElementAudioSourceNode","MediaElementAudioSourceOptions","MediaEncodingConfiguration","MediaEncodingType","MediaEncryptedEvent","MediaEncryptedEventInit","MediaError","MediaImage","MediaKeyMessageEvent","MediaKeyMessageEventInit","MediaKeyMessageType","MediaKeySession","MediaKeySessionClosedReason","MediaKeySessionEventMap","MediaKeySessionType","MediaKeyStatus","MediaKeyStatusMap","MediaKeyStatusMapIterator","MediaKeySystemAccess","MediaKeySystemConfiguration","MediaKeySystemMediaCapability","MediaKeys","MediaKeysPolicy","MediaKeysRequirement","MediaList","MediaMetadata","MediaMetadataInit","MediaPositionState","MediaProvider","MediaQueryList","MediaQueryListEvent","MediaQueryListEventInit","MediaQueryListEventMap","MediaRecorder","MediaRecorderEventMap","MediaRecorderOptions","MediaSession","MediaSessionAction","MediaSessionActionDetails","MediaSessionActionHandler","MediaSessionPlaybackState","MediaSettingsRange","MediaSource","MediaSourceEventMap","MediaSourceHandle","MediaStream","MediaStreamAudioDestinationNode","MediaStreamAudioSourceNode","MediaStreamAudioSourceOptions","MediaStreamConstraints","MediaStreamEventMap","MediaStreamTrack","MediaStreamTrackEvent","MediaStreamTrackEventInit","MediaStreamTrackEventMap","MediaStreamTrackProcessor","MediaStreamTrackProcessorInit","MediaStreamTrackState","MediaTrackCapabilities","MediaTrackConstraintSet","MediaTrackConstraints","MediaTrackSettings","MediaTrackSupportedConstraints","Memory","MemoryDescriptor","MessageChannel","MessageEvent","MessageEventInit","MessageEventSource","MessageEventTarget","MessageEventTargetEventMap","MessagePort","MessagePortEventMap","MethodDecorator","MimeType","MimeTypeArray","Module","ModuleExportDescriptor","ModuleImportDescriptor","ModuleImports","MouseEvent","MouseEventInit","MultiCacheQueryOptions","MutationCallback","MutationObserver","MutationObserverInit","MutationRecord","MutationRecordType","NaN","NamedCurve","NamedNodeMap","NavigateEvent","NavigateEventInit","Navigation","NavigationActivation","NavigationCurrentEntryChangeEvent","NavigationCurrentEntryChangeEventInit","NavigationDestination","NavigationEventMap","NavigationFocusReset","NavigationHistoryBehavior","NavigationHistoryEntry","NavigationHistoryEntryEventMap","NavigationInterceptHandler","NavigationInterceptOptions","NavigationNavigateOptions","NavigationOptions","NavigationPrecommitController","NavigationPrecommitHandler","NavigationPreloadManager","NavigationPreloadState","NavigationReloadOptions","NavigationResult","NavigationScrollBehavior","NavigationTimingType","NavigationTransition","NavigationType","NavigationUpdateCurrentEntryOptions","Navigator","NavigatorAutomationInformation","NavigatorBadge","NavigatorConcurrentHardware","NavigatorContentUtils","NavigatorCookies","NavigatorGPU","NavigatorID","NavigatorLanguage","NavigatorLocks","NavigatorLogin","NavigatorOnLine","NavigatorPlugins","NavigatorStorage","NewableFunction","NoInfer","Node","NodeFilter","NodeIterator","NodeJS","NodeList","NodeListOf","NodeModule","NodeRequire","NonDocumentTypeChildNode","NonElementParentNode","NonNullable","Notification","NotificationDirection","NotificationEvent","NotificationEventInit","NotificationEventMap","NotificationOptions","NotificationPermission","NotificationPermissionCallback","Now","Number","NumberConstructor","NumberFormat","NumberFormatConstructor","NumberFormatOptions","NumberFormatOptionsCurrencyDisplay","NumberFormatOptionsCurrencyDisplayRegistry","NumberFormatOptionsSignDisplay","NumberFormatOptionsSignDisplayRegistry","NumberFormatOptionsStyle","NumberFormatOptionsStyleRegistry","NumberFormatOptionsUseGrouping","NumberFormatOptionsUseGroupingRegistry","NumberFormatPart","NumberFormatPartTypeRegistry","NumberFormatPartTypes","NumberFormatRangePartTypeRegistry","NumberFormatRangePartTypes","NumberRangeFormatPart","OES_draw_buffers_indexed","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","OVR_multiview2","Object","ObjectConstructor","OfflineAudioCompletionEvent","OfflineAudioCompletionEventInit","OfflineAudioContext","OfflineAudioContextEventMap","OfflineAudioContextOptions","OffscreenCanvas","OffscreenCanvasEventMap","OffscreenCanvasRenderingContext2D","OffscreenRenderingContext","OffscreenRenderingContextId","Omit","OmitThisParameter","OnBeforeUnloadEventHandler","OnBeforeUnloadEventHandlerNonNull","OnErrorEventHandler","OnErrorEventHandlerNonNull","Option","OptionalEffectTiming","OptionalPostfixToken","OptionalPrefixToken","OpusBitstreamFormat","OpusEncoderConfig","OrientationLockType","OrientationType","OscillatorNode","OscillatorOptions","OscillatorType","OverSampleType","OverconstrainedError","OverflowOptions","PageRevealEvent","PageRevealEventInit","PageSwapEvent","PageSwapEventInit","PageTransitionEvent","PageTransitionEventInit","PaintTimingMixin","PannerNode","PannerOptions","PanningModelType","ParameterDecorator","Parameters","ParentNode","Partial","PartialTemporalLike","Path2D","PayerErrors","PaymentAddress","PaymentComplete","PaymentCurrencyAmount","PaymentDetailsBase","PaymentDetailsInit","PaymentDetailsModifier","PaymentDetailsUpdate","PaymentItem","PaymentMethodChangeEvent","PaymentMethodChangeEventInit","PaymentMethodData","PaymentOptions","PaymentRequest","PaymentRequestEventMap","PaymentRequestUpdateEvent","PaymentRequestUpdateEventInit","PaymentResponse","PaymentResponseEventMap","PaymentShippingOption","PaymentShippingType","PaymentValidationErrors","Pbkdf2Params","Performance","PerformanceEntry","PerformanceEntryList","PerformanceEventMap","PerformanceEventTiming","PerformanceMark","PerformanceMarkOptions","PerformanceMeasure","PerformanceMeasureOptions","PerformanceNavigation","PerformanceNavigationTiming","PerformanceObserver","PerformanceObserverCallback","PerformanceObserverEntryList","PerformanceObserverInit","PerformancePaintTiming","PerformanceResourceTiming","PerformanceServerTiming","PerformanceTiming","PeriodicWave","PeriodicWaveConstraints","PeriodicWaveOptions","PermissionDescriptor","PermissionName","PermissionState","PermissionStatus","PermissionStatusEventMap","Permissions","PhotoCapabilities","PhotoSettings","Pick","PictureInPictureEvent","PictureInPictureEventInit","PictureInPictureWindow","PictureInPictureWindowEventMap","PlainDate","PlainDateConstructor","PlainDateLike","PlainDateTime","PlainDateTimeConstructor","PlainDateTimeLike","PlainDateTimeToStringOptions","PlainDateToStringOptions","PlainDateToZonedDateTimeOptions","PlainMonthDay","PlainMonthDayConstructor","PlainMonthDayLike","PlainMonthDayToPlainDateOptions","PlainTime","PlainTimeConstructor","PlainTimeLike","PlainTimeToStringOptions","PlainYearMonth","PlainYearMonthConstructor","PlainYearMonthLike","PlainYearMonthToPlainDateOptions","PlaneLayout","PlaybackDirection","Plugin","PluginArray","PluralRuleType","PluralRules","PluralRulesConstructor","PluralRulesOptions","PluralizeUnit","PointerEvent","PointerEventInit","PointerLockOptions","PopStateEvent","PopStateEventInit","PopoverTargetAttributes","PositionAlignSetting","PositionCallback","PositionErrorCallback","PositionOptions","PredefinedColorSpace","PremultiplyAlpha","PresentationStyle","ProcessingInstruction","ProgressEvent","ProgressEventInit","Promise","PromiseConstructor","PromiseConstructorLike","PromiseFulfilledResult","PromiseLike","PromiseRejectedResult","PromiseRejectionEvent","PromiseRejectionEventInit","PromiseSettledResult","PromiseWithResolvers","PropertyDecorator","PropertyDefinition","PropertyDescriptor","PropertyDescriptorMap","PropertyIndexedKeyframes","PropertyKey","Proxy","ProxyConstructor","ProxyHandler","PublicKeyCredential","PublicKeyCredentialClientCapabilities","PublicKeyCredentialCreationOptions","PublicKeyCredentialCreationOptionsJSON","PublicKeyCredentialDescriptor","PublicKeyCredentialDescriptorJSON","PublicKeyCredentialEntity","PublicKeyCredentialParameters","PublicKeyCredentialRequestOptions","PublicKeyCredentialRequestOptionsJSON","PublicKeyCredentialRpEntity","PublicKeyCredentialType","PublicKeyCredentialUserEntity","PublicKeyCredentialUserEntityJSON","PushEncryptionKeyName","PushEvent","PushEventInit","PushManager","PushManagerAttribute","PushMessageData","PushMessageDataInit","PushSubscription","PushSubscriptionChangeEvent","PushSubscriptionChangeEventInit","PushSubscriptionJSON","PushSubscriptionOptions","PushSubscriptionOptionsInit","QueuingStrategy","QueuingStrategyInit","QueuingStrategySize","RTCAnswerOptions","RTCBundlePolicy","RTCCertificate","RTCCertificateExpiration","RTCConfiguration","RTCDTMFSender","RTCDTMFSenderEventMap","RTCDTMFToneChangeEvent","RTCDTMFToneChangeEventInit","RTCDataChannel","RTCDataChannelEvent","RTCDataChannelEventInit","RTCDataChannelEventMap","RTCDataChannelInit","RTCDataChannelState","RTCDegradationPreference","RTCDtlsFingerprint","RTCDtlsRole","RTCDtlsTransport","RTCDtlsTransportEventMap","RTCDtlsTransportState","RTCEncodedAudioFrame","RTCEncodedAudioFrameMetadata","RTCEncodedFrameMetadata","RTCEncodedVideoFrame","RTCEncodedVideoFrameMetadata","RTCError","RTCErrorDetailType","RTCErrorEvent","RTCErrorEventInit","RTCErrorInit","RTCIceCandidate","RTCIceCandidateInit","RTCIceCandidatePair","RTCIceCandidatePairStats","RTCIceCandidateType","RTCIceComponent","RTCIceConnectionState","RTCIceGathererState","RTCIceGatheringState","RTCIceProtocol","RTCIceRole","RTCIceServer","RTCIceTcpCandidateType","RTCIceTransport","RTCIceTransportEventMap","RTCIceTransportPolicy","RTCIceTransportState","RTCInboundRtpStreamStats","RTCLocalIceCandidateInit","RTCLocalSessionDescriptionInit","RTCOfferAnswerOptions","RTCOfferOptions","RTCOutboundRtpStreamStats","RTCPeerConnection","RTCPeerConnectionErrorCallback","RTCPeerConnectionEventMap","RTCPeerConnectionIceErrorEvent","RTCPeerConnectionIceErrorEventInit","RTCPeerConnectionIceEvent","RTCPeerConnectionIceEventInit","RTCPeerConnectionState","RTCPriorityType","RTCQualityLimitationReason","RTCReceivedRtpStreamStats","RTCRtcpMuxPolicy","RTCRtcpParameters","RTCRtpCapabilities","RTCRtpCodec","RTCRtpCodecParameters","RTCRtpCodingParameters","RTCRtpContributingSource","RTCRtpEncodingParameters","RTCRtpHeaderExtensionCapability","RTCRtpHeaderExtensionParameters","RTCRtpParameters","RTCRtpReceiveParameters","RTCRtpReceiver","RTCRtpReceiverTransform","RTCRtpScriptTransform","RTCRtpScriptTransformer","RTCRtpSendParameters","RTCRtpSender","RTCRtpSenderTransform","RTCRtpStreamStats","RTCRtpSynchronizationSource","RTCRtpTransceiver","RTCRtpTransceiverDirection","RTCRtpTransceiverInit","RTCSctpTransport","RTCSctpTransportEventMap","RTCSctpTransportState","RTCSdpType","RTCSentRtpStreamStats","RTCSessionDescription","RTCSessionDescriptionCallback","RTCSessionDescriptionInit","RTCSetParameterOptions","RTCSignalingState","RTCStats","RTCStatsIceCandidatePairState","RTCStatsReport","RTCStatsType","RTCTrackEvent","RTCTrackEventInit","RTCTransformEvent","RTCTransportStats","RadioNodeList","Range","RangeError","RangeErrorConstructor","ReadableByteStreamController","ReadableStream","ReadableStreamAsyncIterator","ReadableStreamBYOBReader","ReadableStreamBYOBReaderReadOptions","ReadableStreamBYOBRequest","ReadableStreamController","ReadableStreamDefaultController","ReadableStreamDefaultReader","ReadableStreamGenericReader","ReadableStreamGetReaderOptions","ReadableStreamIteratorOptions","ReadableStreamReadDoneResult","ReadableStreamReadResult","ReadableStreamReadValueResult","ReadableStreamReader","ReadableStreamReaderMode","ReadableStreamType","ReadableWritablePair","Readonly","ReadonlyArray","ReadonlyMap","ReadonlySet","ReadonlySetLike","ReadyState","Record","RecordingState","RedEyeReduction","ReferenceError","ReferenceErrorConstructor","ReferrerPolicy","Reflect","RegExp","RegExpConstructor","RegExpExecArray","RegExpIndicesArray","RegExpMatchArray","RegExpStringIterator","RegistrationOptions","RegistrationResponseJSON","RelativeTimeFormat","RelativeTimeFormatLocaleMatcher","RelativeTimeFormatNumeric","RelativeTimeFormatOptions","RelativeTimeFormatPart","RelativeTimeFormatStyle","RelativeTimeFormatUnit","RelativeTimeFormatUnitSingular","RemotePlayback","RemotePlaybackAvailabilityCallback","RemotePlaybackEventMap","RemotePlaybackState","RenderingContext","Report","ReportBody","ReportList","ReportingObserver","ReportingObserverCallback","ReportingObserverOptions","Request","RequestCache","RequestCredentials","RequestDestination","RequestInfo","RequestInit","RequestMode","RequestPriority","RequestRedirect","Required","ResidentKeyRequirement","ResizeObserver","ResizeObserverBoxOptions","ResizeObserverCallback","ResizeObserverEntry","ResizeObserverOptions","ResizeObserverSize","ResizeQuality","ResolvedCollatorOptions","ResolvedDateTimeFormatOptions","ResolvedDisplayNamesOptions","ResolvedDurationFormatOptions","ResolvedListFormatOptions","ResolvedNumberFormatOptions","ResolvedNumberFormatOptionsUseGrouping","ResolvedPluralRulesOptions","ResolvedRelativeTimeFormatOptions","ResolvedSegmenterOptions","Response","ResponseInit","ResponseType","ReturnType","RoundingOptions","RoundingOptionsWithLargestUnit","RsaHashedImportParams","RsaHashedKeyAlgorithm","RsaHashedKeyGenParams","RsaKeyAlgorithm","RsaKeyGenParams","RsaOaepParams","RsaOtherPrimesInfo","RsaPssParams","RuntimeError","SVGAElement","SVGAngle","SVGAnimateElement","SVGAnimateMotionElement","SVGAnimateTransformElement","SVGAnimatedAngle","SVGAnimatedBoolean","SVGAnimatedEnumeration","SVGAnimatedInteger","SVGAnimatedLength","SVGAnimatedLengthList","SVGAnimatedNumber","SVGAnimatedNumberList","SVGAnimatedPoints","SVGAnimatedPreserveAspectRatio","SVGAnimatedRect","SVGAnimatedString","SVGAnimatedTransformList","SVGAnimationElement","SVGBoundingBoxOptions","SVGCircleElement","SVGClipPathElement","SVGComponentTransferFunctionElement","SVGDefsElement","SVGDescElement","SVGElement","SVGElementEventMap","SVGElementTagNameMap","SVGEllipseElement","SVGFEBlendElement","SVGFEColorMatrixElement","SVGFEComponentTransferElement","SVGFECompositeElement","SVGFEConvolveMatrixElement","SVGFEDiffuseLightingElement","SVGFEDisplacementMapElement","SVGFEDistantLightElement","SVGFEDropShadowElement","SVGFEFloodElement","SVGFEFuncAElement","SVGFEFuncBElement","SVGFEFuncGElement","SVGFEFuncRElement","SVGFEGaussianBlurElement","SVGFEImageElement","SVGFEMergeElement","SVGFEMergeNodeElement","SVGFEMorphologyElement","SVGFEOffsetElement","SVGFEPointLightElement","SVGFESpecularLightingElement","SVGFESpotLightElement","SVGFETileElement","SVGFETurbulenceElement","SVGFilterElement","SVGFilterPrimitiveStandardAttributes","SVGFitToViewBox","SVGForeignObjectElement","SVGGElement","SVGGeometryElement","SVGGradientElement","SVGGraphicsElement","SVGImageElement","SVGLength","SVGLengthList","SVGLineElement","SVGLinearGradientElement","SVGMPathElement","SVGMarkerElement","SVGMaskElement","SVGMatrix","SVGMetadataElement","SVGNumber","SVGNumberList","SVGPathElement","SVGPatternElement","SVGPoint","SVGPointList","SVGPolygonElement","SVGPolylineElement","SVGPreserveAspectRatio","SVGRadialGradientElement","SVGRect","SVGRectElement","SVGSVGElement","SVGSVGElementEventMap","SVGScriptElement","SVGSetElement","SVGStopElement","SVGStringList","SVGStyleElement","SVGSwitchElement","SVGSymbolElement","SVGTSpanElement","SVGTests","SVGTextContentElement","SVGTextElement","SVGTextPathElement","SVGTextPositioningElement","SVGTitleElement","SVGTransform","SVGTransformList","SVGURIReference","SVGUnitTypes","SVGUseElement","SVGViewElement","Sanitizer","SanitizerAttribute","SanitizerAttributeNamespace","SanitizerConfig","SanitizerElement","SanitizerElementNamespace","SanitizerElementNamespaceWithAttributes","SanitizerElementWithAttributes","SanitizerPresets","Scheduler","SchedulerPostTaskCallback","SchedulerPostTaskOptions","Screen","ScreenOrientation","ScreenOrientationEventMap","ScriptProcessorNode","ScriptProcessorNodeEventMap","ScrollAxis","ScrollBehavior","ScrollIntoViewOptions","ScrollLogicalPosition","ScrollOptions","ScrollRestoration","ScrollSetting","ScrollTimeline","ScrollTimelineOptions","ScrollToOptions","SecurityPolicyViolationEvent","SecurityPolicyViolationEventDisposition","SecurityPolicyViolationEventInit","SegmentData","SegmentIterator","Segmenter","SegmenterOptions","Segments","Selection","SelectionDirection","SelectionMode","Server","ServerWebSocket","ServiceWorker","ServiceWorkerContainer","ServiceWorkerContainerEventMap","ServiceWorkerEventMap","ServiceWorkerGlobalScope","ServiceWorkerGlobalScopeEventMap","ServiceWorkerRegistration","ServiceWorkerRegistrationEventMap","ServiceWorkerState","ServiceWorkerUpdateViaCache","Set","SetConstructor","SetIterator","ShadowRoot","ShadowRootEventMap","ShadowRootInit","ShadowRootMode","ShareData","SharedArrayBuffer","SharedArrayBufferConstructor","SharedWorker","SharedWorkerGlobalScope","SharedWorkerGlobalScopeEventMap","ShellPromise","ShowPopoverOptions","SlotAssignmentMode","Slottable","Socket","SocketHandler","SourceBuffer","SourceBufferEventMap","SourceBufferList","SourceBufferListEventMap","SpeechRecognitionAlternative","SpeechRecognitionErrorCode","SpeechRecognitionErrorEvent","SpeechRecognitionErrorEventInit","SpeechRecognitionEvent","SpeechRecognitionEventInit","SpeechRecognitionResult","SpeechRecognitionResultList","SpeechSynthesis","SpeechSynthesisErrorCode","SpeechSynthesisErrorEvent","SpeechSynthesisErrorEventInit","SpeechSynthesisEvent","SpeechSynthesisEventInit","SpeechSynthesisEventMap","SpeechSynthesisUtterance","SpeechSynthesisUtteranceEventMap","SpeechSynthesisVoice","StartViewTransitionOptions","StaticRange","StaticRangeInit","Stats","StereoPannerNode","StereoPannerOptions","Storage","StorageEstimate","StorageEvent","StorageEventInit","StorageManager","StreamPipeOptions","String","StringConstructor","StringIterator","StringNumericLiteral","StructuredSerializeOptions","StylePropertyMap","StylePropertyMapReadOnly","StylePropertyMapReadOnlyIterator","StyleSheet","StyleSheetList","SubmitEvent","SubmitEventInit","Subprocess","SubtleCrypto","SuppressedError","SuppressedErrorConstructor","SvcOutputMetadata","Symbol","SymbolConstructor","SyntaxError","SyntaxErrorConstructor","TCPSocket","Table","TableDescriptor","TableKind","Tag","TagType","TaskController","TaskControllerInit","TaskPriority","TaskPriorityChangeEvent","TaskPriorityChangeEventInit","TaskSignal","TaskSignalAnyInit","TaskSignalEventMap","TemplateStringsArray","Temporal","TexImageSource","Text","TextDecodeOptions","TextDecoder","TextDecoderCommon","TextDecoderOptions","TextDecoderStream","TextEncoder","TextEncoderCommon","TextEncoderEncodeIntoResult","TextEncoderStream","TextEvent","TextInfo","TextMetrics","TextStreamBase","TextStreamReader","TextStreamWriter","TextTrack","TextTrackCue","TextTrackCueEventMap","TextTrackCueList","TextTrackEventMap","TextTrackKind","TextTrackList","TextTrackListEventMap","TextTrackMode","ThisParameterType","ThisType","TimeLikeObject","TimeRanges","TimeUnit","TimeZoneLike","TimelineRangeOffset","Timeout","Timer","TimerHandler","ToStringRoundingOptions","ToStringRoundingOptionsWithFractionalSeconds","ToggleEvent","ToggleEventInit","TogglePopoverOptions","Touch","TouchEvent","TouchEventInit","TouchInit","TouchList","TouchType","TrackEvent","TrackEventInit","TransferFunction","Transferable","TransformStream","TransformStreamDefaultController","Transformer","TransformerFlushCallback","TransformerStartCallback","TransformerTransformCallback","TransitionEvent","TransitionEventInit","TransitionOptions","TreeWalker","TypeError","TypeErrorConstructor","TypedArray","TypedPropertyDescriptor","UIEvent","UIEventInit","ULongRange","URIError","URIErrorConstructor","URL","URLPattern","URLPatternComponentResult","URLPatternInit","URLPatternInput","URLPatternOptions","URLPatternResult","URLSearchParams","URLSearchParamsIterator","Uint16Array","Uint16ArrayConstructor","Uint32Array","Uint32ArrayConstructor","Uint32List","Uint8Array","Uint8ArrayConstructor","Uint8ClampedArray","Uint8ClampedArrayConstructor","Uncapitalize","UnderlyingByteSource","UnderlyingDefaultSource","UnderlyingSink","UnderlyingSinkAbortCallback","UnderlyingSinkCloseCallback","UnderlyingSinkStartCallback","UnderlyingSinkWriteCallback","UnderlyingSource","UnderlyingSourceCancelCallback","UnderlyingSourcePullCallback","UnderlyingSourceStartCallback","UnicodeBCP47LocaleIdentifier","UnknownCredentialOptions","Uppercase","UserActivation","UserVerificationRequirement","VBArray","VBArrayConstructor","VTTCue","VTTRegion","ValidityState","ValidityStateFlags","ValueType","ValueTypeMap","VibratePattern","VideoColorPrimaries","VideoColorSpace","VideoColorSpaceInit","VideoConfiguration","VideoDecoder","VideoDecoderConfig","VideoDecoderEventMap","VideoDecoderInit","VideoDecoderSupport","VideoEncoder","VideoEncoderBitrateMode","VideoEncoderConfig","VideoEncoderEncodeOptions","VideoEncoderEncodeOptionsForAvc","VideoEncoderEventMap","VideoEncoderInit","VideoEncoderSupport","VideoFacingModeEnum","VideoFrame","VideoFrameBufferInit","VideoFrameCallbackMetadata","VideoFrameCopyToOptions","VideoFrameInit","VideoFrameOutputCallback","VideoFrameRequestCallback","VideoMatrixCoefficients","VideoPixelFormat","VideoPlaybackQuality","VideoTransferCharacteristics","ViewTimeline","ViewTimelineOptions","ViewTransition","ViewTransitionTypeSet","ViewTransitionUpdateCallback","VisualViewport","VisualViewportEventMap","VoidFunction","WEBGL_color_buffer_float","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_pvrtc","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_multi_draw","WGSLLanguageFeatures","WSH","WScript","WakeLock","WakeLockSentinel","WakeLockSentinelEventMap","WakeLockType","WaveShaperNode","WaveShaperOptions","WeakKey","WeakKeyTypes","WeakMap","WeakMapConstructor","WeakRef","WeakRefConstructor","WeakSet","WeakSetConstructor","WebAssembly","WebAssemblyCompileOptions","WebAssemblyInstantiatedSource","WebCodecsErrorCallback","WebGL2RenderingContext","WebGL2RenderingContextBase","WebGL2RenderingContextOverloads","WebGLActiveInfo","WebGLBuffer","WebGLContextAttributes","WebGLContextEvent","WebGLContextEventInit","WebGLFramebuffer","WebGLPowerPreference","WebGLProgram","WebGLQuery","WebGLRenderbuffer","WebGLRenderingContext","WebGLRenderingContextBase","WebGLRenderingContextOverloads","WebGLSampler","WebGLShader","WebGLShaderPrecisionFormat","WebGLSync","WebGLTexture","WebGLTransformFeedback","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES","WebKitCSSMatrix","WebSocket","WebSocketEventMap","WebSocketHandler","WebTransport","WebTransportBidirectionalStream","WebTransportCloseInfo","WebTransportCongestionControl","WebTransportDatagramDuplexStream","WebTransportError","WebTransportErrorOptions","WebTransportErrorSource","WebTransportHash","WebTransportOptions","WebTransportSendOptions","WebTransportSendStreamOptions","WeekInfo","WheelEvent","WheelEventInit","Window","WindowClient","WindowEventHandlers","WindowEventHandlersEventMap","WindowEventMap","WindowLocalStorage","WindowOrWorkerGlobalScope","WindowPostMessageOptions","WindowProxy","WindowSessionStorage","WithImplicitCoercion","Worker","WorkerEventMap","WorkerGlobalScope","WorkerGlobalScopeEventMap","WorkerLocation","WorkerNavigator","WorkerOptions","WorkerType","Worklet","WorkletOptions","WritableStream","WritableStreamDefaultController","WritableStreamDefaultWriter","WriteCommandType","WriteParams","XMLDocument","XMLHttpRequest","XMLHttpRequestBodyInit","XMLHttpRequestEventMap","XMLHttpRequestEventTarget","XMLHttpRequestEventTargetEventMap","XMLHttpRequestResponseType","XMLHttpRequestUpload","XMLSerializer","XPathEvaluator","XPathEvaluatorBase","XPathExpression","XPathNSResolver","XPathResult","XSLTProcessor","YearMonthLikeObject","ZonedDateTime","ZonedDateTimeConstructor","ZonedDateTimeFromOptions","ZonedDateTimeLike","ZonedDateTimeLikeObject","ZonedDateTimeToStringOptions","global","globalThis","process","structuredClone"])});function Cl(e,t={strings:!0}){let r="",n=0;while(n<e.length){let i=e.slice(n,n+2);if(i==="//"){let o=e.indexOf(`
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
`);if(!n.
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
`);
|
|
129
|
-
|
|
130
|
-
`)
|
|
131
|
-
`)
|
|
132
|
-
|
|
133
|
-
`).
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
`)
|
|
137
|
-
`)
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
94
|
+
`;return r}}function Uh(e,t,r={}){return fl(e,t,r,new WeakMap)}function fl(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let a=s(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return ul(e,t,i,n);if(!lt(t)||!lt(e))return t;return Jh(e,t,r,n)}function ul(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Kh(e,t);case"smart":return Hh(e,t,n);default:return t}return t}function Kh(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>io(i,n)))r.push(n);return r}function Hh(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(lt(t[0])&<(e[0]))return zh(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function zh(e,t,r){let n=[...t];for(let i of e){if(!lt(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in i){if(n.find((c)=>lt(c)&&(a in c)&&c[a]===i[a])){s=!0;break}}if(!s)n.push(i)}return n}function Jh(e,t,r,n){let i=t;if(lt(i)&&n.has(i))return n.get(i);let o={...e};if(lt(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let a=i[s],c=o[s];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(lt(a)&<(c))o[s]=fl(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))o[s]=ul(c,a,r.arrayMergeMode||"smart",n);else o[s]=a}return o}function hl(e,t,r="replace"){return Uh(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function io(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(!io(e[r],t[r]))return!1;return!0}if(lt(e)&<(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!io(e[i],t[i]))return!1}return!0}return!1}function lt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class dl{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1}=r;if(i){let f=vi.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!li(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),h=u.default||u,l="default"in u,y=Object.keys(u).length>0;if(!l&&!y)throw new Oi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new Oi(e,Error("Configuration must export a valid object"),"unknown");let C={config:hl(t,h,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)vi.setWithFileCheck("file",C,e,o);return C}catch(f){throw f instanceof Error?cr.configLoad(e,f):cr.configLoad(e,Error(String(f)))}};if(s)return no.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let o of n)for(let s of this.extensions)i.push(Gn(t,`${o}${s}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let o of n){if(!o)continue;if(r.push(o,`.${o}.config`,`${o}.config`,`.${o}`),e)r.push(`${e}.${o}.config`,`.${e}.${o}.config`)}let i=new Set;return r.filter((o)=>{if(!o||i.has(o))return!1;return i.add(o),!0})}checkFileAccess(e){return Vh(async()=>li(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!li(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let a=Gn(e,`${o}${s}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=Gn(e,s);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!li(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class ml{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],h=[],l={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,l);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],l);else return this.validateWithJSONSchema(e,t,l)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:h}}};if(a)return await no.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Ru(t))throw new Ri(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Ri(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(s)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${s}`,expected:a.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let a=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let a of t.required)if(!(a in s)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in s){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],c,f,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}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:qh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Yh(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 pl{fileLoader=new dl;envProcessor=new mo;validator=new ml;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(s,!0,r)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.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"),h=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),l=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(l||u))throw c;if(h&&(!f||!l))a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||o)await this.validateConfiguration(a.config,i,o,s.name);if(r?.enabled&&a)this.cacheResult(s.name||"",a,r,s);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)vt.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw vt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:o,configDir:s,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,h=o||Pi.cwd(),l=[],y=await this.loadLocalConfiguration(n,i,h,s,a,f,u,c,r);if(y)return l.push(...this.getLocalSearchPaths(n,i,h,s)),this.finalizeResult(y,l,c,n,u);let C=await this.loadHomeConfiguration(n,i,a,f,u,c);if(C)return l.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(C,l,c,n,u);let S=await this.loadPackageJsonConfiguration(n,i,h,a,f,u,c);if(S)return l.push(st(h,"package.json")),this.finalizeResult(S,l,c,n,u);if(l.push(...this.getAllSearchPaths(n,i,h,s)),t)throw cr.configNotFound(n,l,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${Yh(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,a,c){let f=a?fi(e,i,s):i,u=this.getLocalDirectories(r,n);for(let h of u){if(s)vt.info(`Searching for configuration in: ${h}`);let l=this.fileLoader.generateConfigPaths(e,h,t),y=await this.fileLoader.tryLoadFromPaths(l,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(s)vt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?fi(e,r,i):r,a=[st(Zt(),".config",e),st(Zt(),".config"),Zt()];for(let c of a){if(i)vt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:n,verbose:i});if(u){if(i)vt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let a=s?fi(e,n,o):n;try{let c=st(r,"package.json");if(!Vf(c))return null;let f={};try{f=JSON.parse(Uf(c,"utf8"))}catch(l){if(o)vt.warn("Failed to parse package.json:",[l instanceof Error?l:Error(String(l))]);return null}let u=f[e],h=e;if(!u&&t){let l=Array.isArray(t)?t:[t];for(let y of l){if(!y)continue;if(f[y]){u=f[y],h=y;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)vt.success(`Configuration loaded from package.json: ${h}`);return{config:hl(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)vt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:fi(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw cr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return vi.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);vi.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}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,st(e,"config"),st(e,".config"),t?st(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(st(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[st(Zt(),".config",e),st(Zt(),".config"),Zt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function fi(e,t,r=!1){let n=new mo,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let h=[...a,f],l=[`${i}_${h.join("_").toUpperCase()}`,`${i}_${h.map((S)=>S.toUpperCase()).join("")}`,`${i}_${h.map((S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,C;for(let S of l)if(y=Pi.env[S],y!==void 0){C=S;break}if(y!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let S=Number(y);if(!Number.isNaN(S))c[f]=S}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((S)=>S.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,h)}return c}return o(t)}var vi,no,Pu,ku=(e)=>e,Du=(e,t)=>{for(var r in t)Pu(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Mu.bind(t,r)})},Iu=(e,t)=>()=>(e&&(t=e(e=0)),t),La,Ha,lr,xr,za,ah,lh,ba,hi,qn,He,Ee,ch,Ea,fh,Sa,uh,hh,jn,dh,$a,Aa,_n,mh,ph,gh,yh,di,Ja,Ch,ze,wh,vh,xa,mi,Yn,Le,ce,bh,Ta,Eh,Oa,Sh,$h,Vn,Ah,Ra,Pa,xh,Un,Th,Oh,Rh,Ph,kh,pi,qa,Mh,Dh="0.15.6",rt,Ai,$r,Zn,Xn,xi,Qn,eo,Ar,to,ro,Mt,Ya,Za,ut,$t,Xa,Qa,Ih,Nh,el,Ti,jy,rl,de,_y,Wh,Vy,Bh,Uy,Ky,ka,Hy,Gh,jh,zy,Ma,Jy,qy,Yy,Zy,Xy,Kn,_h,Qy,ht,il,Oi,nl,ol,ho,sl,al,Ri,ll,cl,cr,qh,vt,e0,t0,r0,Zh,gl;var yl=he(()=>{vi=new Fa,no=new Na,Pu=Object.defineProperty;La={};Du(La,{withErrorRecovery:()=>Ga,tryLoadConfig:()=>ih,loadConfigWithResult:()=>th,loadConfig:()=>Ka,isRetryableError:()=>qu,isConfigNotFoundError:()=>Ju,isBunfigError:()=>ja,globalPerformanceMonitor:()=>xr,globalCache:()=>lr,getEnvOrDefault:()=>Yu,generateConfigTypes:()=>nh,defaultGeneratedDir:()=>Qa,defaultConfigDir:()=>Xa,deepMergeWithArrayStrategy:()=>co,deepMerge:()=>_a,createLibraryConfig:()=>oh,config:()=>rh,bunfigPlugin:()=>sh,applyEnvVarsToConfig:()=>Er,TypeGenerationError:()=>eo,SchemaValidationError:()=>Ar,PluginError:()=>ro,PerformanceMonitor:()=>so,FileSystemError:()=>Qn,ErrorFactory:()=>Mt,EnvVarError:()=>xi,EnvProcessor:()=>ki,ConfigValidator:()=>fo,ConfigValidationError:()=>Zn,ConfigNotFoundError:()=>Ai,ConfigMergeError:()=>Xn,ConfigLoader:()=>uo,ConfigLoadError:()=>$r,ConfigFileLoader:()=>Mi,ConfigCache:()=>oo,CacheUtils:()=>za,BunfigError:()=>rt,BrowserConfigError:()=>to,ArrayMergeStrategies:()=>Ya});Ih=Iu(async()=>{Ha=import.meta.require,lr=new oo,xr=new so,za={createKey:Fu,isEquivalent:Nu,estimateMemoryUsage:Lu},ah=Ci(zn.cwd(),"config"),lh=Ci(zn.cwd(),"src/generated"),ba=yi.env.CLARITY_LOG_DIR||Yf(Gu(),"logs"),hi={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},qn=await ju(),He={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"},Ee=He,ch=He.red,Ea=He.green,fh=He.yellow,Sa=He.blue,uh=He.magenta,hh=He.cyan,jn=He.white,dh=He.gray,$a=He.bgRed,Aa=He.bgYellow,_n=He.bold,mh=He.dim,ph=He.italic,gh=He.underline,yh=He.reset,di={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ja={debug:"\uD83D\uDD0D",info:Sa("\u2139"),success:Ea("\u2713"),warning:Aa(jn(_n(" WARN "))),error:$a(jn(_n(" ERROR ")))},Ch=new Ei("stacks"),ze=new Ei("bunfig",{showTags:!0}),wh=Ye(Sr.cwd(),"config"),vh=Ye(Sr.cwd(),"src/generated"),xa=gi.env.CLARITY_LOG_DIR||Jf(Ku(),"logs"),mi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xa,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 Hu(),Le={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"},ce=Le,bh=Le.red,Ta=Le.green,Eh=Le.yellow,Oa=Le.blue,Sh=Le.magenta,$h=Le.cyan,Vn=Le.white,Ah=Le.gray,Ra=Le.bgRed,Pa=Le.bgYellow,xh=Le.bgGray,Un=Le.bold,Th=Le.dim,Oh=Le.italic,Rh=Le.underline,Ph=Le.strikethrough,kh=Le.reset,pi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},qa={debug:"\uD83D\uDD0D",info:Oa("\u2139"),success:Ta("\u2713"),warning:Pa(Vn(Un(" WARN "))),error:Ra(Vn(Un(" ERROR ")))},Mh=new $i("stacks"),rt=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}`}},Ai=class extends rt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},$r=class extends rt{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}},Zn=class extends rt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Xn=class extends rt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},xi=class extends rt{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}},Qn=class extends rt{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}},eo=class extends rt{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}},Ar=class extends rt{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})}},to=class extends rt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}},ro=class extends rt{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}},Mt={configNotFound(e,t,r){return new Ai(e,t,r)},configLoad(e,t,r){return new $r(e,t,r)},configValidation(e,t,r){return new Zn(e,t,r)},configMerge(e,t,r,n){return new Xn(e,t,r,n)},envVar(e,t,r,n){return new xi(e,t,r,n)},fileSystem(e,t,r){return new Qn(e,t,r)},typeGeneration(e,t,r){return new eo(e,t,r)},schemaValidation(e,t,r){return new Ar(e,t,r)},browserConfig(e,t,r,n){return new to(e,t,r,n)},plugin(e,t,r){return new ro(e,t,r)}},Ya={replace:"replace",concat:"concat",smart:"smart"},Za=/^https?:\/\//,ut=new $i("bunfig",{showTags:!0}),$t=new uo,Xa=Ze(Bt.cwd(),"config"),Qa=Ze(Bt.cwd(),"src/generated")});Nh=wi.env.CLARITY_LOG_DIR||Cu(Fh(),"logs"),el={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Nh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ti={...el},jy=(async()=>{try{let{loadConfig:e}=await Ih().then(()=>La),t=await e({name:"clarity",alias:"logging",defaultConfig:el,cwd:wi.cwd()});if(t)Object.assign(Ti,t)}catch{}return Ti})();rl={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"},de=rl,{red:_y,green:Wh,yellow:Vy,blue:Bh,magenta:Uy,cyan:Ky,white:ka,gray:Hy,bgRed:Gh,bgYellow:jh,bgGray:zy,bold:Ma,dim:Jy,italic:qy,underline:Yy,strikethrough:Zy,reset:Xy}=rl,Kn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_h={debug:"\uD83D\uDD0D",info:Bh("\u2139"),success:Wh("\u2713"),warning:jh(ka(Ma(" WARN "))),error:Gh(ka(Ma(" ERROR ")))};Qy=new Di("stacks");ht=class ht 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}`}};il=class il extends ht{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};Oi=class Oi extends ht{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}};nl=class nl extends ht{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};ol=class ol extends ht{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};ho=class ho extends ht{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};sl=class sl extends ht{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}};al=class al extends ht{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}};Ri=class Ri extends ht{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})}};ll=class ll extends ht{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};cl=class cl extends ht{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}};cr={configNotFound(e,t,r){return new il(e,t,r)},configLoad(e,t,r){return new Oi(e,t,r)},configValidation(e,t,r){return new nl(e,t,r)},configMerge(e,t,r,n){return new ol(e,t,r,n)},envVar(e,t,r,n){return new ho(e,t,r,n)},fileSystem(e,t,r){return new sl(e,t,r)},typeGeneration(e,t,r){return new al(e,t,r)},schemaValidation(e,t,r){return new Ri(e,t,r)},browserConfig(e,t,r,n){return new ll(e,t,r,n)},plugin(e,t,r){return new cl(e,t,r)}};qh=/^https?:\/\//;vt=new Di("bunfig",{showTags:!0});e0=new pl;t0=st(Pi.cwd(),"config"),r0=st(Pi.cwd(),"src/generated"),Zh={cwd:_f.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},gl=Zh});function Cl(e,t,r){let n={file:t,message:"Unknown error",code:Tr.UNKNOWN_ERROR};if(e instanceof Error){n.message=e.message,n.stack=e.stack;let i=e.message.match(/\((\d+),(\d+)\)/);if(i)n.location={line:Number.parseInt(i[1],10),column:Number.parseInt(i[2],10)};if(e.message.includes("Cannot find")||e.message.includes("not found"))n.code=Tr.FILE_NOT_FOUND,n.suggestion="Check that the file path is correct and the file exists.";else if(e.message.includes("syntax")||e.message.includes("Unexpected token"))n.code=Tr.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=Tr.TYPE_INFERENCE_ERROR,n.suggestion="Add explicit type annotations to help with type inference.";else if(e.message.includes("parse")||e.message.includes("Parse"))n.code=Tr.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function wl(e,t){let r=[],n=e.file;if(e.location)n+=`:${e.location.line}:${e.location.column}`;if(e.code)n+=` [${e.code}]`;if(r.push(n),r.push(` Error: ${e.message}`),t&&e.location){r.push("");let i=t.split(`
|
|
95
|
+
`),o=e.location.line-1;if(o>=0&&o<i.length){let s=Math.max(0,o-1),a=Math.min(i.length-1,o+1);for(let c=s;c<=a;c++){let f=(c+1).toString().padStart(4," "),u=c===o?">":" ";if(r.push(` ${u} ${f} | ${i[c]}`),c===o&&e.location.column>0){let h=" ".repeat(10+e.location.column-1);r.push(` ${h}^`)}}}}if(e.suggestion)r.push(""),r.push(` Suggestion: ${e.suggestion}`);return r.join(`
|
|
96
|
+
`)}var Tr;var vl=he(()=>{Tr={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 El(e){return e.endsWith(".vue")}function Xh(e){let t={script:null,scriptSetup:null},r=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,n;while((n=r.exec(e))!==null){let i=n[1]||"",o=/lang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??"js",s={content:n[2]??"",attrs:i,setup:/\bsetup\b/.test(i),lang:o};if(s.setup)t.scriptSetup=s;else t.script=s}return t}function it(e,t){let r=e[t];t++;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n===r)return t+1;t++}return t}function ct(e,t){t++;let r=0;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n==="`"&&r===0)return t+1;if(n==="$"&&e[t+1]==="{"){r++,t+=2;continue}if(n==="}"){if(r>0)r--;t++;continue}t++}return t}function pt(e,t){if(e[t+1]==="/"){let r=e.indexOf(`
|
|
97
|
+
`,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 go(e,t){let r=e[t];if(r==='"'||r==="'")return it(e,t);if(r==="`")return ct(e,t);if(r==="/"&&(e[t+1]==="/"||e[t+1]==="*"))return pt(e,t);return t}function yo(e){let t=e.split(""),r=0;while(r<e.length){let n=go(e,r);if(n>r){for(let i=r;i<n;i++)if(t[i]!==`
|
|
98
|
+
`&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function je(e,t,r,n){let i=0,o=t;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){o=it(e,o);continue}if(s==="`"){o=ct(e,o);continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=pt(e,o);continue}if(s===r)i++;else if(s===n){if(i--,i===0)return o}o++}return-1}function Co(e,t){let r=0,n=t;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=it(e,n);continue}if(i==="`"){n=ct(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=pt(e,n);continue}if(i==="="&&e[n+1]===">"){n+=2;continue}if(i==="<")r++;else if(i===">"){if(r--,r===0)return n}n++}return-1}function fr(e,t=","){let r=[],n=0,i="",o=0;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){let a=it(e,o);i+=e.slice(o,a),o=a;continue}if(s==="`"){let a=ct(e,o);i+=e.slice(o,a),o=a;continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=pt(e,o);continue}if(s==="{"||s==="["||s==="("||s==="<")n++;else if(s==="}"||s==="]"||s===")"||s===">")n--;if(s===t&&n===0){r.push(i),i="",o++;continue}i+=s,o++}if(i.trim()!=="")r.push(i);return r}function Pr(e){let t=e.trim();if(!t.startsWith("{"))return[];let r=je(t,0,"{","}");if(r===-1)return[];let n=t.slice(1,r),i=[];for(let o of fr(n)){let s=-1,a=0;for(let u=0;u<o.length;u++){let h=o[u];if(h==='"'||h==="'"){u=it(o,u)-1;continue}if(h==="`"){u=ct(o,u)-1;continue}if(h==="{"||h==="["||h==="("||h==="<")a++;else if(h==="}"||h==="]"||h===")"||h===">")a--;else if(h===":"&&a===0){s=u;break}}if(s!==-1){i.push({key:Or(o.slice(0,s).trim()),value:o.slice(s+1).trim(),isMethod:!1});continue}let c=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(o.trim());if(c){i.push({key:Or(c[1]),value:o.trim(),isMethod:!0});continue}let f=o.trim();if(f)i.push({key:Or(f),value:"",isMethod:!1})}return i}function Or(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function Rr(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function kr(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n;while((n=r.exec(e))!==null){let i=n.index+n[0].length;while(i<e.length&&/\s/.test(e[i]))i++;let o=null;if(e[i]==="<"){let c=Co(e,i);if(c===-1)return null;o=e.slice(i+1,c).trim(),i=c+1;while(i<e.length&&/\s/.test(e[i]))i++}if(e[i]!=="(")continue;let s=je(e,i,"(",")");if(s===-1)return null;let a=fr(e.slice(i+1,s));return{generic:o,arg:a.length>0?a[0].trim():null}}return null}function Qh(e,t){let r=Sl(e,t);if(!r)return null;return r.kind==="interface"?e.slice(r.bodyStart,r.end):e.slice(r.bodyStart,r.end).trim()}function Sl(e,t){let r=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(r){let i=r.index+r[0].length-1,o=je(e,i,"{","}");if(o!==-1)return{kind:"interface",start:r.index,end:o+1,bodyStart:i}}let n=new RegExp(`\\btype\\s+${t}\\b[^=]*=`,"m").exec(e);if(n){let i=n.index+n[0].length,o=0,s=i;while(i<e.length){let a=e[i];if(a==='"'||a==="'"){i=it(e,i);continue}if(a==="`"){i=ct(e,i);continue}if(a==="{"||a==="["||a==="("||a==="<")o++;else if(a==="}"||a==="]"||a===")"||a===">")o--;else if((a===";"||a===`
|
|
99
|
+
`)&&o===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:s}}return null}function ed(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let r=e.indexOf("<",t),n=Co(e,r);if(n===-1)return null;if(e.slice(n+1).trim()!=="")return null;return e.slice(r+1,n).trim()}function po(e){let t=e.trim(),r=ed(t);if(r!==null)return{type:r,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let n=je(t,0,"[","]");if(n!==-1){let i=fr(t.slice(1,n)).map((o)=>po(o).type).filter((o)=>o!=="unknown");return{type:i.length>0?[...new Set(i)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let n=Pr(t),i=n.find((c)=>c.key==="type"),o=n.find((c)=>c.key==="required"),s=i?po(i.value).type:"unknown",a=!(o&&o.value.trim()==="true");return{type:s,optional:a}}if(bl[t])return{type:bl[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function Li(e){let t=e.trim();if(t.startsWith("{")){let r=Pr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>{if(n.isMethod||n.value==="")return`${Rr(n.key)}?: unknown`;let i=po(n.value);return`${Rr(n.key)}${i.optional?"?":""}: ${i.type}`}).join(", ")} }`}if(t.startsWith("[")){let r=je(t,0,"[","]");if(r===-1)return null;let n=fr(t.slice(1,r)).map((i)=>Or(i.trim())).filter((i)=>i!=="");if(n.length===0)return"{}";return`{ ${n.map((i)=>`${Rr(i)}?: unknown`).join(", ")} }`}return null}function td(e){let t=e.trim();if(!t.startsWith("["))return null;let r=je(t,0,"[","]");if(r===-1)return null;let n=fr(t.slice(1,r)).map((i)=>i.trim());if(n.length===0)return"{}";if(!n.every((i)=>i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"')))return"string[]";return`[${n.map((i)=>JSON.stringify(Or(i))).join(", ")}]`}function rd(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=Pr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>`${JSON.stringify(n.key)}: (...args: any[]) => void`).join(", ")} }`}function $l(e){return td(e)??rd(e)}function id(e){let t=[],r=0,n="",i=0;while(i<e.length){let o=e[i];if(o==='"'||o==="'"){let s=it(e,i);n+=e.slice(i,s),i=s;continue}if(o==="`"){let s=ct(e,i);n+=e.slice(i,s),i=s;continue}if(o==="/"&&(e[i+1]==="/"||e[i+1]==="*")){let s=pt(e,i);n+=e.slice(i,s),i=s;continue}if(o==="="&&e[i+1]===">"){n+="=>",i+=2;continue}if(o==="{"||o==="["||o==="("||o==="<")r++;else if(o==="}"||o==="]"||o===")"||o===">")r--;if((o===";"||o===","||o===`
|
|
100
|
+
`)&&r===0){if(n.trim()!=="")t.push(n.trim());n="",i++;continue}n+=o,i++}if(n.trim()!=="")t.push(n.trim());return t}function nd(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 n=id(t.slice(1,r));if(n.length===0)return"{}";let i=[];for(let o of n){let s=/^\(\s*\w+\s*:\s*/.exec(o);if(!s)return null;let a=s[0].length,c=o[a];if(c!=="'"&&c!=='"'&&c!=="`")return null;let f=it(o,a),u=o.slice(a+1,f-1),h=je(o,o.indexOf("(",0),"(",")");if(h===-1)return null;let l=o.slice(a,h),y=fr(l).slice(1),C=o.slice(h+1).trim();if(C.startsWith(":"))C=C.slice(1).trim();if(C==="")C="void";i.push(`${JSON.stringify(u)}: (${y.map((S)=>S.trim()).join(", ")}) => ${C}`)}return`{ ${i.join(", ")} }`}function wo(e){let t=e;for(let r of["defineProps","defineEmits","defineExpose","defineSlots","defineOptions"])t=od(t,r);return t}function od(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n=[],i=e,o;while((o=r.exec(e))!==null){let s=e.lastIndexOf(`
|
|
101
|
+
`,o.index)+1,a=e.slice(s,o.index),c=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(a);if(!c)continue;let f=o.index+o[0].length;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]==="<"){let l=Co(e,f);if(l===-1)continue;f=l+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 l=s+a.length-c[1].length,y=e.indexOf("(",l);if(y!==-1){let C=je(e,y,"(",")");if(C!==-1)u=C}}let h=u+1;while(h<e.length&&e[h]!==`
|
|
102
|
+
`&&/\s|;/.test(e[h]))h++;if(e[h]===`
|
|
103
|
+
`)h++;n.push([s,h])}for(let s=n.length-1;s>=0;s--)i=i.slice(0,n[s][0])+i.slice(n[s][1]);return i}function vo(e){let t=sd(e);if(t!==-1){let r=/^export\s+default\b/.exec(e.slice(t))?.[0];if(!r)return{options:null,script:e,passthrough:!1};let n=t+r.length;while(n<e.length&&/\s/.test(e[n]))n++;let i=-1,o=-1,s=-1;if(e[n]==="{")i=n,o=je(e,n,"{","}"),s=o;else if(e.startsWith("defineComponent",n)){let f=e.indexOf("(",n);if(f!==-1){let u=f+1;while(u<e.length&&/\s/.test(e[u]))u++;if(e[u]==="{")i=u,o=je(e,u,"{","}"),s=je(e,f,"(",")")}}if(i===-1||o===-1||s===-1)return{options:null,script:e,passthrough:!0};let a=s+1;if(e[a]===";")a++;let c=(e.slice(0,t)+e.slice(a)).trim();return{options:e.slice(i,o+1),script:c,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function sd(e){let t=0,r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=it(e,r);continue}if(n==="`"){r=ct(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=pt(e,r);continue}if(n==="{"||n==="["||n==="(")t++;else if(n==="}"||n==="]"||n===")")t=Math.max(0,t-1);else if(t===0&&e.startsWith("export",r)){let i=r===0?"":e[r-1],o=e[r+6]??"";if(!/[\w$]/.test(i)&&!/[\w$]/.test(o)){if(/^export\s+default\b/.exec(e.slice(r)))return r}}r++}return-1}function Ii(e,t){let r=Pr(e).find((n)=>n.key===t);return r&&r.value!==""?r.value:null}function Fi(e,t){let r=ld(e),n=e;for(let i=r.length-1;i>=0;i--){let o=r[i],s=n.slice(0,o.start)+n.slice(o.end);if(ad(s,o.name))continue;if(new RegExp(`\\btypeof\\s+${o.name}\\b`).test(t))continue;n=s}return n}function ad(e,t){let r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=it(e,r);continue}if(n==="`"){r=ct(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=pt(e,r);continue}if(/[A-Za-z_$]/.test(n)){let i=r+1;while(i<e.length&&/[\w$]/.test(e[i]))i++;if(e.slice(r,i)===t)return!0;r=i;continue}r++}return!1}function ld(e){let t=[],r=cd(e),n=/^[ \t]*(const|let|var|(?:async[ \t]+)?function)[ \t]+([A-Za-z_$][\w$]*)[ \t]*(?::[^=\n]+)?=?/gm,i;while((i=n.exec(e))!==null){let o=e.lastIndexOf(`
|
|
104
|
+
`,i.index)+1;if(!r.has(o))continue;if(/\bexport\b/.test(e.slice(o,i.index)))continue;let s=i[1],a=i[2],c=i.index+i[0].length,f=-1;if(s.endsWith("function")){let u=e.indexOf("(",c);if(u===-1)continue;let h=je(e,u,"(",")");if(h===-1)continue;c=h+1;while(c<e.length&&/\s/.test(e[c]))c++;if(e[c]===":")while(c<e.length&&e[c]!=="{"&&e[c]!==`
|
|
105
|
+
`)c++;while(c<e.length&&/\s/.test(e[c])&&e[c]!==`
|
|
106
|
+
`)c++;if(e[c]!=="{")continue;let l=je(e,c,"{","}");if(l===-1)continue;f=l+1}else{let u=0;while(c<e.length){let h=e[c];if(h==='"'||h==="'"){c=it(e,c);continue}if(h==="`"){c=ct(e,c);continue}if(h==="/"&&(e[c+1]==="/"||e[c+1]==="*")){c=pt(e,c);continue}if(h==="{"||h==="["||h==="(")u++;else if(h==="}"||h==="]"||h===")")u--;else if(h===";"&&u===0){f=c+1;break}else if(h===`
|
|
107
|
+
`&&u===0){f=c;break}c++}if(f===-1)f=e.length}if(e[f]===`
|
|
108
|
+
`)f++;t.push({name:a,start:i.index,end:f})}return t}function cd(e){let t=new Set([0]),r=0,n=0;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=it(e,n);continue}if(i==="`"){n=ct(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=pt(e,n);continue}if(i==="{"||i==="["||i==="(")r++;else if(i==="}"||i==="]"||i===")")r=Math.max(0,r-1);if(i===`
|
|
109
|
+
`&&r===0)t.add(n+1);n++}return t}function Ni(e,t,r){let n=e.indexOf(r);if(n===-1)return e;let i=e.lastIndexOf(`
|
|
110
|
+
`,n)+1;if(/\bexport\b/.test(e.slice(i,n)))return e;let o=e.slice(0,n)+e.slice(n+r.length);if(new RegExp(`\\b${t}\\b`).test(o))return e;return o}function bo(e){let t="",r=0,n=()=>{for(let o=t.length-1;o>=0;o--)if(!/\s/.test(t[o]))return t[o];return""},i=(o)=>{for(let s=o;s<e.length;s++)if(!/\s/.test(e[s]))return e[s];return""};while(r<e.length){let o=e[r];if(o==='"'||o==="'"){let s=it(e,r);t+=e.slice(r,s),r=s;continue}if(o==="`"){let s=ct(e,r);t+=e.slice(r,s),r=s;continue}if(o==="/"&&e[r+1]==="*"){let s=pt(e,r);t+=e.slice(r,s).replace(/\s*\n\s*/g," "),r=s;continue}if(o==="/"&&e[r+1]==="/"){let s=r+2;while(s<e.length&&e[s]!==`
|
|
111
|
+
`)s++;let a=e.slice(r+2,s).trim();if(a!==""&&!a.includes("*/"))t+=`/* ${a} */`;r=s;continue}if(o===`
|
|
112
|
+
`){let s=n(),a=i(r+1);if(s===""||a===""){r++;continue}let c=fd(t);if(!c&&("{;,(<:=[".includes(s)||"}),]>;|&".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+=o,r++}return t}function fd(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 n=r-1;n>=0;n--){let i=e[n];if(/\s/.test(i))continue;return"{;,(<:".includes(i)}return!0}function Wi(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=kr(n,"defineProps");if(!i)continue;if(i.generic){let o=i.generic;if(o.startsWith("{"))return{type:o};if(/^[A-Za-z_$][\w$]*$/.test(o)){for(let s of r){let a=Sl(s,o);if(!a)continue;let c=Qh(s,o);if(c===null)continue;return{type:c,inlinedLocal:{name:o,declText:s.slice(a.start,a.end)}}}return{type:o}}return{type:o}}if(i.arg){let o=Li(i.arg);if(o!==null)return{type:o}}}return null}function Eo(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=kr(n,"defineEmits");if(!i)continue;if(i.generic)return nd(i.generic)??i.generic;if(i.arg){let o=$l(i.arg);if(o!==null)return o}}return null}function So(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=kr(n,"defineExpose");if(!i||!i.arg||!i.arg.startsWith("{"))continue;let o=Pr(i.arg);if(o.length===0)return null;return`{ ${o.map((s)=>{if(s.value===""&&/^[A-Za-z_$][\w$]*$/.test(s.key))return`${Rr(s.key)}: typeof ${s.key}`;let a=s.isMethod||/=>|^\s*function\b/.test(s.value);return`${Rr(s.key)}: ${a?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function Al(e){let t=Xh(e),r="",n=null,i=null;if(t.script){let x=vo(t.script.content);if(x.passthrough)return t.scriptSetup?`${t.script.content}
|
|
113
|
+
${t.scriptSetup.content}`:t.script.content;if(r=x.script,x.options){let v=Ii(x.options,"props");if(v)n=Li(v);let G=Ii(x.options,"emits");if(G)i=$l(G)}}let o=t.scriptSetup?.content??null,s=o!==null?wo(o):null,a=Wi(o,o!==null?null:r),c=a?.type??n??"{}",f=Eo(o,null)??i,u=So(o,null),h=a?.inlinedLocal;if(h){if(r=Ni(r,h.name,h.declText),s!==null)s=Ni(s,h.name,h.declText)}let l=[c,u??"{}"];if(f)l.push("{}","{}","{}","{}","{}",f);let y=bo(`DefineComponent<${l.join(", ")}>`),C=[],S=Fi(r,y);if(S.trim()!=="")C.push(S);if(s&&s.trim()!==""){let x=Fi(s,y);if(x.trim()!=="")C.push(x)}return C.push("import type { DefineComponent } from 'vue'"),C.push(`type __DtsxComponentType = ${y}`),C.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),C.push("export default __dtsx_component__"),C.join(`
|
|
114
|
+
`)}var bl;var $o=he(()=>{bl={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 Tl(e){return e.endsWith(".stx")}function ud(e){let t=[],r=/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi,n;while((n=r.exec(e))!==null){let i=n[1]??"",o=/\blang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??(/\b(?:type\s*=\s*["'](?:text\/)?typescript["']|typescript)\b/i.test(i)?"ts":"js"),s=/\bserver\b/i.test(i)?"server":/\bclient\b/i.test(i)?"client":"universal";t.push({content:n[2]??"",kind:"script",attrs:i,context:s,lang:o,start:n.index})}return t}function hd(e){let t=[],r=/^[ \t]*@ts[ \t]*(?:\r?\n|$)/gm,n;while((n=r.exec(e))!==null){let i=r.lastIndex,o=/^[ \t]*@endts[ \t]*(?:\r?\n|$)/gm;o.lastIndex=i;let s=o.exec(e),a=s?.index??e.length;if(t.push({content:e.slice(i,a),kind:"ts",attrs:"",context:"universal",lang:"ts",start:n.index}),!s)break;r.lastIndex=o.lastIndex}return t}function dd(e){return[...ud(e),...hd(e)].sort((t,r)=>t.start-r.start)}function md(e){if(e.kind==="ts"||e.context!=="universal"||e.lang==="ts")return!0;return/\b(?:defineProps|defineEmits|defineExpose|defineSlots)\b|\bexport\s|\b(?:interface|type)\s+[A-Za-z_$]/.test(e.content)}function pd(e){let t=/(?:\$?props)\s+as\s+/g,r;while((r=t.exec(e))!==null){let n=t.lastIndex;while(n<e.length&&/\s/.test(e[n]))n++;if(e[n]==="{"){let s=je(e,n,"{","}");if(s!==-1)return e.slice(n,s+1).trim();continue}let i=/^[A-Za-z_$][\w$]*/.exec(e.slice(n))?.[0];if(!i)continue;let o=n+i.length;while(o<e.length&&/\s/.test(e[o]))o++;if(e[o]==="<"){let s=je(e,o,"<",">");if(s!==-1)o=s+1}return e.slice(n,o).trim()}return null}function gd(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function yd(e){let t=/^\s*(?:\|\||\?\?)\s*([^;\n]+)/.exec(e)?.[1]?.trim();if(/^['"`]/.test(t??""))return"string";if(/^(?:true|false)\b/.test(t??""))return"boolean";if(/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)\b/.test(t??""))return"number";if(/^\[/.test(t??""))return"unknown[]";if(/^\{/.test(t??""))return"Record<string, unknown>";if(/^\s*(?:===?|!==?)\s*(?:true|false)\b/.test(e))return"boolean";return"unknown"}function Cd(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function wd(e){let t=yo(e),r=new Map,n=/\$props(?:\.([A-Za-z_$][\w$]*)|\[\s*(['"])([^'"\n]+)\2\s*\])/g,i;while((i=n.exec(e))!==null){if(t.slice(i.index,i.index+6)!=="$props")continue;let o=i[1]??i[3],s=yd(e.slice(n.lastIndex));r.set(o,Cd(r.get(o),s))}if(r.size===0)return null;return{type:`{ ${[...r].map(([o,s])=>`${/^[A-Za-z_$][\w$]*$/.test(o)?o:JSON.stringify(o)}?: ${s}`).join(", ")} }`}}function vd(e){let t=Wi(e,null);if(t)return t;let r=pd(e)??gd(e);if(!r)return wd(e);if(/^[A-Za-z_$][\w$]*$/.test(r)){let n=r.replace(/[$]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:declare\\s+)?(?:interface|type)\\s+${n}\\b`).test(e))return{type:r}}return Wi(`${e}
|
|
115
|
+
defineProps<${r}>()`,null)}function bd(e){return wo(e)}function xl(e){let t=yo(e).trimStart();if(t==="")return!0;return/^(?:import\b|export\b|declare\b|interface\b|type\b|(?:export\s+)?namespace\b|(?:export\s+)?module\b|(?:abstract\s+)?class\b|const\b|let\b|var\b|(?:async\s+)?function\b)/.test(t)}function Ed(e){let t=[],r=0,n=0,i=0;while(i<e.length){let s=e[i],a=go(e,i);if(a>i){i=a;continue}if(s==="{"||s==="["||s==="(")n++;else if(s==="}"||s==="]"||s===")")n=Math.max(0,n-1);if((s===";"||s===`
|
|
116
|
+
`)&&n===0){let c=i+1;if(!xl(e.slice(r,c)))t.push([r,c]);r=c}i++}if(r<e.length&&!xl(e.slice(r)))t.push([r,e.length]);let o=e;for(let s=t.length-1;s>=0;s--)o=o.slice(0,t[s][0])+o.slice(t[s][1]);return o}function Ol(e){let t=dd(e).filter(md).map((S)=>S.content).join(`
|
|
117
|
+
`),r=null,n=vo(t);if(n.passthrough)return t;if(t=n.script,n.options){let S=Ii(n.options,"props");if(S)r=Li(S)}let i=t,o=bd(t),s=vd(i),a=s?.type??r??"{}",c=Eo(i,null),f=So(i,null),u=kr(i,"defineSlots")?.generic??null,h=s?.inlinedLocal;if(h)o=Ni(o,h.name,h.declText);let l=`DefineComponent<${a}>`,y=[];if(c)y.push(`readonly __stxEmits?: ${c}`);if(u)y.push(`readonly __stxSlots?: ${u}`);if(f)y.push(`readonly __stxExposed?: ${f}`);if(y.length>0)l+=` & { ${y.join(", ")} }`;l=bo(l),o=Ed(Fi(o,l));let C=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${l}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(o.trim()!=="")C.push(o);return C.join(`
|
|
118
|
+
`)}var Rl=he(()=>{$o()});function xt(e,t=!0){if(!t||!e||e.length===0)return"";if(e.length===1){let n=e[0];if(n.length>0&&n.charCodeAt(0)>32&&n.charCodeAt(n.length-1)>32)return`${n}
|
|
142
119
|
`;return`${n.trim()}
|
|
143
120
|
`}let r="";for(let n=0;n<e.length;n++){if(n>0)r+=`
|
|
144
121
|
`;r+=e[n].trim()}return`${r}
|
|
145
|
-
`}function
|
|
146
|
-
`)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let
|
|
147
|
-
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function
|
|
148
|
-
`)||e.includes("\r"))return"string";return e}function
|
|
122
|
+
`}function Do(e){return e.replaceAll("*/","*\\/")}function xo(e){return Fl(e).replace(/\n[ \t]*(?=\n)/g,"")}function Fl(e){if(e.indexOf("/*")===-1)return e.trim();let t=[],r=0,n=0,i=e.length;while(n<i)if(e.charCodeAt(n)===47&&n+1<i&&e.charCodeAt(n+1)===42){if(n>r)t.push(e.substring(r,n));n+=2;while(n<i-1){if(e.charCodeAt(n)===42&&e.charCodeAt(n+1)===47){n+=2;break}n++}r=n}else n++;if(r<i)t.push(e.substring(r));return t.join("").trim()}function Fo(){_i=!0,Xe=null}function No(){_i=!1;let e=Xe;return Xe=null,e}function Lo(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 n=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===n)return!1;if(r<t&&e.charCodeAt(r)===46){r++;let i=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===i)return!1}return r===t}function Sd(e){for(let t=0,r=e.length-1;t<r;t++){let n=e.charCodeAt(t);if(n<48||n>57)return!1}return!0}function Ao(e,t){let r=0,n=0;while((n=e.indexOf(t,n))!==-1)r++,n+=t.length;return r}function Pl(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===36||e===95||e===46||e===58||e===45}function Bi(e){let t=e.trim();if(t.length<3||t.charCodeAt(0)!==60)return!1;if(t.startsWith("<>"))return t.endsWith("</>");let r=t.charCodeAt(1);if(!(r>=65&&r<=90||r>=97&&r<=122||r===36||r===95))return!1;let n=2;while(n<t.length&&Pl(t.charCodeAt(n)))n++;let i=t.slice(1,n),o=t.charCodeAt(n);if(o>32&&o!==62&&o!==47)return!1;if(t.endsWith("/>"))return!0;let s=t.lastIndexOf("</");if(s===-1)return!1;let a=s+2;while(a<t.length&&Pl(t.charCodeAt(a)))a++;return t.slice(s+2,a)===i&&t.charCodeAt(a)===62&&a===t.length-1}function Gi(e){let t=e.length,r=!1;for(let s=1;s<t;s++)if(e.charCodeAt(s)<=32&&e.charCodeAt(s-1)<=32){r=!0;break}if(!r)for(let s=0;s<t;s++){let a=e.charCodeAt(s);if(a===10||a===13||a===9){r=!0;break}}if(!r)return e;let n=[],i=-1,o=!1;for(let s=0;s<t;s++)if(e.charCodeAt(s)<=32){if(!o){if(i>=0)n.push(e.substring(i,s));n.push(" "),o=!0,i=-1}}else{if(o||i<0)i=s;o=!1}if(i>=0)n.push(e.substring(i));return n.join("")}function Ie(e,t=!1,r=!1,n=0){if(!e||typeof e!=="string")return"unknown";if(n>=Io)return"unknown";let i=e.trim();if(Bi(i))return"JSX.Element";if(i.startsWith("BigInt("))return"bigint";if(i.startsWith("Symbol.for("))return"symbol";if(i.includes(".raw`")||i.includes("String.raw`"))return"string";if(i.startsWith("`")&&i.endsWith("`")){if(!t||i.includes("${")||i.includes(`
|
|
123
|
+
`)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let s=$d(i);if(s!==null){if(s==="string"||!t)return"string";return s}}if(Lo(i)){if(!t)return"number";return i}if(i==="true"||i==="false"){if(!t)return"boolean";return i}if(i==="null")return"null";if(i==="undefined")return"undefined";if(i.startsWith("[")&&i.endsWith("]"))return Ro(i,t,n+1);if(i.startsWith("{")&&i.endsWith("}"))return Ld(i,t,n+1);if(i.startsWith("class ")||i.startsWith("class{"))return Fd(i);if(i.startsWith("new "))return Id(i);if(i.endsWith("as const")){let s=i.slice(0,-8).trim();if(s.startsWith("[")&&s.endsWith("]")){let a=s.slice(1,-1).trim();if(!a)return"readonly []";let c=ji(a),f=[];for(let u=0;u<c.length;u++)f.push(Ie(c[u].trim(),!0,!1,n+1));return`readonly [${f.join(", ")}]`}return Ie(s,!0,r,n+1)}if(dr(i)!==-1||i.startsWith("function")||i.startsWith("async"))return _l(i,r,n,t);if(i.startsWith("`")&&i.endsWith("`"))return Dd(i,t);if(i.startsWith("Promise."))return Wl(i,t,n);if(i.startsWith("await "))return"unknown";if(i.charCodeAt(i.length-1)===110&&i.length>1&&Sd(i)){if(t)return i;return"bigint"}if(i.startsWith("Symbol(")||i==="Symbol.for")return"symbol";let o=Bl(i);if(o!==null)return o;if(Nl(i))return"boolean";if(Od(i))return"number";return"unknown"}function kl(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return It(e,0,t)===e.length}function $d(e){if(kl(e))return e;let t=Ad(e);if(t.length<2)return null;let r=!1,n=!0,i="";for(let o of t){let s=o.trim();if(kl(s))r=!0,i+=xd(s);else n=!1}if(n)return Td(i);if(r)return"string";return null}function Ad(e){let t=[],r=0,n=0,i=0;while(i<e.length){let o=e.charCodeAt(i);if(o===39||o===34||o===96){i=It(e,i,o);continue}if(o===40||o===91||o===123)r++;else if(o===41||o===93||o===125)r--;else if(o===43&&r===0)t.push(e.slice(n,i)),n=i+1;i++}return t.push(e.slice(n)),t}function xd(e){return e.slice(1,-1).replace(/\\(.)/g,(t,r)=>{if(r==="n")return`
|
|
124
|
+
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function Td(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Od(e){if(e==="")return!1;let t=!1,r=!1;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);if(i>=48&&i<=57){t=!0;continue}if(i===43||i===45||i===42||i===47||i===37){r=!0;continue}if(i===46||i===40||i===41||i<=32)continue;return!1}return t&&r}function Nl(e){let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=It(e,r,n)-1;continue}if(n===40||n===91||n===123){t++;continue}if(n===41||n===93||n===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((n===62||n===60)&&e.charCodeAt(r-1)!==61&&e.charCodeAt(r+1)!==61)return!0}return!1}function Rd(e,t=!1,r=0){return Ie(e,t,!0,r)}function hr(e,t=!1,r=""){let n=To(r),i=[],o=!1,s=0;while(s<e.length){let c=e.charCodeAt(s);if(c===34||c===39||c===96){s=It(e,s,c);continue}if(c===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10&&e.charCodeAt(s)!==13)s++;continue}if(c===47&&e.charCodeAt(s+1)===42){let f=e.indexOf("*/",s+2);s=f===-1?e.length:f+2;continue}if(e.startsWith("function",s)&&Mr(e,s,8)||e.startsWith("class",s)&&Mr(e,s,5)){let f=Md(e,s);if(f!==-1){s=Oo(e,f);continue}}if(c===61&&e.charCodeAt(s+1)===62){let f=s+2;while(f<e.length&&e.charCodeAt(f)<=32)f++;if(e.charCodeAt(f)===123){s=Oo(e,f);continue}}if(e.startsWith("return",s)&&(s===0||!At(e.charCodeAt(s-1)))&&!At(e.charCodeAt(s+6))){s+=6;let f=!1;while(s<e.length&&e.charCodeAt(s)<=32){let x=e.charCodeAt(s);if(x===10||x===13)f=!0;s++}if(f||s>=e.length||e.charCodeAt(s)===59||e.charCodeAt(s)===125){o=!0;continue}let u=s,h=0,l=0,y=0;while(s<e.length){let x=e.charCodeAt(s);if(x===34||x===39||x===96){s=It(e,s,x);continue}if(x===47&&e.charCodeAt(s+1)===47){if(h===0&&l===0&&y===0)break;while(s<e.length&&e.charCodeAt(s)!==10&&e.charCodeAt(s)!==13)s++;continue}if(x===47&&e.charCodeAt(s+1)===42){let v=e.indexOf("*/",s+2);s=v===-1?e.length:v+2;continue}if(x===40)h++;else if(x===41)h--;else if(x===91)l++;else if(x===93)l--;else if(x===123)y++;else if(x===125){if(y===0&&h===0&&l===0)break;y--}else if(x===59&&h===0&&l===0&&y===0)break;else if((x===10||x===13)&&h===0&&l===0&&y===0){let v=s+1;while(v<e.length&&e.charCodeAt(v)<=32)v++;if(e.startsWith("return",v)&&!At(e.charCodeAt(v+6)))break}s++}let C=e.slice(u,s).trim(),S=xo(Dt(C,n));if(!i.includes(S))i.push(S);continue}s++}if(o&&!i.includes("undefined"))i.push("undefined");let a=i.includes("unknown")?"unknown":i.length===0?"void":Ll(i);return t&&!a.startsWith("Promise<")?`Promise<${a}>`:a}function To(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=0,i=0,o=0;for(let s=0;s<=r.length;s++){let a=r.charCodeAt(s);if(a===40||a===91||a===123)i++;else if(a===41||a===93||a===125)i--;else if(a===60)o++;else if(a===62&&r.charCodeAt(s-1)!==61&&o>0)o--;if(s!==r.length&&(a!==44||i!==0||o!==0))continue;let c=r.slice(n,s).trim(),f=c.indexOf(":");if(f!==-1){let u=c.slice(0,f).trim().replace(/^\.\.\./,"").replace(/\?$/,""),h=c.slice(f+1).trim(),l=h.indexOf("=");if(l!==-1)h=h.slice(0,l).trim();if(Dr(u)&&h)t.set(u,h)}n=s+1}return t}function Dt(e,t){let r=e.trim();while(Wo(r))r=r.slice(1,-1).trim();if(Bi(r))return"JSX.Element";if(r.startsWith("await ")){let o=Dt(r.slice(6),t);return o.startsWith("Promise<")&&o.endsWith(">")?o.slice(8,-1):o}if(t.has(r))return t.get(r);if(r.startsWith("!"))return"boolean";if(r.startsWith("fetch("))return"Promise<Response>";if(Pd(r))return Ie(r,!1);let n=kd(r);if(n){let o=Dt(n.whenTrue,t),s=Dt(n.whenFalse,t);return o===s?o:Ll([o,s])}if(Nl(r))return"boolean";let i=0;for(let o=r.length-1;o>=0;o--){let s=r.charCodeAt(o);if(s===41||s===93||s===125)i++;else if(s===40||s===91||s===123)i--;else if(i===0&&(s===43||s===45||s===42||s===47||s===37)){let a=Dt(r.slice(0,o),t),c=Dt(r.slice(o+1),t);if(s===43&&(a==="string"||c==="string"))return"string";if(a==="number"&&c==="number")return"number";break}}return Ie(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(o)=>{let s=o.slice(7);return t.get(s)??"unknown"})}function Ll(e){return e.map((t)=>e.length>1&&dr(t)!==-1?`(${t})`:t).join(" | ")}function Pd(e){if(e.startsWith("function")&&Mr(e,0,8))return!0;let t=dr(e);if(t===-1)return!1;let r=e.slice(0,t).trim();if(r.startsWith("async")&&Mr(r,0,5))r=r.slice(5).trim();if(r.startsWith("<")){let i=Qe(r,0,"<",">");if(i===-1)return!1;r=r.slice(i+1).trim()}if(r.startsWith("(")){let i=Qe(r,0,"(",")");if(i===-1)return!1;let o=r.slice(i+1).trim();if(o&&!o.startsWith(":"))return!1}let n=Mo(r);return Wo(n.params)||Dr(n.params)}function Wo(e){if(!e.startsWith("(")||!e.endsWith(")"))return!1;let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===40)t++;else if(n===41&&--t===0)return r===e.length-1}return!1}function kd(e){let t=0,r=-1;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);if(i===40||i===91||i===123)t++;else if(i===41||i===93||i===125)t--;else if(i===63&&t===0&&e.charCodeAt(n+1)!==63)r=n;else if(i===58&&t===0&&r!==-1)return{whenTrue:e.slice(r+1,n),whenFalse:e.slice(n+1)}}return null}function Mr(e,t,r){return(t===0||!At(e.charCodeAt(t-1)))&&!At(e.charCodeAt(t+r))}function Md(e,t){for(let r=t;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=It(e,r,n)-1;continue}if(n===123)return r;if(n===59)return-1}return-1}function Oo(e,t){let r=1,n=t+1;while(n<e.length&&r>0){let i=e.charCodeAt(n);if(i===34||i===39||i===96){n=It(e,n,i);continue}if(i===47&&e.charCodeAt(n+1)===47){n+=2;while(n<e.length&&e.charCodeAt(n)!==10&&e.charCodeAt(n)!==13)n++;continue}if(i===47&&e.charCodeAt(n+1)===42){let o=e.indexOf("*/",n+2);n=o===-1?e.length:o+2;continue}if(i===123)r++;else if(i===125)r--;n++}return n}function It(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===92){n+=2;continue}if(r===96&&i===36&&e.charCodeAt(n+1)===123){n=Oo(e,n+1);continue}if(n++,i===r)break}return n}function Dd(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
|
|
125
|
+
`)||e.includes("\r"))return"string";return e}function Id(e){let t=4;while(t<e.length&&e.charCodeAt(t)<=32)t++;let r=t,n=e.charCodeAt(t);if(n<65||n>90)return"unknown";while(t<e.length&&(At(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let i=e.slice(r,t);{let o=e.slice(t),s=o;if(o.startsWith("<")){let c=0,f=-1;for(let u=0;u<o.length;u++)if(o[u]==="<")c++;else if(o[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=o.slice(0,f+1);s=o.slice(f+1);let h=s.indexOf("(");if(h!==-1){let l=0,y=-1;for(let C=h;C<s.length;C++)if(s[C]==="(")l++;else if(s[C]===")"){if(l--,l===0){y=C;break}}if(y!==-1){if(s.slice(y+1).trimStart().startsWith("."))return"unknown"}}return`${i}${u}`}}let a=s.indexOf("(");if(a!==-1){let c=0,f=-1;for(let u=a;u<s.length;u++)if(s[u]==="(")c++;else if(s[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(s.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(i){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 i}}return"unknown"}function Fd(e){return"{ new (...args: any[]): any }"}function Wl(e,t,r=0){if(e.startsWith("Promise.resolve(")){let n=e.indexOf(")",16);if(n!==-1){let i=e.slice(16,n).trim();if(i)return`Promise<${Ie(i,t,!1,r+1)}>`}return"Promise<unknown>"}if(e.startsWith("Promise.reject("))return"Promise<never>";if(e.startsWith("Promise.all(")){let n=e.indexOf("[",12),i=e.lastIndexOf("]");if(n!==-1&&i>n){let o=e.slice(n+1,i).trim(),s=ji(o),a=[];for(let c=0;c<s.length;c++){let f=s[c].trim();if(f.startsWith("Promise.resolve(")){let u=Wl(f,t,r+1),h=u.indexOf("<"),l=u.lastIndexOf(">");a.push(h!==-1&&l>h?u.slice(h+1,l):"unknown")}else a.push(Ie(f,t,!1,r+1))}return`Promise<[${a.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function Ro(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(r>=Io)return"unknown[]";let i=ji(n),o=!1;for(let l=0;l<i.length;l++){let y=i[l],C=y.length;while(C>0&&y.charCodeAt(C-1)<=32)C--;if(C>=8&&y.slice(C-8,C)==="as const"){o=!0;break}}if(o){let l=[];for(let y=0;y<i.length;y++){let C=i[y].trim();if(C.endsWith("as const")){let S=C.slice(0,-8).trim();if(S.startsWith("[")&&S.endsWith("]")){let x=S.slice(1,-1).trim(),v=ji(x),G=[];for(let L=0;L<v.length;L++)G.push(Ie(v[L].trim(),!0,!1,r+1));l.push(`readonly [${G.join(", ")}]`)}else l.push(Ie(S,!0,!1,r+1))}else if(C.startsWith("[")&&C.endsWith("]"))l.push(Ro(C,!0,r+1));else l.push(Ie(C,!0,!1,r+1))}return`readonly [
|
|
149
126
|
${l.join(` |
|
|
150
127
|
`)}
|
|
151
|
-
]`}let
|
|
152
|
-
`:"",x=C,v=!1;if(C==="..."){let
|
|
153
|
-
${x}: ${
|
|
128
|
+
]`}let s=_i&&!t,a=[],c=[];for(let l of i){let y=l.trim(),C=Xe;if(Xe=null,y.startsWith("...")){let S=y.slice(3).trim(),x=Ie(S,!1,!1,r+1);if(x.endsWith("[]"))a.push(x.slice(0,-2));else if(x.startsWith("readonly [")&&x.endsWith("]"))a.push(x.slice(10,-1));else if(ur(S))a.push(`(typeof ${S})[number]`);else a.push("unknown")}else if(y.startsWith("[")&&y.endsWith("]"))a.push(Ro(y,t,r+1));else a.push(Rd(y,t,r+1));if(s)c.push(Xe);Xe=C}if(s)if(ko(e))Xe=Gi(e);else{let l=[];for(let y=0;y<i.length;y++){let C=i[y].trim();if(C.endsWith("as const"))continue;if(Po(C)||C==="null"||C==="undefined")l.push(C);else if(C.startsWith("[")&&ko(C))l.push(Gi(C));else if(C.startsWith("{")){if(c[y])l.push(c[y])}else{let S=Ie(C,!1,!1,0);if(S!=="unknown")l.push(S)}}if(l.length>0)Xe=`[${l.join(", ")}]`}if(t)return`readonly [${a.join(", ")}]`;let f=new Set,u=[],h=!0;for(let l of a){if(!f.has(l))f.add(l),u.push(l);if(h){if(!(Lo(l)||l==="true"||l==="false"||l.charCodeAt(0)===34&&l.charCodeAt(l.length-1)===34||l.charCodeAt(0)===39&&l.charCodeAt(l.length-1)===39))h=!1}}if(h&&a.length<=10)return`readonly [${a.join(", ")}]`;if(u.length===1)return`${u[0]}[]`;return`(${u.join(" | ")})[]`}function ji(e){let t=[],r=0,n=0,i=!1,o=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(!i&&(c===34||c===39||c===96))i=!0,o=c;else if(i&&c===o&&(a===0||e.charCodeAt(a-1)!==92))i=!1;if(!i){if(c===91||c===123||c===40)n++;else if(c===93||c===125||c===41)n--;else if(c===44&&n===0){let f=e.substring(r,a).trim();if(f)t.push(f);r=a+1;continue}}}let s=e.substring(r).trim();if(s)t.push(s);return t}function Po(e){if(Lo(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function Nd(e){return e==="number"||e==="string"||e==="boolean"}function ko(e){let t=!1,r=0,n=e.length;for(let i=0;i<n;i++){let o=e.charCodeAt(i);if(t){if(o===92){i++;continue}if(o===r)t=!1;continue}if(o===34||o===39||o===96){t=!0,r=o;continue}if(o===61&&i+1<n&&e.charCodeAt(i+1)===62)return!1;if(o>=97&&o<=122){let s=i;while(i<n&&(e.charCodeAt(i)>=97&&e.charCodeAt(i)<=122||e.charCodeAt(i)>=65&&e.charCodeAt(i)<=90||e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57||e.charCodeAt(i)===95||e.charCodeAt(i)===36))i++;let a=e.slice(s,i);if(a==="new"||a==="async"||a==="await"||a==="function"||a==="yield"||a==="console"||a==="process")return!1;let c=i;while(c<n&&e.charCodeAt(c)<=32)c++;if(c<n&&e.charCodeAt(c)===40)return!1;i--}}return!0}function Ld(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"{}";if(r>=Io)return"Record<string, unknown>";let i=jd(n),o=[],s=[],a=_i&&!t,c=[];for(let[h,l]of i){let{comments:y,key:C}=jl(h),S=y?`${y}
|
|
129
|
+
`:"",x=C,v=!1;if(C==="..."){let U=l.trim(),H=ur(U)?`typeof ${U}`:Ie(U,t,!1,r+1);if(H!=="unknown")s.push(H);if(a&&(ur(U)||U.startsWith("{")))c.push(`...${Gi(U)}`);continue}let G=Xe;Xe=null;let L,P=l.trim();if(P===C&&Dr(P))L=`typeof ${P}`;else if(Ud(P)){v=!0;let U=Kd(C);if(U){x=U.name;let H="";if(P.startsWith("async "))H="async ";if(P.charCodeAt(H.length)===42)H+="*";L=Il(U.name,H+U.typeParams+P.slice(H.length))}else L=Il(C,P)}else{if(L=Ie(l,t,!1,r+1),L==="unknown"&&ur(P))L=`typeof ${P}`;if(L.includes("=>")||L.includes("function")||L.includes("async"))L=Ml(L)}let F=Xe;Xe=G;let I=l.trim(),k=_d(C);if(k){let U=Vd(k.kind,k.name,L);if(U){o.push(`${S}${U}`);continue}}if(!t&&Nd(L)&&Po(I))o.push(`${S}/** @defaultValue ${Do(I)} */
|
|
130
|
+
${x}: ${L}`);else o.push(`${S}${x}: ${L}`);if(a){let U=Fl(x);if(I.endsWith("as const"));else if(Po(I))c.push(`${U}: ${I}`);else if(I.startsWith("[")&&ko(I))c.push(`${U}: ${Gi(I)}`);else if(I.startsWith("{")){if(F)c.push(`${U}: ${F}`)}else if(v)c.push(`${U}: ${xo(Ml(L))}`);else if(!I.startsWith("[")&&(I.includes("=>")||I.startsWith("function")||I.startsWith("async"))){let H=_l(I,!1,0,!0);c.push(`${U}: ${xo(H)}`)}}}if(a&&c.length>0){let h=r>0?(r-1)/2:0,l=`{ ${c.join(", ")} }`;if(l.length<=80)Xe=l;else{let y=" ".repeat((h+1)*2),C=" ".repeat(h*2);Xe=`{
|
|
154
131
|
${y}${c.join(`,
|
|
155
132
|
${y}`)}
|
|
156
|
-
${C}}`}}let f=
|
|
157
|
-
${
|
|
133
|
+
${C}}`}}let f=o.length>0?`{
|
|
134
|
+
${o.join(`;
|
|
158
135
|
`)}
|
|
159
|
-
}`:"{}";if(
|
|
160
|
-
`).map((f)=>
|
|
161
|
-
`),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(!
|
|
162
|
-
`),key:e.slice(r).trim()}}function
|
|
163
|
-
`))I=I.slice(6).trimStart(),k="async ";if(I.startsWith("*"))I=I.slice(1).trimStart(),k+="*";n=F+I,r=k+
|
|
164
|
-
${n}`:n,n]);else if(n.startsWith("...")&&n.length>3)e.push(["...",n.slice(3).trim()])}function Xd(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 Qd(e,t,r){let n=r.trim();if(n.charCodeAt(0)!==40)return null;let i=it(n,0,"(",")");if(i===-1)return null;let s=n.slice(1,i).trim(),o=n.slice(i+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 ep(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 n=0;n<t.length;n++){let i=t.charCodeAt(n);if(i===40)r++;else if(i===41){if(r--,r===0){let s=t.slice(n+1).trimStart();if(s.startsWith("{"))return!0;if(s.startsWith(":")){let o=Ts(s,1);if(o?.kind==="arrow")return!1;if(o?.kind==="body")return!0}return!1}}}return!1}function tp(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let r=0,n=-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){n=s;break}}}if(n===-1)return null;let i=t.slice(0,n).trimEnd();if(!i)return null;return{name:i,typeParams:t.slice(n)}}function Hl(e,t){let r=t.trimStart(),n=!1,i=!1;if(r.startsWith("async ")||r.startsWith("async\t"))n=!0,r=r.slice(5).trimStart();if(r.startsWith("*"))i=!0,r=r.slice(1).trimStart();let s="";if(r.charCodeAt(0)===60){let l=0,y=-1;for(let C=0;C<r.length;C++)if(r.charCodeAt(C)===60)l++;else if(r.charCodeAt(C)===62&&!(C>0&&r.charCodeAt(C-1)===61)){if(l--,l===0){y=C;break}}if(y!==-1)s=r.slice(0,y+1),r=r.slice(y+1).trimStart()}let o=r.indexOf("("),a=it(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 l=u.slice(1),y=Ts(l,0);if(y)f=l.slice(0,y.index).trim();else f=l.trim()}if(f==="unknown"&&!i&&u.charCodeAt(0)===123){let l=it(u,0,"{","}");if(l!==-1){let y=hr(u.slice(1,l),n,c);if(y!=="unknown"&&y!=="Promise<unknown>")f=n&&y.startsWith("Promise<")?y.slice(8,-1):y;else if(n)f="Promise<unknown>"}}if(f==="unknown"){if(n&&i)f="AsyncGenerator<unknown, void, unknown>";else if(i)f="Generator<unknown, void, unknown>";else if(n)f="Promise<void>"}else if(n&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let h=_t(c);return`${s}${h} => ${f}`}function Ts(e,t){let r=0,n=0,i=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)n++;else if(f===93&&n>0)n--;else if(f===60)i++;else if(f===62&&i>0&&e.charCodeAt(c-1)!==61)i--;else if(f===125&&s>0)s--;else if(f===123){let u=r>0||n>0||i>0||s>0,h=e.slice(t,c).trimEnd(),l=h.charCodeAt(h.length-1),y=h.length===0||l===38||l===124||l===40||l===44||l===58||l===61||l===91;if(u||y)s++;else return{index:c,kind:"body"}}else if(f===61&&c+1<e.length&&e.charCodeAt(c+1)===62&&r===0&&n===0&&i===0&&s===0)return{index:c,kind:"arrow"}}return null}function it(e,t,r,n){let i=0;for(let s=t;s<e.length;s++)if(e[s]===r)i++;else if(e[s]===n){if(n===">"&&s>0&&e[s-1]==="=")continue;if(i--,i===0)return s}return-1}function Li(e){let t=0,r=0,n=!1,i="";for(let s=0;s<e.length-1;s++){let o=e[s],a=e[s+1],c=s>0?e[s-1]:"";if(!n&&(o==='"'||o==="'"||o==="`"))n=!0,i=o;else if(n&&o===i&&c!=="\\")n=!1;if(!n){if(o==="<"){let f=it(e,s,"<",">");if(f!==-1){s=f;continue}}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 ec(e,t=!1,r=0,n=!0){let i=e.trim();if(i.length>200&&ms(i,"=>")>2&&ms(i,"<")>5&&!i.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(i.startsWith("async ")&&i.includes("=>")){let o=i.slice(5).trim(),a=Li(o);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=o.substring(0,a).trim(),f=o.substring(a+2).trim(),u=Kl(c),{params:h,returnType:l}=u;if(h=_t(h),h==="()"||h==="")h="()";else if(!h.startsWith("("))h=`(${h})`;let y=l;if(y);else if(f.startsWith("{"))y=hr(f.slice(1,f.endsWith("}")?-1:void 0),!0,h);else y=Ie(f,n,!1,r+1);let C=`${h} => ${l||y.startsWith("Promise<")?y:`Promise<${y}>`}`;return t?`(${C})`:C}if(i.includes("=>")){let o="",a=i;if(i.startsWith("<")){let x=it(i,0,"<",">");if(x!==-1)o=i.substring(0,x+1),a=i.substring(x+1).trim()}let c=Li(a);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,c).trim(),u=a.substring(c+2).trim(),h=Kl(f),{params:l,returnType:y}=h;if(l=_t(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let C="unknown";if(y)C=y;else if(u.startsWith("{"))C=hr(u.slice(1,u.endsWith("}")?-1:void 0),!1,l);else if(Fi(u)||Jl(u)&&Fi(u.slice(1,-1).trim()))C="JSX.Element";else if(u.includes("=>")){let x=u.trimStart(),v=x.indexOf("("),B=v!==-1?it(x,v,"(",")"):-1,W=B!==-1?x.indexOf("=>",B):-1;if(v===0&&B!==-1&&W!==-1){let P=x.substring(v+1,B).trim(),F=_t(P);if(o.includes("T")&&F.includes("T"))C=`(${F}) => T`;else C=`(${F}) => any`}else C="any"}else if(t)C="unknown";else C=Bt(u,Yl(l));let S=`${o}${l} => ${C}`;return t?`(${S})`:S}if(i.startsWith("function")){let o=8,a=i.length;while(o<a&&i.charCodeAt(o)<=32)o++;let c=!1;if(o<a&&i.charCodeAt(o)===42){c=!0,o++;while(o<a&&i.charCodeAt(o)<=32)o++}let f="";if(o<a&&i.charCodeAt(o)===60){let l=o,y=1;o++;while(o<a&&y>0){let C=i.charCodeAt(o);if(C===60)y++;else if(C===62&&i.charCodeAt(o-1)!==61)y--;o++}f=i.substring(l,o);while(o<a&&i.charCodeAt(o)<=32)o++}let u=i.indexOf("(",o);if(u!==-1){let l=1,y=u+1;while(y<a&&l>0){let W=i.charCodeAt(y);if(W===40)l++;else if(W===41)l--;y++}let C=i.substring(u+1,y-1).trim(),S=C?_t(`(${C})`):"()";if(c){let W=i.substring(y).trim(),P=W.indexOf("Generator<");if(P!==-1){let I=P+10,k=W.indexOf(">",I);if(k!==-1){let H=W.substring(I,k),j=`${f}${S} => Generator<${H}>`;return t?`(${j})`:j}}let F=`${f}${S} => Generator<any, any, any>`;return t?`(${F})`:F}let x="unknown",v=i.substring(y).trimStart();if(v.charCodeAt(0)===58){let W=v.slice(1),P=Ts(W,0),F=(P?W.slice(0,P.index):W).trim();if(F)x=F}let B=`${f}${S} => ${x}`;return t?`(${B})`:B}let h="(...args: any[]) => unknown";return t?`(${h})`:h}if(i.includes("=>")&&i.includes("(")&&i.includes(")")){if(i.length>100||ms(i,"=>")>2){let o="";if(i.charCodeAt(0)===60){let h=it(i,0,"<",">");if(h!==-1)o=i.substring(0,h+1)}let a=i.indexOf("("),c=a!==-1?it(i,a,"(",")"):-1,f=a!==-1&&c!==-1?i.substring(a,c+1):"(...args: any[])";f=_t(f);let u=`${o}${f} => any`;return t?`(${u})`:u}return t?`(${i})`:i}let s="() => unknown";return t?`(${s})`:s}function Kl(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=it(t,0,"(",")");if(r===-1)return{params:t,returnType:""};let n=t.slice(r+1).trim();return{params:t.slice(0,r+1),returnType:n.startsWith(":")?n.slice(1).trim():""}}function tc(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 _i(e){let t=-1,r=0;for(let i=0;i<e.length;i++){let s=e.charCodeAt(i);if(s===34||s===39||s===96){i=Nt(e,i,s)-1;continue}if(s===47&&e.charCodeAt(i+1)===47){while(i<e.length&&e.charCodeAt(i)!==10)i++;continue}if(s===47&&e.charCodeAt(i+1)===42){let o=e.indexOf("*/",i+2);i=o===-1?e.length:o+1;continue}if(s===47){let o=i-1;while(o>=0&&e.charCodeAt(o)<=32)o--;if(o<0||"([{:;,=!?&|+*-~>".includes(e[o])){let a=!1;for(i++;i<e.length;i++){let c=e.charCodeAt(i);if(c===92)i++;else if(c===91)a=!0;else if(c===93)a=!1;else if(c===47&&!a)break}continue}}if(s===40||s===91||s===123)r++;else if(s===41||s===93||s===125)r--;else if(r===0&&e.startsWith("satisfies",i)&&ys(e,i,9)&&e[i-1]!==".")t=i}if(t===-1)return null;let n=e.slice(t+9).trim();if(n.endsWith(";"))n=n.slice(0,-1).trim();return n||null}var Es=20,Gi=!1,Qe=null;var Os=()=>{};function sp(e){let t=[],r=0;for(let n=0;n<=e.length;n++)if(n===e.length||e[n]===`
|
|
165
|
-
|
|
136
|
+
}`:"{}";if(s.length===0)return f;let u=s[0];for(let h=1;h<s.length;h++)u=`Omit<${u}, keyof ${s[h]}> & ${s[h]}`;return o.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function Dr(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(!At(e.charCodeAt(r)))return!1;return!0}function ur(e){let t=e.split(".");return t.length>0&&t.every(Dr)}function Wd(e){let t=!1,r="";for(let n=0;n<e.length;n++){let i=e[n];if(t){if(i==="\\")n++;else if(i===r)t=!1;continue}if(i==='"'||i==="'"||i==="`"){t=!0,r=i;continue}if(i==="(")return n;if(i==="<"){let o=Qe(e,n,"<",">");if(o!==-1)n=o}}return-1}function Bl(e){if(e.length<3||!e.endsWith(")"))return null;let t=Wd(e);if(t===-1||Qe(e,t,"(",")")!==e.length-1)return null;let r=e.slice(0,t).trim(),n=!1;if(r.endsWith("?."))n=!0,r=r.slice(0,-2).trim();let i=r,o=!1,s=r.indexOf("<");if(s!==-1){if(Qe(r,s,"<",">")!==r.length-1)return null;i=r.slice(0,s).trim(),o=!0}if(!ur(i))return null;let a=e.slice(t+1,-1).trim(),c=dr(a)!==-1||a.startsWith("function")||a.startsWith("async function"),f=ur(a),u=!c&&a.endsWith(")")&&Bl(a)!==null;if(!o&&!n&&!c&&!f&&!u)return null;let h=`ReturnType<typeof ${r}>`;return n?`${h} | undefined`:h}function Ml(e){let t=e.split(`
|
|
137
|
+
`).map((f)=>Gl(f)).join(`
|
|
138
|
+
`),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(!At(f)&&!At(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let n=t.indexOf("(");if(n!==-1){let f=Qe(t,n,"(",")");if(f!==-1){let u=t.slice(n,f+1),h=Gt(u);t=t.slice(0,n)+h+t.slice(f+1)}}let i=t.length,o="",s=[],a=!1,c=!1;for(let f=0;f<i;f++){let u=t.charCodeAt(f);if(u===123||u===40)s.push(u);else if(u===125||u===41)s.pop();if(u<=32){if(a=!0,u===10||u===13)c=!0;continue}if(a&&o.length>0){let h=(s.length>0?s[s.length-1]:0)===123;if(c&&h){let l=o.charCodeAt(o.length-1),y=l===59||l===44||l===123||u===125,C=o.length>=2&&o.charCodeAt(o.length-1)===47&&o.charCodeAt(o.length-2)===42;if(!y&&!C)o+="; ";else o+=" "}else o+=" "}a=!1,c=!1,o+=t[f]}return o.trim()}function At(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Gt(e){let t=e.trim(),r,n=!1;if(t.startsWith("(")&&t.endsWith(")"))r=t.slice(1,-1),n=!0;else r=t;let i=r.trim();if(!i)return n?"()":"";let o=!1;{let C=0;for(let S=0;S<i.length;S++){let x=i.charCodeAt(S);if(x===40||x===60||x===91||x===123)C++;else if(x===41||x===93||x===125||x===62&&i.charCodeAt(S-1)!==61)C--;else if(C===0&&x===61){let v=S>0?i.charCodeAt(S-1):0,G=S+1<i.length?i.charCodeAt(S+1):0;if(v!==61&&v!==33&&v!==60&&v!==62&&G!==61&&G!==62){o=!0;break}}}}if(!o)return t;let s=[],a=[],c=0,f=0,u=!1,h=0;for(let C=0;C<=i.length;C++){if(C===i.length){s.push(i.slice(c));break}let S=i.charCodeAt(C);if(u){if(S===92){C++;continue}if(S===h)u=!1;continue}if(S===47&&C+1<i.length){let x=i.charCodeAt(C+1);if(x===42){C+=2;while(C+1<i.length&&!(i.charCodeAt(C)===42&&i.charCodeAt(C+1)===47))C++;C++;continue}if(x===47){while(C<i.length&&i.charCodeAt(C)!==10)C++;continue}}if(S===39||S===34||S===96){u=!0,h=S;continue}if(S===40||S===60||S===91||S===123)f++;else if(S===41||S===93||S===125||S===62&&i.charCodeAt(C-1)!==61)f--;else if(S===44&&f===0){s.push(i.slice(c,C));let x=",",v=C+1;while(v<i.length&&i.charCodeAt(v)<=32)x+=i[v],v++;a.push(x),c=v}}let l=[];for(let C of s){let S=C.trim();if(!S){l.push(C);continue}if(S.startsWith("//"))continue;let x=Gl(S),v=C.slice(0,C.length-C.trimStart().length);l.push(v+Bd(x))}let y=l[0]||"";for(let C=1;C<l.length;C++)y+=(a[C-1]||", ")+l[C];return n?`(${y})`:y}function Gl(e){let t=!1,r=0;for(let n=0;n<e.length-1;n++){let i=e.charCodeAt(n);if(t){if(i===92){n++;continue}if(i===r)t=!1;continue}if(i===39||i===34||i===96){t=!0,r=i;continue}if(i===47&&e.charCodeAt(n+1)===47)return e.slice(0,n).trimEnd()}return e}function Bd(e){if(e.startsWith("..."))return e;let t=-1,r=-1,n=0,i=!1,o=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(i){if(c===92){a++;continue}if(c===o)i=!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){i=!0,o=c;continue}if(c===40||c===60||c===91||c===123)n++;else if(c===41||c===93||c===125||c===62&&e.charCodeAt(a-1)!==61)n--;else if(n===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 s=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=s&&!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 Gd(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 jl(e){let t=[],r=0,n=e.length;while(r<n){while(r<n&&e.charCodeAt(r)<=32)r++;if(r+1>=n||e.charCodeAt(r)!==47||e.charCodeAt(r+1)!==42)break;let i=r;r+=2;while(r+1<n&&!(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47))r++;r=Math.min(r+2,n),t.push(e.slice(i,r).trim())}return{comments:t.join(`
|
|
139
|
+
`),key:e.slice(r).trim()}}function jd(e){let t=[],r="",n="",i=0,o=!1,s="",a=!0,c=!1,f=0,u=!1,h=!1,l=0,y=!1,C=!1;for(let S=0;S<e.length;S++){let x=e.charCodeAt(S),v=S>0?e.charCodeAt(S-1):0,G=S<e.length-1?e.charCodeAt(S+1):0;if(!o&&!c&&x===47&&G===47){r=r.replace(/[ \t]+$/,""),S+=2;while(S<e.length&&e.charCodeAt(S)!==10)S++;S--;continue}if(!o&&!c&&x===47&&G===42){c=!0,f=1,r+="/*",S++;continue}else if(c&&x===42&&G===47){if(f--,r+="*/",S++,f===0)c=!1;continue}else if(c&&x===47&&G===42){f++,r+="/*",S++;continue}let L=e[S];if(!o&&!c&&(x===34||x===39||x===96))o=!0,s=L,r+=L;else if(o&&L===s&&v!==92)o=!1,r+=L;else if(!o&&!c)if(x===40&&i===0&&a&&l===0){n=r.trim();let P=Gd(n),F=P>0?n.slice(0,P):"",I=n.slice(P),k="";if(I.startsWith("async ")||I.startsWith("async\t")||I.startsWith(`async
|
|
140
|
+
`))I=I.slice(6).trimStart(),k="async ";if(I.startsWith("*"))I=I.slice(1).trimStart(),k+="*";n=F+I,r=k+L,a=!1,y=!0,C=!1,i=1}else if(x===123||x===91||x===40){if(i++,r+=L,C&&x===123)C=!1}else if(x===125||x===93||x===41){if(i--,r+=L,x===41&&i===0&&!a&&!y)u=!0;if(y){if(x===41&&i===0&&!C)C=!0;else if(x===125&&i===0)y=!1,C=!1}}else if(x===58&&i===0&&a&&l===0)n=r.trim(),r="",a=!1;else if(x===58&&i===0&&u)h=!0,r+=L;else if(x===60&&h)l++,r+=L;else if(x===60&&a&&i===0)l++,r+=L;else if(x===62&&l>0&&v!==61)l--,r+=L;else if(x===61&&G===62&&h&&l===0)h=!1,u=!1,r+=L;else if(x===44&&i===0&&l===0&&!C){if(n&&r.trim()){let P=r.trim();t.push([n,P])}else if(a&&r.trim())Dl(t,r.trim());r="",n="",a=!0,u=!1,h=!1,l=0}else r+=L;else r+=L}if(n&&r.trim()){let S=r.trim();t.push([n,S])}else if(a&&r.trim())Dl(t,r.trim());return t}function Dl(e,t){let{comments:r,key:n}=jl(t);if(Dr(n))e.push([r?`${r}
|
|
141
|
+
${n}`:n,n]);else if(n.startsWith("...")&&n.length>3)e.push(["...",n.slice(3).trim()])}function _d(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 Vd(e,t,r){let n=r.trim();if(n.charCodeAt(0)!==40)return null;let i=Qe(n,0,"(",")");if(i===-1)return null;let o=n.slice(1,i).trim(),s=n.slice(i+1).trimStart();if(!s.startsWith("=>"))return null;let a=s.slice(2).trim();if(e==="get")return`get ${t}(): ${a||"unknown"}`;return`set ${t}(${o})`}function Ud(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 n=0;n<t.length;n++){let i=t.charCodeAt(n);if(i===40)r++;else if(i===41){if(r--,r===0){let o=t.slice(n+1).trimStart();if(o.startsWith("{"))return!0;if(o.startsWith(":")){let s=Bo(o,1);if(s?.kind==="arrow")return!1;if(s?.kind==="body")return!0}return!1}}}return!1}function Kd(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let r=0,n=-1;for(let o=t.length-1;o>=0;o--){let s=t.charCodeAt(o);if(s===62){if(o>0&&t.charCodeAt(o-1)===61)continue;r++}else if(s===60){if(r--,r===0){n=o;break}}}if(n===-1)return null;let i=t.slice(0,n).trimEnd();if(!i)return null;return{name:i,typeParams:t.slice(n)}}function Il(e,t){let r=t.trimStart(),n=!1,i=!1;if(r.startsWith("async ")||r.startsWith("async\t"))n=!0,r=r.slice(5).trimStart();if(r.startsWith("*"))i=!0,r=r.slice(1).trimStart();let o="";if(r.charCodeAt(0)===60){let l=0,y=-1;for(let C=0;C<r.length;C++)if(r.charCodeAt(C)===60)l++;else if(r.charCodeAt(C)===62&&!(C>0&&r.charCodeAt(C-1)===61)){if(l--,l===0){y=C;break}}if(y!==-1)o=r.slice(0,y+1),r=r.slice(y+1).trimStart()}let s=r.indexOf("("),a=Qe(r,s,"(",")");if(s===-1||a===-1)return"() => unknown";let c=r.slice(s,a+1),f="unknown",u=r.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let l=u.slice(1),y=Bo(l,0);if(y)f=l.slice(0,y.index).trim();else f=l.trim()}if(f==="unknown"&&!i&&u.charCodeAt(0)===123){let l=Qe(u,0,"{","}");if(l!==-1){let y=hr(u.slice(1,l),n,c);if(y!=="unknown"&&y!=="Promise<unknown>")f=n&&y.startsWith("Promise<")?y.slice(8,-1):y;else if(n)f="Promise<unknown>"}}if(f==="unknown"){if(n&&i)f="AsyncGenerator<unknown, void, unknown>";else if(i)f="Generator<unknown, void, unknown>";else if(n)f="Promise<void>"}else if(n&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let h=Gt(c);return`${o}${h} => ${f}`}function Bo(e,t){let r=0,n=0,i=0,o=0,s=!1,a=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(s){if(f===92)c++;else if(f===a)s=!1;continue}if(f===34||f===39||f===96){s=!0,a=f;continue}if(f===40)r++;else if(f===41&&r>0)r--;else if(f===91)n++;else if(f===93&&n>0)n--;else if(f===60)i++;else if(f===62&&i>0&&e.charCodeAt(c-1)!==61)i--;else if(f===125&&o>0)o--;else if(f===123){let u=r>0||n>0||i>0||o>0,h=e.slice(t,c).trimEnd(),l=h.charCodeAt(h.length-1),y=h.length===0||l===38||l===124||l===40||l===44||l===58||l===61||l===91;if(u||y)o++;else return{index:c,kind:"body"}}else if(f===61&&c+1<e.length&&e.charCodeAt(c+1)===62&&r===0&&n===0&&i===0&&o===0)return{index:c,kind:"arrow"}}return null}function Qe(e,t,r,n){let i=0;for(let o=t;o<e.length;o++)if(e[o]===r)i++;else if(e[o]===n){if(n===">"&&o>0&&e[o-1]==="=")continue;if(i--,i===0)return o}return-1}function dr(e){let t=0,r=0,n=!1,i="";for(let o=0;o<e.length-1;o++){let s=e[o],a=e[o+1],c=o>0?e[o-1]:"";if(!n&&(s==='"'||s==="'"||s==="`"))n=!0,i=s;else if(n&&s===i&&c!=="\\")n=!1;if(!n){if(s==="<"){let f=Qe(e,o,"<",">");if(f!==-1){o=f;continue}}if(s==="(")t++;else if(s===")")t--;else if(s==="[")r++;else if(s==="]")r--;if(s==="="&&a===">"&&t===0&&r===0)return o}}return-1}function _l(e,t=!1,r=0,n=!0){let i=e.trim();if(i.length>200&&Ao(i,"=>")>2&&Ao(i,"<")>5&&!i.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(i.startsWith("async ")&&i.includes("=>")){let s=i.slice(5).trim(),a=dr(s);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=s.substring(0,a).trim(),f=s.substring(a+2).trim(),u=Mo(c),{params:h,returnType:l}=u;if(h=Gt(h),h==="()"||h==="")h="()";else if(!h.startsWith("("))h=`(${h})`;let y=l;if(y);else if(f.startsWith("{"))y=hr(f.slice(1,f.endsWith("}")?-1:void 0),!0,h);else y=Dt(f,To(h));let C=`${h} => ${l||y.startsWith("Promise<")?y:`Promise<${y}>`}`;return t?`(${C})`:C}if(i.includes("=>")){let s="",a=i;if(i.startsWith("<")){let x=Qe(i,0,"<",">");if(x!==-1)s=i.substring(0,x+1),a=i.substring(x+1).trim()}let c=dr(a);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,c).trim(),u=a.substring(c+2).trim(),h=Mo(f),{params:l,returnType:y}=h;if(l=Gt(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let C="unknown";if(y)C=y;else if(u.startsWith("{"))C=hr(u.slice(1,u.endsWith("}")?-1:void 0),!1,l);else if(Bi(u)||Wo(u)&&Bi(u.slice(1,-1).trim()))C="JSX.Element";else if(u.includes("=>")){let x=u.trimStart(),v=x.indexOf("("),G=v!==-1?Qe(x,v,"(",")"):-1,L=G!==-1?x.indexOf("=>",G):-1;if(v===0&&G!==-1&&L!==-1){let P=x.substring(v+1,G).trim(),F=Gt(P);if(s.includes("T")&&F.includes("T"))C=`(${F}) => T`;else C=`(${F}) => any`}else C="any"}else if(t)C="unknown";else C=Dt(u,To(l));let S=`${s}${l} => ${C}`;return t?`(${S})`:S}if(i.startsWith("function")){let s=8,a=i.length;while(s<a&&i.charCodeAt(s)<=32)s++;let c=!1;if(s<a&&i.charCodeAt(s)===42){c=!0,s++;while(s<a&&i.charCodeAt(s)<=32)s++}let f="";if(s<a&&i.charCodeAt(s)===60){let l=s,y=1;s++;while(s<a&&y>0){let C=i.charCodeAt(s);if(C===60)y++;else if(C===62&&i.charCodeAt(s-1)!==61)y--;s++}f=i.substring(l,s);while(s<a&&i.charCodeAt(s)<=32)s++}let u=i.indexOf("(",s);if(u!==-1){let l=1,y=u+1;while(y<a&&l>0){let L=i.charCodeAt(y);if(L===40)l++;else if(L===41)l--;y++}let C=i.substring(u+1,y-1).trim(),S=C?Gt(`(${C})`):"()";if(c){let L=i.substring(y).trim(),P=L.indexOf("Generator<");if(P!==-1){let I=P+10,k=L.indexOf(">",I);if(k!==-1){let U=L.substring(I,k),H=`${f}${S} => Generator<${U}>`;return t?`(${H})`:H}}let F=`${f}${S} => Generator<any, any, any>`;return t?`(${F})`:F}let x="unknown",v=i.substring(y).trimStart();if(v.charCodeAt(0)===58){let L=v.slice(1),P=Bo(L,0),F=(P?L.slice(0,P.index):L).trim();if(F)x=F}let G=`${f}${S} => ${x}`;return t?`(${G})`:G}let h="(...args: any[]) => unknown";return t?`(${h})`:h}if(i.includes("=>")&&i.includes("(")&&i.includes(")")){if(i.length>100||Ao(i,"=>")>2){let s="";if(i.charCodeAt(0)===60){let h=Qe(i,0,"<",">");if(h!==-1)s=i.substring(0,h+1)}let a=i.indexOf("("),c=a!==-1?Qe(i,a,"(",")"):-1,f=a!==-1&&c!==-1?i.substring(a,c+1):"(...args: any[])";f=Gt(f);let u=`${s}${f} => any`;return t?`(${u})`:u}return t?`(${i})`:i}let o="() => unknown";return t?`(${o})`:o}function Mo(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=Qe(t,0,"(",")");if(r===-1)return{params:t,returnType:""};let n=t.slice(r+1).trim();return{params:t.slice(0,r+1),returnType:n.startsWith(":")?n.slice(1).trim():""}}function Vl(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 Vi(e){let t=-1,r=0;for(let i=0;i<e.length;i++){let o=e.charCodeAt(i);if(o===34||o===39||o===96){i=It(e,i,o)-1;continue}if(o===47&&e.charCodeAt(i+1)===47){while(i<e.length&&e.charCodeAt(i)!==10)i++;continue}if(o===47&&e.charCodeAt(i+1)===42){let s=e.indexOf("*/",i+2);i=s===-1?e.length:s+1;continue}if(o===47){let s=i-1;while(s>=0&&e.charCodeAt(s)<=32)s--;if(s<0||"([{:;,=!?&|+*-~>".includes(e[s])){let a=!1;for(i++;i<e.length;i++){let c=e.charCodeAt(i);if(c===92)i++;else if(c===91)a=!0;else if(c===93)a=!1;else if(c===47&&!a)break}continue}}if(o===40||o===91||o===123)r++;else if(o===41||o===93||o===125)r--;else if(r===0&&e.startsWith("satisfies",i)&&Mr(e,i,9)&&e[i-1]!==".")t=i}if(t===-1)return null;let n=e.slice(t+9).trim();if(n.endsWith(";"))n=n.slice(0,-1).trim();return n||null}var Io=20,_i=!1,Xe=null;var Go=()=>{};function _e(e){return e===Me||e===De||e===ve||e===xe}function Jd(e){let t=!0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===gt){if(t)return!1;t=!0}else if(t){if(!yt(n))return!1;t=!1}else if(!Ue(n))return!1}return e.length>0&&!t}function Ki(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===nt){n+=2;continue}if(n++,i===r)break}return n}function qd(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 Hl(e,t,r=!0){return Jl(e,t,r,!0)}function zl(e,t,r=!0){return Jl(e,t,r,!1)}function Jl(e,t,r,n){let i=e,o=r,s=n,a=i.length,c=[],f=new Map,u=new Map,h=new Set,l=0;function y(d){let p=u.get(d.name);if(p)p.push(d);else u.set(d.name,[d]);f.set(d.name,d)}if(l<a&&i.charCodeAt(l)===65279)l++;function C(d,p){if(d<p){let m=i.charCodeAt(d),g=i.charCodeAt(p-1);if(m!==Me&&m!==De&&m!==ve&&m!==xe&&g!==Me&&g!==De&&g!==ve&&g!==xe)return i.slice(d,p)}while(d<p&&_e(i.charCodeAt(d)))d++;while(p>d&&_e(i.charCodeAt(p-1)))p--;return i.slice(d,p)}let S=/[\r\n]/g;function x(d){return S.lastIndex=d,S.exec(i)?.index??a}function v(){if(l>=a)return;let d=i.charCodeAt(l);if(d!==Me&&d!==De&&d!==ve&&d!==xe&&d!==ee)return;while(l<a){let p=i.charCodeAt(l);if(p===Me||p===De||p===ve||p===xe){l++;continue}if(p===ee&&l+1<a){let m=i.charCodeAt(l+1);if(m===ee){l=x(l+2);continue}if(m===Ae){let g=i.indexOf("*/",l+2);l=g===-1?a:g+2;continue}}break}}function G(d){let p=d.length,m=0,g=p;for(let w=0;w<p;w++){let b=d.charCodeAt(w);if(m){if(b===nt){w++;continue}if(b===m)m=0;continue}if(b===le||b===fe||b===Fe){m=b;continue}if(b===ee&&w+1<p){let T=d.charCodeAt(w+1);if(T===ee){g=w;while(g>0&&(d.charCodeAt(g-1)===Me||d.charCodeAt(g-1)===De))g--;return d.slice(0,g)}if(T===Ae){let R=d.indexOf("*/",w+2);if(R!==-1){d=`${d.slice(0,w)} ${d.slice(R+2)}`,w--;continue}}}}g=p;while(g>0&&(d.charCodeAt(g-1)===Me||d.charCodeAt(g-1)===De||d.charCodeAt(g-1)===xe))g--;return g<p?d.slice(0,g):d}function L(d){l++;let p=d===le?"'":'"';while(l<a){let m=i.indexOf(p,l);if(m===-1){l=a;return}let g=0,w=m-1;while(w>=0&&i.charCodeAt(w)===nt)g++,w--;if(g%2===0){l=m+1;return}l=m+1}}function P(){l++;let d=[];while(l<a){let p=i.charCodeAt(l);if(d.length===0){if(p===nt){l+=2;continue}if(p===Fe){l++;return}if(p===zd&&l+1<a&&i.charCodeAt(l+1)===J){l+=2,d.push(0);continue}l++;continue}if(p===le||p===fe){L(p);continue}if(p===Fe){P();continue}if(p===ee&&l+1<a){let m=i.charCodeAt(l+1);if(m===ee){l=x(l+2);continue}if(m===Ae){let g=i.indexOf("*/",l+2);l=g===-1?a:g+2;continue}if(k()){U();continue}l++;continue}if(p===J){d[d.length-1]++,l++;continue}if(p===Q){let m=d[d.length-1];if(m===0){d.pop(),l++;continue}d[d.length-1]=m-1,l++;continue}l++}}let F=!1;function I(){F=!1;let d=i.charCodeAt(l);if(d===le||d===fe)return L(d),!0;if(d===Fe)return P(),!0;if(d===ee&&l+1<a){let p=i.charCodeAt(l+1);if(p===ee)return l=x(l+2),!0;if(p===Ae){let m=i.indexOf("*/",l+2);return F=x(l+2)<(m===-1?a:m),l=m===-1?a:m+2,!0}if(k())return U(),!0}return!1}function k(){return Hr(i,l)}function U(){l=gr(i,l)}function H(){let d=l;while(l<a&&Ue(i.charCodeAt(l)))l++;return i.slice(d,l)}function O(d){if(l+d.length>a)return!1;for(let p=0;p<d.length;p++)if(i.charCodeAt(l+p)!==d.charCodeAt(p))return!1;if(l+d.length<a&&Ue(i.charCodeAt(l+d.length)))return!1;return!0}function z(d){let p=l+d;while(p<a){let m=i.charCodeAt(p);if(m===Me||m===De||m===ve||m===xe){p++;continue}return m!==gt&&m!==be}return!1}function pe(){if(!F)return!1;let d=l;v();let p=l>=a||Oe()||i.charCodeAt(l)===Q;return l=d,p}function Oe(){if(l>=a)return!1;switch(i.charCodeAt(l)){case 101:return O("export")||O("enum");case 105:return O("import")||O("interface");case 102:return O("function");case 99:return O("class")||O("const");case 116:return O("type");case 108:return O("let");case 118:return O("var");case 100:return O("declare")||O("default");case 109:return O("module");case 110:return O("namespace");case 97:return O("abstract")||O("async");default:return!1}}function ie(){let d=i.charCodeAt(l);if(d!==ve&&d!==xe)return!1;let p=l;if(l++,d===xe&&l<a&&i.charCodeAt(l)===ve)l++;while(l<a){let g=i.charCodeAt(l);if(g===Me||g===De||g===xe||g===ve){l++;continue}if(g===ee&&l+1<a){let w=i.charCodeAt(l+1);if(w===ee){l=x(l+2);continue}if(w===Ae){let b=i.indexOf("*/",l+2);l=b===-1?a:b+2;continue}}break}let m=l>=a||Oe()||i.charCodeAt(l)===Q;return l=p,m}function ne(d){let p=d-1;while(p>=0){let E=i.charCodeAt(p);if(E===Me||E===De||E===xe||E===ve){p--;continue}break}if(p<0)return!0;let m=i[p];if("+-*/%=<>&|^!~?:,.([{".includes(m))return!0;let g=p;while(g>0&&i.charCodeAt(g-1)!==ve)g--;let w=i.slice(g,p+1),b=w.lastIndexOf("<");if(b!==-1&&/^<[A-Za-z]/.test(w.slice(b))&&!w.slice(b).includes(">"))return!0;let T=p;while(T>=0&&/[a-z]/i.test(i[T]))T--;let R=i.slice(T+1,p+1);return["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(R)}function ue(){let d=i.charCodeAt(l);if(d!==ve&&d!==xe)return!1;if(ne(l))return!1;let p=l;l++;while(l<a){let b=i.charCodeAt(l);if(b===Me||b===De||b===xe||b===ve){l++;continue}if(b===ee&&l+1<a){let T=i.charCodeAt(l+1);if(T===ee){l=x(l+2);continue}if(T===Ae){let R=i.indexOf("*/",l+2);l=R===-1?a:R+2;continue}}break}let m=l<a?i[l]:"",g=i.slice(l,l+2),w=m==="."||m==="?"||m===":"||m===")"||m==="]"||m==="}"||m===","||m==="+"||m==="-"||m==="*"||m==="/"||m==="%"||m==="<"||m===">"||m==="="||m==="&"||m==="|"||m==="^"||m==="`"||g==="=>"||O("as")||O("satisfies")||O("instanceof")||O("in");return l=p,!w}function se(){let d=i.charCodeAt(l);if(d!==ve&&d!==xe)return!1;if(ne(l))return!1;let p=l;l++;while(l<a){let w=i.charCodeAt(l);if(w===Me||w===De||w===xe||w===ve){l++;continue}if(w===ee&&l+1<a){let b=i.charCodeAt(l+1);if(b===ee){l=x(l+2);continue}if(b===Ae){let T=i.indexOf("*/",l+2);l=T===-1?a:T+2;continue}}break}let m=l<a?i[l]:"",g=m==="|"||m==="&"||m==="["||m==="."||m==="?"||m===":"||m===">"||m===")"||m===","||O("extends");return l=p,!g}function W(){let d=i.charCodeAt(l);if(d!==ve&&d!==xe)return!1;let p=l;if(l++,d===xe&&l<a&&i.charCodeAt(l)===ve)l++;while(l<a){let g=i.charCodeAt(l);if(g===Me||g===De||g===xe||g===ve){l++;continue}if(g===ee&&l+1<a&&i.charCodeAt(l+1)===ee){l=x(l+2);continue}break}if(l>=a)return l=p,!0;let m=i.charCodeAt(l);if(m===124||m===38||m===gt||m===Ui||m===ft)return l=p,!1;if(O("extends")||O("keyof")||O("typeof")||O("infer")||O("is")||O("as")||O("in"))return l=p,!1;return l=p,!0}let K=/[{}'"`\/]/g,q=/[()'"`\/]/g,Z=/[[\]'"`\/]/g,te=/[<>'"`\/]/g;function X(d,p){let m=1;l++;let g=d===J?K:d===ae?q:d===$e?Z:te;g.lastIndex=l;let w;while((w=g.exec(i))!==null){let b=w.index,T=i.charCodeAt(b);if(T===le||T===fe){l=b,L(T),g.lastIndex=l;continue}if(T===Fe){l=b,P(),g.lastIndex=l;continue}if(T===ee){if(l=b,I()){g.lastIndex=l;continue}g.lastIndex=b+1;continue}if(T===d)m++;else if(T===p){if(p===me&&b>0&&i.charCodeAt(b-1)===be){g.lastIndex=b+1;continue}if(m--,m===0)return l=b+1,l}g.lastIndex=b+1}return l=a,l}function oe(){return l>0&&i.charCodeAt(l-1)===be}function Ge(){return l+1<a&&i.charCodeAt(l+1)===me}let Ve=/[<{};'"`\/\n\r()[\]]/g;function Re(d=!1){let p=0,m=0,g=0,w=0,b=i.charCodeAt(l)===J;Ve.lastIndex=l;let T;while((T=Ve.exec(i))!==null){let R=T.index,E=i.charCodeAt(R);if(E===le||E===fe){l=R,L(E),Ve.lastIndex=l;continue}if(E===Fe){l=R,P(),Ve.lastIndex=l;continue}if(E===ee){if(R>0&&i.charCodeAt(R-1)===we){Ve.lastIndex=R+1;continue}if(l=R,I()){if(p===0&&m===0&&g===0&&w===0&&pe())return;Ve.lastIndex=l;continue}Ve.lastIndex=R+1;continue}if(E===we){let A=ns(R);if(A!==null)w=Math.max(0,w+A);Ve.lastIndex=R+1;continue}if(E===ae){m++,Ve.lastIndex=R+1;continue}if(E===Se){m--,Ve.lastIndex=R+1;continue}if(E===$e){g++,Ve.lastIndex=R+1;continue}if(E===ke){g--,Ve.lastIndex=R+1;continue}if(E===J){p++,Ve.lastIndex=R+1;continue}if(E===Q){let A=p>0;if(!A&&d&&m===0&&g===0&&w===0){l=R;return}if(A)p--;if((!A||b)&&p===0&&m===0&&g===0&&w===0){l=R+1;return}Ve.lastIndex=R+1;continue}if(E===re&&p===0&&m===0&&g===0&&w===0){l=R+1;return}if((E===ve||E===xe)&&p===0&&m===0&&g===0&&w===0){if(l=R,ie())return}Ve.lastIndex=R+1}l=a}function Zc(){l++;while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;let d=i.indexOf(`
|
|
142
|
+
`,l),p=d===-1?a:d,m=i.indexOf(";",l);if(m!==-1&&m<p){let g=m-1;while(g>=l&&(i.charCodeAt(g)===Me||i.charCodeAt(g)===De))g--;let w=i.charCodeAt(l),b=i.charCodeAt(g);if(w===J&&b===Q||w===$e&&b===ke||w===le&&b===le||w===fe&&b===fe||w===Fe&&b===Fe){l=m+1;return}}Re()}function Xo(){X(J,Q);while(l<a&&_e(i.charCodeAt(l)))l++;if(O("from")){l+=4;while(l<a&&_e(i.charCodeAt(l)))l++;if(l<a){let d=i.charCodeAt(l);if(d===le||d===fe)L(d)}}while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;if(l<a&&i.charCodeAt(l)===re)l++}function Qo(){l++;while(l<a&&_e(i.charCodeAt(l)))l++;if(O("as")){l+=2;while(l<a&&_e(i.charCodeAt(l)))l++;H();while(l<a&&_e(i.charCodeAt(l)))l++}if(O("from")){l+=4;while(l<a&&_e(i.charCodeAt(l)))l++;if(l<a){let d=i.charCodeAt(l);if(d===le||d===fe)L(d)}}while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;if(l<a&&i.charCodeAt(l)===re)l++}function Gr(d){let p=d.indexOf("from ");if(p===-1)return;let m=p+5;while(m<d.length&&(d.charCodeAt(m)===32||d.charCodeAt(m)===9))m++;if(m>=d.length)return;let g=d.charCodeAt(m);if(g!==39&&g!==34)return;let w=d.indexOf(d[m],m+1);if(w===-1)return;return d.slice(m+1,w)}function tt(d){if(!o)return;let p=d-1;while(p>=0&&_e(i.charCodeAt(p)))p--;if(p<0)return;let m=[],g=!1;while(p>=0){if(p>=1&&i.charCodeAt(p)===ee&&i.charCodeAt(p-1)===Ae){let T=i.lastIndexOf("/*",p-2);if(T>=0){m.push(i.slice(T,p+1)),g=!0,p=T-1;while(p>=0&&_e(i.charCodeAt(p)))p--;continue}break}let w=p;while(w>0&&i.charCodeAt(w-1)!==ve)w--;let b=C(w,p+1);if(b.startsWith("//")){if(g)break;let T=[b];p=w-1;while(p>=0&&(i.charCodeAt(p)===ve||i.charCodeAt(p)===xe))p--;while(p>=0){let R=p;while(R>0&&i.charCodeAt(R-1)!==ve)R--;let E=C(R,p+1);if(E.startsWith("//")){T.push(E),p=R-1;while(p>=0&&(i.charCodeAt(p)===ve||i.charCodeAt(p)===xe))p--}else if(E===""){p=R-1;while(p>=0&&(i.charCodeAt(p)===ve||i.charCodeAt(p)===xe))p--}else break}T.reverse(),m.push(T.join(`
|
|
143
|
+
`));continue}break}if(m.length===0)return;return m.reverse(),m}function Xc(d){let p=d,m=!1;while(l<a){let E=i.charCodeAt(l);if(E===re){l++;break}if(E===le||E===fe){L(E),m=!0;while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;if(l<a&&i.charCodeAt(l)===re)l++;break}if(E===ve&&m)break;l++}let g=C(p,l),w=g.charCodeAt(7)===116&&(g.startsWith("import type ")||g.startsWith("import type{")),b=!1;{let E=6;while(E<g.length&&(g.charCodeAt(E)===Me||g.charCodeAt(E)===De))E++;if(E<g.length&&g.charCodeAt(E)===116&&g.startsWith("type",E)){E+=4;while(E<g.length&&(g.charCodeAt(E)===Me||g.charCodeAt(E)===De))E++}if(E<g.length){let A=g.charCodeAt(E);b=A===le||A===fe}}let T="";{let E=g.indexOf("from ");if(E!==-1){let A=E+5;while(A<g.length&&(g.charCodeAt(A)===Me||g.charCodeAt(A)===De))A++;if(A<g.length){let M=g.charCodeAt(A);if(M===le||M===fe){let _=g.indexOf(String.fromCharCode(M),A+1);if(_!==-1)T=g.slice(A+1,_)}}}else if(b){let A=6;while(A<g.length&&g.charCodeAt(A)!==le&&g.charCodeAt(A)!==fe)A++;if(A<g.length){let M=g.charCodeAt(A),_=g.indexOf(String.fromCharCode(M),A+1);if(_!==-1)T=g.slice(A+1,_)}}}let R=tt(p);return{kind:"import",name:"",text:g,isExported:!1,isTypeOnly:w,isSideEffect:b,source:T,leadingComments:R,start:p,end:l}}function Xi(){let d=l;return X(J,Q),i.slice(d,l)}function es(d){let p=d.indexOf("(");if(p===-1)return d;let m=d.slice(p);if(m.indexOf("=")===-1)return d;let g=!1;for(let E=0;E<m.length;E++)if(m.charCodeAt(E)===61){let A=E>0?m.charCodeAt(E-1):0,M=E+1<m.length?m.charCodeAt(E+1):0;if(A!==61&&A!==33&&A!==60&&A!==62&&M!==61&&M!==62){g=!0;break}}if(!g)return d;let w=0,b=-1;for(let E=p;E<d.length;E++){let A=d.charCodeAt(E);if(A===40)w++;else if(A===41){if(w--,w===0){b=E;break}}}if(b===-1)return d;let T=d.slice(p,b+1),R=_t(T);return d.slice(0,p)+R+d.slice(b+1)}function ts(d){let p=d.indexOf("//")!==-1||d.indexOf("/*")!==-1,m=d.split(`
|
|
144
|
+
`),g=[],w=[],b=[],T=!1,R=1/0;for(let M=0;M<m.length;M++){let _=m[M];if(p){if(T){if(_.includes("*/"))T=!1;continue}let B=_.trim();if(B.length===0)continue;let N=B.charCodeAt(0);if(N===ee){let Je=B.charCodeAt(1);if(Je===ee)continue;if(Je===Ae){if(!B.includes("*/"))T=!0;continue}}if(N===Ae)continue;let D=G(_);if(D.charCodeAt(D.length-1)===re)D=D.slice(0,-1);D=es(D);let j=D.trim();if(!j)continue;g.push(D),w.push(j);let V=0;while(V<D.length&&_e(D.charCodeAt(V)))V++;if(j!=="{"&&j!=="}"){if(V<R)R=V}b.push(V)}else{let B=_.length;while(B>0&&(_.charCodeAt(B-1)===Me||_.charCodeAt(B-1)===De||_.charCodeAt(B-1)===xe))B--;if(B===0)continue;let N=B<_.length?_.slice(0,B):_;if(N.charCodeAt(N.length-1)===re)N=N.slice(0,-1);N=es(N);let D=N.trim();if(!D)continue;g.push(N),w.push(D);let j=0;while(j<N.length&&_e(N.charCodeAt(j)))j++;if(D!=="{"&&D!=="}"){if(j<R)R=j}b.push(j)}}if(g.length===0)return"{}";if(R===1/0||R<=2)return g.join(`
|
|
145
|
+
`);let E=R-2,A=Array(g.length);for(let M=0;M<g.length;M++){let _=w[M];if(_==="{"){A[M]=_;continue}let B=b[M];if(B>R)A[M]=g[M];else if(B===R&&(_.charCodeAt(0)===Q||_.charCodeAt(0)===ke||_.charCodeAt(0)===Se))A[M]=g[M];else{let N=Math.max(0,B-E);A[M]=" ".repeat(N)+_}}return A.join(`
|
|
146
|
+
`)}function mt(){if(l>=a||i.charCodeAt(l)!==we)return"";let d=l;X(we,me);let p=i.slice(d,l);if(p.includes(`
|
|
147
|
+
`)){let m="",g=!1;for(let w=0;w<p.length;w++){let b=p.charCodeAt(w);if(b===32||b===9||b===10||b===13){if(!g&&m.length>0)m+=" ",g=!0}else m+=p[w],g=!1}if(m.charCodeAt(1)===32)m=`<${m.slice(2)}`;if(m.charCodeAt(m.length-2)===32)m=`${m.slice(0,-2)}>`;return m}return p}function Tt(){if(l>=a||i.charCodeAt(l)!==ae)return"()";let d=l;return X(ae,Se),i.slice(d,l)}function jr(d){if(d.indexOf("/")===-1)return d;let p="",m=!1,g=0;for(let w=0;w<d.length;w++){let b=d.charCodeAt(w);if(m){if(p+=d[w],b===nt&&w+1<d.length){p+=d[++w];continue}if(b===g)m=!1;continue}if(b===le||b===fe||b===Fe){m=!0,g=b,p+=d[w];continue}if(b===ee&&w+1<d.length){let T=d.charCodeAt(w+1);if(T===Ae){let R=d.indexOf("*/",w+2);w=R===-1?d.length:R+1,p+=" ";continue}if(T===ee){let R=d.indexOf(`
|
|
148
|
+
`,w+2);w=R===-1?d.length:R-1;continue}}p+=d[w]}return p.trim()}function _t(d){let p=d.slice(1,-1).trim();if(!p)return"()";if(d.indexOf(`
|
|
149
|
+
`)===-1&&p.indexOf(":")!==-1&&p.indexOf("{")===-1&&p.indexOf("[")===-1&&p.indexOf("=")===-1&&p.indexOf("@")===-1&&p.indexOf("...")===-1){let E=0,A=0,M=0;for(let _=0;_<p.length;_++){let B=p.charCodeAt(_);if(B===ae||B===we||B===J)M++;else if(B===Se||B===me||B===Q)M--;else if(M===0){if(B===ft)E++;else if(B===dt)A++}}if(E>=A+1){let _=!1;for(let B=0;B<_o.length;B++){let N=_o[B],D=p.indexOf(N);if(D!==-1){let j=D+N.length;if((D===0||!Ue(p.charCodeAt(D-1)))&&(j>=p.length||!Ue(p.charCodeAt(j)))){_=!0;break}}}if(!_)return d}}let m=[],g=0,w=0,b=!1,T=0;for(let E=0;E<=p.length;E++){if(E===p.length){m.push(jr(p.slice(g).trim()));break}let A=p.charCodeAt(E);if(b){if(A===nt){E++;continue}if(A===T)b=!1;continue}if(A===ee&&E+1<p.length){let M=p.charCodeAt(E+1);if(M===Ae){E+=2;while(E+1<p.length&&!(p.charCodeAt(E)===Ae&&p.charCodeAt(E+1)===ee))E++;E++;continue}if(M===ee){while(E<p.length&&p.charCodeAt(E)!==10)E++;continue}}if(A===le||A===fe||A===Fe){b=!0,T=A;continue}if(A===ae||A===J||A===$e||A===we)w++;else if(A===Se||A===Q||A===ke||A===me&&!(E>0&&p.charCodeAt(E-1)===be))w--;else if(A===dt&&w===0)m.push(jr(p.slice(g,E).trim())),g=E+1}let R=[];for(let E of m){if(!E)continue;let A=E.trim();if(A.startsWith("//")||A.startsWith("/*"))continue;let M=E;{let _=!1,B=0,N=0,D=0;for(let j=0;j<M.length-1;j++){let V=M.charCodeAt(j);if(V===ve){D=j+1;continue}if(_){if(V===nt){j++;continue}if(V===B)_=!1;continue}if(V===le||V===fe||V===Fe){_=!0,B=V;continue}if(V===J||V===$e||V===ae||V===we){N++;continue}if(V===Q||V===ke||V===Se||V===me){if(N>0)N--;continue}if(V===ee&&M.charCodeAt(j+1)===ee){if(N===0){M=M.slice(0,j).trimEnd();break}let Je=M.indexOf(`
|
|
150
|
+
`,j);if(Je===-1){M=M.slice(0,D).trimEnd();break}let qe=M.slice(0,D),Kt=M.slice(Je+1);M=`${qe}${Kt}`,j=D-1}}}if(!M.trim())continue;R.push(rs(M))}return`(${R.join(", ")})`}function Qc(d){if(!d.startsWith("{")&&!d.startsWith("["))return d;let p="",m=0,g=0,w=!1,b=0;while(m<d.length){let T=d.charCodeAt(m);if(w){if(T===nt&&m+1<d.length){p+=d[m]+d[m+1],m+=2;continue}if(T===b)w=!1;p+=d[m],m++;continue}if(T===ee&&m+1<d.length){let R=d.charCodeAt(m+1);if(R===Ae){let E=m;m+=2;while(m+1<d.length&&!(d.charCodeAt(m)===Ae&&d.charCodeAt(m+1)===ee))m++;m=Math.min(m+2,d.length),p+=d.slice(E,m);continue}if(R===ee){let E=m;while(m<d.length&&d.charCodeAt(m)!==10)m++;p+=d.slice(E,m);continue}}if(T===le||T===fe||T===Fe){w=!0,b=T,p+=d[m],m++;continue}if(T===J||T===$e||T===ae)g++;else if(T===Q||T===ke||T===Se)g--;if(g>=1&&T===be&&(m+1>=d.length||d.charCodeAt(m+1)!==be&&d.charCodeAt(m+1)!==me)){while(p.length>0&&(p[p.length-1]===" "||p[p.length-1]==="\t"||p[p.length-1]===`
|
|
151
|
+
`))p=p.slice(0,-1);m++;let R=0;while(m<d.length){let E=d.charCodeAt(m);if(E===le||E===fe||E===Fe){let A=E;m++;while(m<d.length){if(d.charCodeAt(m)===nt){m+=2;continue}if(d.charCodeAt(m)===A){m++;break}m++}continue}if(E===J||E===$e||E===ae)R++;else if(E===Q||E===ke||E===Se){if(R===0)break;R--}else if(E===dt&&R===0)break;m++}continue}if(g===1&&T===gt&&m+2<d.length&&d.charCodeAt(m+1)===gt&&d.charCodeAt(m+2)===gt){m+=3;continue}p+=d[m],m++}return p}function rs(d){let p=d.trim(),m=p.startsWith("...");if(m)p=p.slice(3).trim();while(p.startsWith("@")){let D=1;while(D<p.length&&Ue(p.charCodeAt(D)))D++;if(D<p.length&&p.charCodeAt(D)===ae){let j=1;D++;while(D<p.length&&j>0){if(p.charCodeAt(D)===ae)j++;else if(p.charCodeAt(D)===Se)j--;D++}}p=p.slice(D).trim()}let g=!0;while(g){g=!1;for(let D of _o)if(p.startsWith(D)&&p.length>D.length&&!Ue(p.charCodeAt(D.length))){let j=p.slice(D.length).trim();if(j.charCodeAt(0)===ft||j.charCodeAt(0)===Ui&&j.length>1&&j.charCodeAt(1)===ft)break;p=j,g=!0;break}}let w=-1,b=-1,T=0,R=!1,E=0;for(let D=0;D<p.length;D++){let j=p.charCodeAt(D);if(R){if(j===nt){D++;continue}if(j===E)R=!1;continue}if(j===ee&&D+1<p.length){let V=p.charCodeAt(D+1);if(V===Ae){D+=2;while(D+1<p.length&&!(p.charCodeAt(D)===Ae&&p.charCodeAt(D+1)===ee))D++;D++;continue}if(V===ee){while(D<p.length&&p.charCodeAt(D)!==10)D++;continue}}if(j===le||j===fe||j===Fe){R=!0,E=j;continue}if(j===ae||j===J||j===$e||j===we)T++;else if(j===Se||j===Q||j===ke||j===me&&!(D>0&&p.charCodeAt(D-1)===be))T--;else if(T===0){if(j===ft&&w===-1)w=D;else if(j===be&&b===-1&&(D===0||p.charCodeAt(D-1)!==be)&&(D+1>=p.length||p.charCodeAt(D+1)!==be&&p.charCodeAt(D+1)!==me))b=D}}let A,M,_=b!==-1;if(w!==-1&&(b===-1||w<b))if(A=p.slice(0,w).trim(),b!==-1)M=p.slice(w+1,b).trim();else M=p.slice(w+1).trim();else if(b!==-1)A=p.slice(0,b).trim(),M=Qi(p.slice(b+1).trim());else A=p,M="unknown";if(A=Qc(A),(A.startsWith("{")||A.startsWith("["))&&A.includes(`
|
|
152
|
+
`)){let D=A.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(D.length<=40)A=D;else A=A.split(`
|
|
153
|
+
`).map((j)=>{let V=j.trim();if(!V)return"";if(V==="{"||V==="}"||V==="["||V==="]"||V.startsWith("}")||V.startsWith("]"))return V;return` ${V}`}).join(`
|
|
154
|
+
`)}let B=A.endsWith("?")||_;if(A.endsWith("?"))A=A.slice(0,-1).trim();let N=B&&!m?"?":"";if(m)return`...${A}: ${M}`;return`${A}${N}: ${M}`}function is(d){let p=0;if(p<d.length&&d.charCodeAt(p)===45)p++;if(p>=d.length)return!1;let m=d.charCodeAt(p);if(m<48||m>57)return!1;while(p<d.length&&d.charCodeAt(p)>=48&&d.charCodeAt(p)<=57)p++;if(p<d.length&&d.charCodeAt(p)===46){if(p++,p>=d.length||d.charCodeAt(p)<48||d.charCodeAt(p)>57)return!1;while(p<d.length&&d.charCodeAt(p)>=48&&d.charCodeAt(p)<=57)p++}return p===d.length}function Qi(d){let p=d.trim();if(p==="true"||p==="false")return"boolean";if(is(p))return"number";if(p.startsWith("'")&&p.endsWith("'")||p.startsWith('"')&&p.endsWith('"'))return"string";if(p.startsWith("["))return"unknown[]";if(p.startsWith("{"))return"Record<string, unknown>";return"unknown"}function en(d){let p=d.trim();if(p.endsWith("as const"))p=p.slice(0,-8).trim();if(p==="true"||p==="false")return p;if(is(p))return p;let m=ef(p);if(m!==null)return m;return"unknown"}function ef(d){if(d==="")return null;if(d.charCodeAt(0)===le||d.charCodeAt(0)===fe){if(Ki(d,0,d.charCodeAt(0))===d.length)return d}let p=tf(d,"+");if(p.length>1){let m=!1,g=!0,w=[];for(let b of p){let T=b.trim(),R=T.charCodeAt(0);if((R===le||R===fe)&&Ki(T,0,R)===T.length)m=!0,w.push(rf(T));else g=!1}if(g)return nf(w.join(""));if(m)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(d)&&/\d/.test(d)&&/[+*/%\-\s]/.test(d))return"number";return null}function tf(d,p){let m=[],g=0,w="",b=0;while(b<d.length){let T=d.charCodeAt(b);if(T===le||T===fe||T===Fe){let R=Ki(d,b,T);w+=d.slice(b,R),b=R;continue}if(T===ee&&(d.charCodeAt(b+1)===ee||d.charCodeAt(b+1)===42)){if(d.charCodeAt(b+1)===ee){let A=d.indexOf(`
|
|
155
|
+
`,b+2),M=A===-1?d.length:A;w+=d.slice(b,M),b=M;continue}let R=d.indexOf("*/",b+2),E=R===-1?d.length:R+2;w+=d.slice(b,E),b=E;continue}if(T===ae||T===$e||T===J)g++;else if(T===Se||T===ke||T===Q)g--;if(d[b]===p&&g===0){m.push(w),w="",b++;continue}w+=d[b],b++}return m.push(w),m}function rf(d){return d.slice(1,-1).replace(/\\(.)/g,(p,m)=>{if(m==="n")return`
|
|
156
|
+
`;if(m==="t")return"\t";if(m==="r")return"\r";if(m==="0")return"\x00";return m})}function nf(d){return`'${d.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function _r(d){if(d.endsWith("as const"))return null;let p=0,m=-1;for(let g=0;g<d.length;g++){let w=d.charCodeAt(g);if(w===le||w===fe||w===Fe)g=Ki(d,g,w)-1;else if(w===123||w===91||w===40)p++;else if(w===125||w===93||w===41)p--;else if(p===0&&w===32&&g+4<=d.length&&d.substring(g,g+4)===" as ")m=g}if(m===-1)return null;return d.slice(m+4).trim()||null}function pr(){if(v(),l<a&&i.charCodeAt(l)===ft){l++,v();let d=l,p=0;while(l<a){if(I())continue;let m=i.charCodeAt(l);if(m===ae||m===$e||m===we)p++;else if(m===Se||m===ke||m===me&&!oe())p--;else if(m===J)if(p>0)p++;else{let g=C(d,l),w=(b)=>{let T=g.length-b.length;return T>=0&&g.endsWith(b)&&(T===0||!Ue(g.charCodeAt(T-1)))};if(g.length===0||g.endsWith("|")||g.endsWith("&")||w("is")||w("extends"))p++;else break}else if(m===Q){if(p===0)break;p--}else if(p===0&&m===re)break;if(p===0&&W())break;l++}return C(d,l)}return""}function Ot(d,p,m,g){l+=8,v();let w=l<a&&i.charCodeAt(l)===Ae;if(w)l++,v();let b=H();if(!b&&!g)return null;v();let T=mt();v();let R=Tt();v();let E=pr(),A=E.length>0;if(!E)if(m&&w)E="AsyncGenerator<unknown, void, unknown>";else if(w)E="Generator<unknown, void, unknown>";else if(m)E="Promise<void>";else E="void";v();let M=!1;if(l<a&&i.charCodeAt(l)===J){M=!0;let j=l+1;if(X(J,Q),!A&&!w)E=hr(i.slice(j,l-1),m,R)}else if(l<a&&i.charCodeAt(l)===re)l++;let _=_t(R),B=`${p?g?"export default function ":"export declare function ":"declare function "}${b||(g?"":"default")}${T}${_}: ${E};`,N=tt(d),D={kind:"function",name:b||"default",text:B,isExported:p,isDefault:g,isAsync:m,isGenerator:w,returnType:E,generics:T||void 0,leadingComments:N,start:d,end:l};if(M)h.add(D);return D}function Lt(d,p,m){l+=p.length,v();let g=[];do{if(v(),l>=a)break;let w=i.charCodeAt(l);if(w===J||w===$e)return Re(),g;let b=H();if(!b)return Re(),g;v();let T,R,E=!1;if(l<a&&i.charCodeAt(l)===ft){l++,v();let _=l,B=0;while(l<a){if(I()){if(B===0&&pe())break;continue}let N=i.charCodeAt(l);if(N===ae||N===J||N===$e||N===we)B++;else if(N===Se||N===Q||N===ke||N===me&&!oe())B--;else if(B===0&&(N===re||N===dt))break;else if(B===0&&N===be&&!Ge())break;if(B===0&&(ie()||se()))break;l++}T=C(_,l)}if(l<a&&i.charCodeAt(l)===be)if(s&&T&&(!o||!qd(T)))Zc();else{l++,v();let _=l,B=0,N=0,D=0,j=!0;for(;;){l=_,B=0,N=0,D=0;while(l<a){if(I()){if(B===0&&N===0&&D===0&&pe())break;continue}let V=i.charCodeAt(l);if(V===ae||V===J||V===$e)B++;else if(V===Se||V===Q||V===ke)B--;else if(V===we&&B===0){let Je=ns(l);if(Je!==null)D=Math.max(0,D+Je);else if(j&&(l+1>=a||i.charCodeAt(l+1)!==be))N++}else if(V===me&&B===0&&D===0&&!oe()){if(N>0&&(l+1>=a||i.charCodeAt(l+1)!==be))N--}else if(B===0&&N===0&&D===0&&(V===re||V===dt))break;if(B===0&&N===0&&D===0&&(ie()||ue()))break;l++}if(N>0&&j){j=!1;continue}break}if(R=C(_,l),R.endsWith(" as const")||R==="const"){if(E=!0,!T){let V=R.endsWith(" as const")?R.slice(0,-9).trim():R,Je=en(V);T=Je!=="unknown"?Je:void 0}}else if(!T){let V=Vi(R)??_r(R);if(V)T=V}}if(l<a){let _=i.charCodeAt(l);if(_===dt){l++;continue}if(_===re)l++}let A=tt(d),M=`${m?"export ":""}declare ${p} ${b}: ${T||"unknown"};`;g.push({kind:"variable",name:b,text:M,isExported:m,typeAnnotation:T,value:R,modifiers:E?[p,"const assertion"]:[p],leadingComments:A,start:d,end:l});break}while(l<a);return g}function ns(d){if(i.charCodeAt(d)!==we||d+1>=a)return null;let p=i.charCodeAt(d+1);if(p===me)return 1;if(p===ee)return-1;if(!yt(p))return null;let m=d+2;while(m<a){let A=i.charCodeAt(m);if(!Ue(A)&&A!==gt&&A!==58&&A!==45)break;m++}let g=i.slice(d+1,m),w=i.charCodeAt(m);if(w>32&&w!==me&&w!==ee)return null;let b=0,T=0,R=m;for(;R<a;R++){let A=i.charCodeAt(R);if(T!==0){if(A===nt)R++;else if(A===T)T=0;continue}if(A===le||A===fe||A===Fe)T=A;else if(A===J)b++;else if(A===Q&&b>0)b--;else if(A===me&&b===0)break}if(R>=a)return null;let E=R-1;while(E>d&&i.charCodeAt(E)<=32)E--;if(i.charCodeAt(E)===ee)return 0;return i.indexOf(`</${g}`,R+1)===-1?null:1}function tn(d,p){l+=9,v();let m=H();v();let g=mt();v();let w="";if(O("extends")){l+=7,v();let A=l,M=0;while(l<a){if(I())continue;let _=i.charCodeAt(l);if(_===we)M++;else if(_===me&&!oe())M--;else if(_===J&&M===0)break;l++}w=C(A,l)}v();let b=l<a&&i.charCodeAt(l)===J?Xi():"{}",T=ts(b),R=`${p?"export ":""}declare interface ${m}${g}${w?` extends ${w}`:""} ${T}`,E=tt(d);return{kind:"interface",name:m,text:R,isExported:p,extends:w||void 0,generics:g||void 0,leadingComments:E,start:d,end:l}}function rn(d,p){l+=4,v();let m=H();v();let g=mt();if(v(),l<a&&i.charCodeAt(l)===be)l++;v();let w=l,b=0;while(l<a){if(I())continue;let A=i.charCodeAt(l);if(A===ae||A===J||A===$e||A===we)b++;else if(A===Se||A===Q||A===ke||A===me&&!oe())b--;else if(b===0&&A===re)break;if(b===0&&(ie()||se()))break;l++}let T=C(w,l);if(l<a&&i.charCodeAt(l)===re)l++;let R=`${p?"export ":""}type ${m}${g} = ${T}`,E=tt(d);return{kind:"type",name:m,text:R,isExported:p,generics:g||void 0,leadingComments:E,start:d,end:l}}function Vt(d,p,m){l+=4,v();let g=H();v();let w=l;if(l<a&&i.charCodeAt(l)===J)X(J,Q);let b=C(d,l),T=tt(d);return{kind:"enum",name:g,text:b,isExported:p,modifiers:m?["const"]:void 0,leadingComments:T,start:d,end:l}}function Rt(d,p,m,g=!1){l+=5,v();let w=H()||"AnonymousClass";v();let b=mt();v();let T="";if(O("extends")){l+=7,v();let _=l,B=0;while(l<a){if(I())continue;let N=i.charCodeAt(l);if(N===we)B++;else if(N===me&&!oe())B--;else if(B===0&&(N===J||O("implements")))break;l++}T=C(_,l)}let R;if(O("implements")){l+=10,v();let _=l,B=0;while(l<a){if(I())continue;let D=i.charCodeAt(l);if(D===we)B++;else if(D===me&&!oe())B--;else if(B===0&&D===J)break;l++}let N=C(_,l);if(N)R=N.split(",").map((D)=>D.trim())}v();let E=nn(),A=`${p?g?"export default ":"export declare ":"declare "}${m?"abstract ":""}class ${w}${b}${T?` extends ${T}`:""}${R&&R.length>0?` implements ${R.join(", ")}`:""} ${E}`,M=tt(d);return{kind:"class",name:w,text:A,isExported:p,isDefault:g,extends:T||void 0,implements:R,generics:b||void 0,modifiers:m?["abstract"]:void 0,leadingComments:M,start:d,end:l}}function nn(){if(l>=a||i.charCodeAt(l)!==J)return"{}";l++;let d=[];while(l<a){if(v(),l>=a)break;if(i.charCodeAt(l)===Q){l++;break}if(i.charCodeAt(l)===re){l++;continue}if(O("static")&&sn("static")===J){l+=6,v(),X(J,Q);continue}let p=!1,m=!1,g=!1,w=!1,b=!1,T=!1,R=!1,E=!1,A=!0;while(A){v();let B=l,N=H();if(l=B,N){let D=sn(N);if(D===ae||D===we||D===Ui||D===33||D===ft||D===be||D===re||D===Q)break}if(O("private")){p=!0,l+=7;continue}if(O("protected")){m=!0,l+=9;continue}if(O("public")){l+=6;continue}if(O("static")){g=!0,l+=6;continue}if(O("abstract")){w=!0,l+=8;continue}if(O("readonly")){b=!0,l+=8;continue}if(O("override")){T=!0,l+=8;continue}if(O("accessor")){R=!0,l+=8;continue}if(O("async")){E=!0,l+=5;continue}if(O("declare")){l+=7;continue}break}if(v(),l>=a||i.charCodeAt(l)===Q)break;if(i.charCodeAt(l)===jo)p=!0;let M=p?[]:d,_=" ";if(m)_+="protected ";if(g)_+="static ";if(w)_+="abstract ";if(b)_+="readonly ";if(O("constructor")){l+=11,v();let B=Tt();if(v(),sf(B,M),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let N=_t(B);M.push(` constructor${N};`)}else if(O("get"))if(l+=3,v(),l<a&&os(i.charCodeAt(l))){let B=on();if(B.startsWith("#")){if(v(),l<a&&i.charCodeAt(l)===ae)Tt();if(v(),pr(),v(),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;continue}v(),Tt(),v();let N=pr()||"unknown";if(v(),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;M.push(`${_}get ${B}(): ${N};`)}else as("get",_,g,b,E,M);else if(O("set"))if(l+=3,v(),l<a&&os(i.charCodeAt(l))){let B=on();if(B.startsWith("#")){if(v(),l<a&&i.charCodeAt(l)===ae)Tt();if(v(),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;continue}v();let N=Tt();if(v(),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let D=_t(N);M.push(`${_}set ${B}${D};`)}else as("set",_,g,b,E,M);else{let B=i.charCodeAt(l)===Ae;if(B)l++,v();let N=on();if(!N){ss();continue}ls(N,_,g,b,B,w,E,M)}}return`{
|
|
157
|
+
${d.join(`
|
|
158
|
+
`)}
|
|
159
|
+
}`}function os(d){return yt(d)||d===$e||d===jo||d===le||d===fe}function on(){if(l>=a)return"";let d=i.charCodeAt(l);if(d===$e){let p=l;return X($e,ke),i.slice(p,l)}if(d===jo)return l++,`#${H()}`;if(d===le||d===fe){let p=l;return L(d),i.slice(p,l)}return H()}function sn(d){let p=l;l+=d.length,v();let m=l<a?i.charCodeAt(l):0;return l=p,m}function ss(){let d=0;while(l<a){if(I())continue;let p=i.charCodeAt(l);if(p===J||p===ae)d++;else if(p===Q||p===Se){if(d===0)return;d--}else if(p===re&&d===0){l++;return}if(d===0&&W())return;l++}}function as(d,p,m,g,w,b){ls(d,p,m,g,!1,!1,w,b)}function ls(d,p,m,g,w,b,T,R){if(v(),l>=a)return;let E=i.charCodeAt(l),A=!1;if(E===Ui)A=!0,l++,v();if(l<a&&i.charCodeAt(l)===33)l++,v();let M=l<a?i.charCodeAt(l):0;if(M===ae||M===we){let _=M===we?mt():"";v();let B=Tt();v();let N=pr(),D=N.length>0;if(!N)if(T&&w)N="AsyncGenerator<unknown, void, unknown>";else if(w)N="Generator<unknown, void, unknown>";else if(T)N="Promise<void>";else N="void";if(v(),l<a&&i.charCodeAt(l)===J){let Je=l+1;if(X(J,Q),!D&&!w)N=hr(i.slice(Je,l-1),T,B)}else if(l<a&&i.charCodeAt(l)===re)l++;let j=_t(B),V=A?"?":"";R.push(`${p}${d}${V}${_}${j}: ${N};`)}else if(M===ft||M===be||M===re||M===Q||M===ve||M===xe){let _="";if(M===ft){l++,v();let D=l,j=0;while(l<a){if(I())continue;let V=i.charCodeAt(l);if(V===ae||V===J||V===$e||V===we)j++;else if(V===Se||V===Q||V===ke||V===me&&!oe()){if(j===0)break;j--}else if(j===0&&(V===re||V===dt))break;else if(j===0&&V===be&&!Ge())break;if(j===0&&W())break;l++}_=C(D,l)}let B="";if(l<a&&i.charCodeAt(l)===be)if(s&&_){l++;let D=0;while(l<a){if(I())continue;let j=i.charCodeAt(l);if(j===ae||j===J||j===$e)D++;else if(j===Se||j===Q||j===ke){if(D===0&&j===Q)break;D--}else if(D===0&&j===re)break;if(D===0&&W())break;l++}}else{l++,v();let D=l,j=0;while(l<a){if(I())continue;let V=i.charCodeAt(l);if(V===ae||V===J||V===$e)j++;else if(V===Se||V===Q||V===ke){if(j===0&&V===Q)break;j--}else if(j===0&&V===re)break;if(j===0&&W())break;l++}B=C(D,l)}if(l<a&&i.charCodeAt(l)===re)l++;if(!_)if(B){let D=_r(B);if(D)_=D;else _=B.endsWith("as const")||m&&g?en(B):Qi(B)}else _="unknown";let N=A?"?":"";R.push(`${p}${d}${N}: ${_};`)}else ss()}function of(d){let p=0;for(let m=0;m<d.length;m++){let g=d.charCodeAt(m);if(g===ae||g===J||g===$e||g===we)p++;else if(g===Se||g===Q||g===ke||g===me&&d.charCodeAt(m-1)!==be)p--;else if(g===be&&p===0&&d.charCodeAt(m+1)!==me&&d.charCodeAt(m+1)!==be)return!0}return!1}function sf(d,p){let m=d.slice(1,-1).trim();if(!m)return;let g=[],w=0,b=0,T=!1,R=0;for(let E=0;E<=m.length;E++){if(E===m.length){g.push(jr(m.slice(w).trim()));break}let A=m.charCodeAt(E);if(T){if(A===nt){E++;continue}if(A===R)T=!1;continue}if(A===ee&&E+1<m.length){let M=m.charCodeAt(E+1);if(M===Ae){E+=2;while(E+1<m.length&&!(m.charCodeAt(E)===Ae&&m.charCodeAt(E+1)===ee))E++;E++;continue}if(M===ee){while(E<m.length&&m.charCodeAt(E)!==10)E++;continue}}if(A===le||A===fe||A===Fe){T=!0,R=A;continue}if(A===ae||A===J||A===$e||A===we)b++;else if(A===Se||A===Q||A===ke||A===me&&!(E>0&&m.charCodeAt(E-1)===be))b--;else if(A===dt&&b===0)g.push(jr(m.slice(w,E).trim())),w=E+1}for(let E of g){let A=E.startsWith("public ")||E.startsWith("public\t"),M=E.startsWith("protected ")||E.startsWith("protected\t"),_=E.startsWith("private ")||E.startsWith("private\t"),B=E.includes("readonly ");if(!A&&!M&&!_&&!B)continue;if(_)continue;let N=E,D=[];if(A){let qe=6;while(qe<N.length&&_e(N.charCodeAt(qe)))qe++;N=N.slice(qe),D.push("public")}if(M){let qe=9;while(qe<N.length&&_e(N.charCodeAt(qe)))qe++;N=N.slice(qe),D.push("protected")}if(B){let qe=N.indexOf("readonly ");if(qe!==-1){let Kt=qe+8;while(Kt<N.length&&_e(N.charCodeAt(Kt)))Kt++;N=N.slice(0,qe)+N.slice(Kt)}D.push("readonly")}let j=D.length>0?`${D.join(" ")} `:"",V=rs(N),Je=N.search(/[?:=]/);if(Je!==-1&&N.charCodeAt(Je)!==63&&of(N))V=V.replace(/^([\w$]+)\?:/,"$1:");p.push(` ${j}${V};`)}}function an(d=" "){if(l>=a||i.charCodeAt(l)!==J)return"{}";l++;let p=[];while(l<a){if(v(),l>=a)break;if(i.charCodeAt(l)===Q){l++;break}if(i.charCodeAt(l)===re){l++;continue}let m=!1;if(O("export"))m=!0,l+=6,v();if(O("declare"))l+=7,v();let g=m?"export ":"";if(O("function")||O("async")&&af("async","function")){let w=!1;if(O("async"))w=!0,l+=5,v();if(l+=8,v(),l<a&&i.charCodeAt(l)===Ae)l++,v();let b=H();v();let T=mt();v();let R=Tt();v();let E=pr();if(!E)E=w?"Promise<void>":"void";if(v(),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let A=_t(R);p.push(`${d}${g}function ${b}${T}${A}: ${E};`)}else if(O("const")||O("let")||O("var")){let w=O("const")?"const":O("let")?"let":"var";l+=w.length,v();let b=H();if(!b){Re(!0);continue}v();let T="";if(l<a&&i.charCodeAt(l)===ft){l++,v();let E=l,A=0;while(l<a){if(I())continue;let M=i.charCodeAt(l);if(M===ae||M===J||M===$e||M===we)A++;else if(M===Q&&A===0)break;else if(M===Se||M===Q||M===ke||M===me&&!oe())A--;else if(A===0&&(M===re||M===dt))break;else if(A===0&&M===be&&!Ge())break;if(A===0&&ie())break;l++}T=C(E,l)}let R="";if(l<a&&i.charCodeAt(l)===be){l++,v();let E=l,A=0;while(l<a){if(I())continue;let M=i.charCodeAt(l);if(M===ae||M===J||M===$e||M===we)A++;else if(M===Q&&A===0)break;else if(M===Se||M===Q||M===ke||M===me&&!oe())A--;else if(A===0&&(M===re||M===dt))break;if(A===0&&ie())break;l++}R=C(E,l)}if(l<a&&i.charCodeAt(l)===re)l++;if(!T&&R){let E=_r(R);if(E)T=E;else if(w==="const")T=en(R);else T=Qi(R)}if(!T)T="unknown";p.push(`${d}${g}${w} ${b}: ${T};`)}else if(O("interface")){l+=9,v();let w=H();v();let b=mt();v();let T="";if(O("extends")){l+=7,v();let E=l,A=0;while(l<a){if(I())continue;let M=i.charCodeAt(l);if(M===we)A++;else if(M===me&&!oe())A--;else if(M===J&&A===0)break;l++}T=C(E,l)}let R=ts(Xi());p.push(`${d}${g}interface ${w}${b}${T?` extends ${T}`:""} ${R}`)}else if(O("type")){l+=4,v();let w=H();v();let b=mt();if(v(),l<a&&i.charCodeAt(l)===be){l++,v();let T=l,R=0;while(l<a){if(I())continue;let A=i.charCodeAt(l);if(A===ae||A===J||A===$e||A===we)R++;else if(A===Q&&R===0)break;else if(A===Se||A===Q||A===ke||A===me&&!oe())R--;else if(R===0&&A===re)break;if(R===0&&ie())break;l++}let E=C(T,l);if(l<a&&i.charCodeAt(l)===re)l++;p.push(`${d}${g}type ${w}${b} = ${E}`)}}else if(O("class")){l+=5,v();let w=H();v();let b=mt();v();let T=l,R=0;while(l<a){if(I())continue;let _=i.charCodeAt(l);if(_===we)R++;else if(_===me&&!oe())R--;else if(_===J&&R===0)break;l++}let E=C(T,l),A=E?` ${E}`:"",M=nn();p.push(`${d}${g}class ${w}${b}${A} ${M}`)}else if(O("enum")){l+=4,v();let w=H();v();let b=Xi();p.push(`${d}${g}enum ${w} ${b}`)}else if(O("namespace")||O("module")){let w=O("namespace")?"namespace":"module";l+=w.length,v();let b=H();v();let T=an(d);p.push(`${d}${g}${w} ${b} ${T}`)}else if(O("abstract"))if(l+=8,v(),O("class")){l+=5,v();let w=H();v();let b=mt();v();let T=l,R=0;while(l<a){if(I())continue;let _=i.charCodeAt(l);if(_===we)R++;else if(_===me&&!oe())R--;else if(_===J&&R===0)break;l++}let E=C(T,l),A=E?` ${E}`:"",M=nn();p.push(`${d}${g}abstract class ${w}${b}${A} ${M}`)}else Re(!0);else if(m&&O("default")){l+=7,v();let w=l;Re(!0);let b=C(w,l);if(b.charCodeAt(b.length-1)===re)b=b.slice(0,-1);if(b)p.push(`${d}export default ${b};`)}else if(!m&&(i.charCodeAt(l)===le||i.charCodeAt(l)===fe||i.charCodeAt(l)===Fe))Re(!0);else Re(!0)}if(p.length===0)return"{}";return`{
|
|
160
|
+
${p.join(`
|
|
161
|
+
`)}
|
|
162
|
+
}`}function af(d,p){let m=l+d.length;while(m<a&&_e(i.charCodeAt(m)))m++;for(let g=0;g<p.length;g++)if(m+g>=a||i.charCodeAt(m+g)!==p.charCodeAt(g))return!1;return m+p.length>=a||!Ue(i.charCodeAt(m+p.length))}function Ut(d,p,m){l+=m.length,v();let g="",w=i.charCodeAt(l);if(w===le||w===fe){let A=l;L(w),g=i.slice(A,l)}else{g=H();while(l<a&&i.charCodeAt(l)===gt)l++,g+=`.${H()}`}v();let b=l<a&&i.charCodeAt(l)===J?an():"{}",T=`${p?"export ":""}declare ${m} ${g} ${b}`,R=tt(d),E=g.startsWith("'")||g.startsWith('"');return{kind:"module",name:g,text:T,isExported:p,source:E?g.slice(1,-1):void 0,leadingComments:R,start:d,end:l}}function cs(d,p){Re();let m=C(p,l);if(m.charCodeAt(m.length-1)===re)m=m.slice(0,-1).trimEnd();if(!m)return;let g=yt(m.charCodeAt(0));for(let A=1;g&&A<m.length;A++)g=Ue(m.charCodeAt(A));let w=tt(d);if(g){c.push({kind:"export",name:"default",text:`export default ${m};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:d,end:l});return}let b="__dtsx_default_export__",T=1;while(i.includes(b))b=`__dtsx_default_export_${T++}__`;let R=_r(m)||Ie(m,!1),E=R==="unknown"&&Jd(m)?`typeof ${m}`:R;c.push({kind:"variable",name:b,text:`declare const ${b}: ${E};`,isExported:!1,typeAnnotation:E,modifiers:["const"],start:d,end:l}),c.push({kind:"export",name:"default",text:`export default ${b};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:d,end:l})}while(l<a){if(v(),l>=a)break;let d=l,p=i.charCodeAt(l);if(p===105&&O("import"))c.push(Xc(d));else if(p===101&&O("export")){l+=6,v();let m=i.charCodeAt(l);if(m===100&&O("default")){l+=7,v();let g=l,w=i.charCodeAt(l);if(w===102&&O("function")){let b=Ot(d,!0,!1,!0);if(b)c.push(b)}else if(w===97&&O("async")&&sn("async")!==re)if(l+=5,v(),O("function")){let b=Ot(d,!0,!0,!0);if(b)c.push(b)}else cs(d,g);else if(w===99&&O("class")){let b=Rt(d,!0,!1,!0);c.push(b)}else if(w===97&&O("abstract")){if(l+=8,v(),O("class")){let b=Rt(d,!0,!0,!0);c.push(b)}}else cs(d,g)}else if(m===116&&O("type")){let g=l;if(l+=4,v(),l<a&&i.charCodeAt(l)===J){Xo();let w=C(d,l),b=tt(d);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Gr(w),leadingComments:b,start:d,end:l})}else if(l<a&&i.charCodeAt(l)===Ae){Qo();let w=C(d,l);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Gr(w),start:d,end:l})}else{l=g;let w=rn(d,!0);c.push(w)}}else if(m===105&&O("interface")){let g=tn(d,!0);c.push(g)}else if(m===102&&O("function")){let g=Ot(d,!0,!1,!1);if(g)c.push(g)}else if(m===97&&O("async"))if(l+=5,v(),O("function")){let g=Ot(d,!0,!0,!1);if(g)c.push(g)}else Re();else if(m===99)if(O("class")){let g=Rt(d,!0,!1);c.push(g)}else if(O("const")){let g=l;if(l+=5,v(),O("enum")){l=g+5,v();let w=Vt(d,!0,!0);c.push(w)}else{l=g;let w=Lt(d,"const",!0);for(let b=0;b<w.length;b++)c.push(w[b])}}else Re();else if(m===97&&O("abstract")){if(l+=8,v(),O("class")){let g=Rt(d,!0,!0);c.push(g)}}else if(m===108&&O("let")){let g=Lt(d,"let",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else if(m===118&&O("var")){let g=Lt(d,"var",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else if(m===101&&O("enum")){let g=Vt(d,!0,!1);c.push(g)}else if(m===100&&O("declare"))l+=7,v(),us(d,!0);else if(m===110&&O("namespace")&&z(9)){let g=Ut(d,!0,"namespace");c.push(g)}else if(m===109&&O("module")&&z(6)){let g=Ut(d,!0,"module");c.push(g)}else if(m===J){Xo();let g=C(d,l),w=g.includes("export type"),b=tt(d);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:w,source:Gr(g),leadingComments:b,start:d,end:l})}else if(m===Ae){Qo();let g=C(d,l),w=tt(d);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:!1,source:Gr(g),leadingComments:w,start:d,end:l})}else{Re();let g=C(d,l);if(g)c.push({kind:"export",name:"",text:g,isExported:!0,start:d,end:l})}}else if(p===100&&O("declare"))l+=7,v(),us(d,!1);else if(p===105&&O("interface")){let m=tn(d,!1);f.set(m.name,m)}else if(p===116&&O("type")){let m=rn(d,!1);f.set(m.name,m),c.push(m)}else if(p===102&&O("function")){let m=Ot(d,!1,!1,!1);if(m)y(m);else Re()}else if(p===97)if(O("async")){let m=l;if(l+=5,v(),O("function")){let g=Ot(d,!1,!0,!1);if(g)y(g);else l=m,Re()}else l=m,Re()}else if(O("abstract"))if(l+=8,v(),O("class")){let m=Rt(d,!1,!1);f.set(m.name,m),c.push(m)}else Re();else l++,Re();else if(p===99)if(O("class")){let m=Rt(d,!1,!1);f.set(m.name,m),c.push(m)}else if(O("const")){let m=l;if(l+=5,v(),O("enum")){l=m+5,v();let g=Vt(d,!1,!0);f.set(g.name,g),c.push(g)}else{l=m;let g=Lt(d,"const",!1);for(let w=0;w<g.length;w++)f.set(g[w].name,g[w])}}else l++,Re();else if(p===101&&O("enum")){let m=Vt(d,!1,!1);f.set(m.name,m),c.push(m)}else if(p===108&&O("let")||p===118&&O("var")){let m=O("let")?"let":"var",g=Lt(d,m,!1);for(let w=0;w<g.length;w++)f.set(g[w].name,g[w])}else if(p===109&&O("module")&&z(6)){let m=Ut(d,!1,"module");c.push(m)}else if(p===110&&O("namespace")&&z(9)){let m=Ut(d,!1,"namespace");c.push(m)}else{let m=i.charCodeAt(l);if(m===re)l++;else if(m===le||m===fe){if(L(m),l<a&&i.charCodeAt(l)===re)l++}else if(m===Fe){if(P(),l<a&&i.charCodeAt(l)===re)l++}else if(m===Hd){if(l++,H(),v(),l<a&&i.charCodeAt(l)===gt)l++,H(),v();if(l<a&&i.charCodeAt(l)===ae)X(ae,Se)}else l++,Re()}}if(h.size>0){fs(c);for(let d of u.values())fs(d)}if(f.size>0)Yd(c,f,u);return c;function fs(d){let p=new Map;for(let g of d)if(g.kind==="function")p.set(g.name,(p.get(g.name)||0)+1);let m=new Set;for(let[g,w]of p)if(w>1)m.add(g);if(m.size>0){let g=new Set;for(let w of m)for(let b=d.length-1;b>=0;b--)if(d[b].kind==="function"&&d[b].name===w&&h.has(d[b])){g.add(b);break}if(g.size>0){let w=[...g].sort((b,T)=>T-b);for(let b of w)d.splice(b,1)}}}function us(d,p){if(O("function")){let m=Ot(d,p,!1,!1);if(m)c.push(m)}else if(O("async")){if(l+=5,v(),O("function")){let m=Ot(d,p,!0,!1);if(m)c.push(m)}}else if(O("class")){let m=Rt(d,p,!1);c.push(m)}else if(O("abstract")){if(l+=8,v(),O("class")){let m=Rt(d,p,!0);c.push(m)}}else if(O("interface")){let m=tn(d,p);c.push(m)}else if(O("type")){let m=rn(d,p);c.push(m)}else if(O("enum")){let m=Vt(d,p,!1);c.push(m)}else if(O("const")){let m=l;if(l+=5,v(),O("enum")){l=m+5,v();let g=Vt(d,p,!0);c.push(g)}else if(p){l=m;let g=Lt(d,"const",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else Re()}else if(O("let")||O("var"))if(p){let m=O("let")?"let":"var",g=Lt(d,m,!0);for(let w=0;w<g.length;w++)c.push(g[w])}else Re();else if(O("module")){let m=Ut(d,p,"module");c.push(m)}else if(O("namespace")){let m=Ut(d,p,"namespace");c.push(m)}else if(O("global")){l+=6,v();let m=`declare global ${l<a&&i.charCodeAt(l)===J?an():"{}"}`,g=tt(d);c.push({kind:"module",name:"global",text:m,isExported:!1,leadingComments:g,start:d,end:l})}else Re()}}function Ul(e,t){let r=0,n=e.length;while(r<n){let i=e.charCodeAt(r);if(i>=65&&i<=90||i>=97&&i<=122||i===95||i===36||i>127){let o=r;r++;while(r<n){let s=e.charCodeAt(r);if(s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===95||s===36||s>127)r++;else break}t.add(e.substring(o,r))}else r++}}function Kl(e,t){let r=0;while(r<e.length){let n=e.charCodeAt(r);if(n===le||n===fe||n===Fe){let u=n;r++;while(r<e.length)if(e.charCodeAt(r)===nt)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(n===ee&&e.charCodeAt(r+1)===ee){r+=2;while(r<e.length&&e.charCodeAt(r)!==ve&&e.charCodeAt(r)!==xe)r++;continue}if(n===ee&&e.charCodeAt(r+1)===Ae){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!yt(n)){r++;continue}let i=r++;while(r<e.length&&Ue(e.charCodeAt(r)))r++;let o=i-1,s=r;while(o>=0&&_e(e.charCodeAt(o)))o--;while(s<e.length&&_e(e.charCodeAt(s)))s++;let a=o>=0?e.charCodeAt(o):0,c=s<e.length?e.charCodeAt(s):0,f=i>=3&&e.slice(i-3,i)==="...";if(c===ft||a===gt&&!f)continue;if(c===ae&&(a===J||a===dt))continue;t.add(e.slice(i,r))}}function Yd(e,t,r){let n=new Set,i=new Set;for(let a of e)i.add(a.name);let o=new Set,s=[];for(let a=0;a<e.length;a++){let c=e[a];if(c.kind!=="import"){if(s.push(c.text),Ul(c.text,o),typeof c.value==="string")Kl(c.value,o)}}for(;;){let a=[];for(let[u,h]of t){if(n.has(u))continue;if(o.has(u)){if(!i.has(u)){let l=h.kind==="function"?r.get(u):void 0;if(l)for(let y of l)a.push(y);else a.push(h);i.add(u)}n.add(u)}}if(a.length===0)break;a.sort((u,h)=>(u.start??1/0)-(h.start??1/0));let c=[],f=0;for(let u=0;u<e.length;u++){let h=e[u].start??1/0;while(f<a.length&&(a[f].start??1/0)<=h)c.push(a[f++]);c.push(e[u])}while(f<a.length)c.push(a[f++]);e.length=0;for(let u=0;u<c.length;u++)e.push(c[u]);for(let u of a)if(u.kind!=="import"){if(s.push(u.text),Ul(u.text,o),typeof u.value==="string")Kl(u.value,o)}}}var Me=32,De=9,ve=10,xe=13,ee=47,Ae=42,le=39,fe=34,Fe=96,nt=92,J=123,Q=125,ae=40,Se=41,$e=91,ke=93,we=60,me=62,re=59,ft=58,be=61,dt=44,gt=46,Ui=63,jo=35,Hd=64,zd=36,_o;var ql=he(()=>{hn();Go();_o=["public","protected","private","readonly","override"]});function Zl(e,t,r=!0,n=!1){if(El(t))e=Al(e);else if(Tl(t))e=Ol(e);let i=vr(e),o=`${t}:${r?1:0}:${n?1:0}`,s=mr.get(o);if(s&&s.contentHash===i)return s.lastAccess=++Yl,s.declarations;let a=n?Hl(e,t,r):zl(e,t,r);if(mr.set(o,{declarations:a,contentHash:i,lastAccess:++Yl}),mr.size>Zd){let c=Math.max(1,Math.ceil(mr.size*0.1)),f=[];for(let[u,h]of mr)f.push([u,h.lastAccess]);f.sort((u,h)=>u[1]-h[1]);for(let u=0;u<c&&u<f.length;u++)mr.delete(f[u][0])}return a}var Zd=100,Yl=0,mr;var Xl=he(()=>{$o();Rl();ql();Sn();mr=new Map});function Ql(e,t,r=!0,n=!1){return Zl(e,t,r,n)}var ec=he(()=>{Xl()});async function Xd(){if(Hi!==null)return Hi;try{return Ft=await import("prettier"),Hi=!0,!0}catch{return Hi=!1,!1}}async function Qd(e,t){if(!Ft)return null;try{if(t&&Ft.resolveConfig){let r=await Ft.resolveConfig(t);if(r)return r}if(e&&Ft.resolveConfig){let r=await Ft.resolveConfig(e);if(r)return r}return null}catch{return null}}async function em(e,t){if(!Ft)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return Ft.format(e,r)}function tm(e,t={}){let{indentSize:r=2,useTabs:n=!1,maxLineWidth:i=100,trailingNewline:o=!0,normalizeWhitespace:s=!0,sortImports:a=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(r);if(f.indexOf(`\r
|
|
163
|
+
`)!==-1)f=f.replace(/\r\n/g,`
|
|
164
|
+
`);if(s){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
`)!==-1)f=f.replace(/\n{3,}/g,`
|
|
168
|
+
|
|
169
|
+
`);f=rm(f,u)}if(a||c)f=im(f,{sort:a,group:c});if(i>0)f=om(f,i,u);if(o&&!f.endsWith(`
|
|
170
|
+
`))f+=`
|
|
171
|
+
`;return f}function rm(e,t){let r=e.split(`
|
|
172
|
+
`),n=[];for(let i of r){let o=i.match(/^(\s*)(.*)$/);if(!o){n.push(i);continue}let[,s,a]=o;if(!a){n.push("");continue}let c=s.replace(/\t/g," ").length,f=Math.floor(c/2);n.push(t.repeat(f)+a)}return n.join(`
|
|
173
|
+
`)}function im(e,t){let r=e.split(`
|
|
174
|
+
`),n=[],i=[],o=!1,s=0;for(let c=0;c<r.length;c++){let f=r[c],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){o=!0,s=c;let h=u[1];n.push({line:f,source:u[2],isType:h.startsWith("import type ")||h.startsWith("import type\t")})}else if(o&&f.trim()==="")continue;else{if(o)o=!1;i.push(f)}}if(n.length===0)return e;if(t.sort)n.sort((c,f)=>{if(c.isType!==f.isType)return c.isType?1:-1;return nm(c.source,f.source)});let a;if(t.group){let c=[],f=[],u=[],h=[],l=[];for(let y=0;y<n.length;y++){let C=n[y],S=C.source;if(S.charCodeAt(0)===46)l.push(C);else if(S.startsWith("node:"))c.push(C);else if(S.charCodeAt(0)===64)h.push(C);else if(S.includes("/"))u.push(C);else f.push(C)}a=[...c.map((y)=>y.line),...c.length>0&&f.length>0?[""]:[],...f.map((y)=>y.line),...(c.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((y)=>y.line),...h.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...h.map((y)=>y.line),...l.length>0?[""]:[],...l.map((y)=>y.line)]}else a=n.map((c)=>c.line);return[...a,"",...i].join(`
|
|
175
|
+
`)}function nm(e,t){let r=e.startsWith("node:"),n=t.startsWith("node:");if(r!==n)return r?-1:1;let i=e.startsWith("."),o=t.startsWith(".");if(i!==o)return i?1:-1;return e.localeCompare(t)}function om(e,t,r){let n=e.split(`
|
|
176
|
+
`),i=[];for(let o of n){if(o.length<=t){i.push(o);continue}if(o.trimStart().startsWith("import ")){i.push(o);continue}let s=o.match(/^(\s*)/)?.[1]||"",a=s+r,c=am(o,s,a);if(c){i.push(...c);continue}if(o.includes("{")&&o.includes("}")){let f=lm(o,t,s,a);i.push(...f);continue}if(o.includes(" | ")){let f=cm(o,t,s,a);i.push(...f);continue}i.push(o)}return i.join(`
|
|
177
|
+
`)}function am(e,t,r){let n=e.match(sm);if(!n)return null;let[,i,o,s,a]=n,c=s.split(",").map((h)=>h.trim()).filter(Boolean);if(c.length<=1)return[e];let f=`${t}${i}${o??""} {`,u=a?`${t}} ${a};`:`${t}};`;return[f,...c.map((h)=>`${r}${h},`),u]}function lm(e,t,r,n){let i=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!i)return[e];let[,,o,s,a,c]=i,f=a.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${r}${o}${s}`,...f.map((u)=>`${n}${u.trim()};`),`${r}${c.trim()}`]}function cm(e,t,r,n){let i=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!i)return[e];let[,,o,s]=i,a=s.split(/\s*\|\s*/).filter((c)=>c.trim());if(a.length<=2)return[e];return[`${r}${o}`,...a.map((c,f)=>`${n}${f>0?"| ":" "}${c.trim()}`)]}async function tc(e,t={},r){let n=[];if(t.usePrettier!==!1){if(await Xd())try{let i={...await Qd(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await em(e,i),usedPrettier:!0}}catch(i){n.push(`Prettier formatting failed: ${i}. Using built-in formatter.`)}else if(t.usePrettier===!0)n.push("Prettier requested but not available. Using built-in formatter.")}return{content:tm(e,t.builtIn),usedPrettier:!1,warnings:n.length>0?n:void 0}}var Hi=null,Ft=null,sm;var rc=he(()=>{sm=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/});class zi{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 n=await r.onStart(t);if(n)t=n}return this.config=t,t}async runOnBeforeFile(e,t){let r=t;for(let n of this.plugins)if(n.onBeforeFile){let i={filePath:e,sourceCode:t,content:r,config:this.config,log:this.createLogger(n.name)},o=await n.onBeforeFile(i);if(typeof o==="string")r=o}return r}async runOnDeclarations(e,t,r){let n=r;for(let i of this.plugins)if(i.onDeclarations){let o={filePath:e,sourceCode:t,declarations:n,config:this.config,log:this.createLogger(i.name)},s=await i.onDeclarations(o);if(s)n=s}return n}async runOnAfterFile(e,t,r){let n=r;for(let i of this.plugins)if(i.onAfterFile){let o={filePath:e,sourceCode:t,content:n,config:this.config,log:this.createLogger(i.name)},s=await i.onAfterFile(o);if(typeof s==="string")n=s}return n}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,r){for(let n of this.plugins)if(n.onError){let i={filePath:t,sourceCode:r,config:this.config,log:this.createLogger(n.name)};await n.onError(e,i)}}}function fm(e){return e}var M0,D0;var ic=he(()=>{M0=new zi;D0=fm({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(e)=>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 sc(e,t={}){let{lineEnding:r="lf",trailingNewline:n=!0,maxBlankLines:i=1,trimTrailingWhitespace:o=!0,normalizeIndentation:s=!0,indent:a={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:h=!0}=t,l=e;if(l=dm(l,r),f?.enabled!==!1)l=Cm(l,f||{});if(c)l=wm(l,c);if(o)l=mm(l);if(l=pm(l,i),s)l=ym(l,a);if(n||h)l=gm(l);return l}function dm(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
|
|
178
|
+
`)!==-1)r=r.replace(/\r\n/g,`
|
|
179
|
+
`);if(r.indexOf("\r")!==-1)r=r.replace(/\r/g,`
|
|
180
|
+
`)}if(t==="crlf")r=r.replace(/\n/g,`\r
|
|
181
|
+
`);return r}function mm(e){return e.split(`
|
|
182
|
+
`).map((t)=>t.replace(/[\t ]+$/,"")).join(`
|
|
183
|
+
`)}function pm(e,t){let r=new RegExp(`\\n{${t+2},}`,"g");return e.replace(r,`
|
|
184
|
+
`.repeat(t+1))}function gm(e){return`${e.replace(/\s+$/,"")}
|
|
185
|
+
`}function ym(e,t){let{style:r="spaces",size:n=2}=t,i=r==="tabs"?"\t":" ".repeat(n),o=e.split(`
|
|
186
|
+
`),s=[];for(let a of o){let c=a.match(/^([\t ]*)(.*)$/);if(!c){s.push(a);continue}let[,f,u]=c;if(!u){s.push("");continue}let h=f.replace(/\t/g," "),l=Math.floor(h.length/2);s.push(i.repeat(l)+u)}return s.join(`
|
|
187
|
+
`)}function Cm(e,t){let{groups:r=hm,separateGroups:n=!0,alphabetize:i=!0}=t,o=e.split(`
|
|
188
|
+
`),s=[],a=[],c=-1;for(let C=0;C<o.length;C++){let S=o[C],x=nc(S);if(x)s.push({line:S,source:x.source,group:x.group,isType:x.isType}),c=C;else if(s.length>0&&S.trim()==="")continue;else if(s.length>0||S.trim()!==""){if(s.length===0||C>c+1)a.push(S)}}if(s.length===0)return e;let f=new Map;for(let C of r)f.set(C,[]);for(let C of s)(f.get(C.group)||f.get("external")||[]).push(C);if(i)for(let[,C]of f)C.sort((S,x)=>{if(S.isType!==x.isType)return S.isType?1:-1;return S.source.localeCompare(x.source)});let u=[],h=null;for(let C of r){let S=f.get(C)||[];if(S.length===0)continue;if(n&&h!==null)u.push("");for(let x of S)u.push(x.line);h=C}let l=o.slice(0,o.findIndex((C)=>nc(C)!==null)),y=a;while(y.length>0&&y[0].trim()==="")y.shift();return[...l,...u,"",...y].join(`
|
|
189
|
+
`)}function nc(e){let t=e.trim(),r=t.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!r){let o=t.match(/^import\s+['"]([^'"]+)['"]/);if(o)return{source:o[1],group:oc(o[1]),isType:!1};return null}let n=!!r[1],i=r[2];return{source:i,group:n?"type":oc(i),isType:n}}function oc(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 wm(e,t){let{kinds:r=um,alphabetize:n=!1,groupExports:i=!0}=t,o=e.split(`
|
|
190
|
+
`),s=[],a=[],c=[],f=null,u=0,h=!0,l=!1,y=[];for(let x=0;x<o.length;x++){let v=o[x],G=v.trim(),L=u,P=G.startsWith("///"),F=L===0&&!P&&(G.startsWith("//")||G.startsWith("/*"));if(l||F){if(y.push(v),!l&&G.startsWith("/*")&&!G.includes("*/"))l=!0;else if(l&&G.includes("*/"))l=!1;continue}if(L===0&&y.length>0&&G===""){y.push(v);continue}u+=(v.match(/\{/g)||[]).length,u-=(v.match(/\}/g)||[]).length;let I=vm(G);if(h&&I&&I.kind!=="import"&&!G.startsWith("//")&&!G.startsWith("/*"))h=!1;if(h){if(y.length>0){if(I?.kind==="import"||!I)a.push(...y),y.length=0}a.push(v);continue}if(I&&u<=1){if(f)s.push(f);f={lines:y.length>0?[...y,v]:[v],kind:I.kind,name:I.name,isExport:I.isExport},y.length=0}else if(f)f.lines.push(v);else{if(G==="")continue;c.push(v)}}if(f)s.push(f);if(y.length>0)c.push(...y);s.sort((x,v)=>{if(i&&x.isExport!==v.isExport)return x.isExport?-1:1;let G=r.indexOf(x.kind),L=r.indexOf(v.kind),P=G>=0?G:r.length,F=L>=0?L:r.length;if(P!==F)return P-F;if(n)return x.name.localeCompare(v.name);return 0});let C=[...a],S=null;for(let x of s){if(S!==null&&x.kind!==S)C.push("");C.push(...x.lines),S=x.kind}if(c.length>0)C.push(""),C.push(...c);return C.join(`
|
|
191
|
+
`)}function vm(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 um,hm;var ac=he(()=>{um=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],hm=["builtin","external","scoped","internal","parent","sibling","index","type"]});function Am(e){switch(e){case"strict":return Em;case"readonly":return Sm;case"simplified":return $m;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 cc{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...bm);if(e.presets)for(let t of e.presets)this.rules.push(...Am(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],n=typeof r.pattern==="string"?new RegExp(r.pattern.replace(xm,"\\$&"),r.global?"g":""):r.pattern;e[t]={rule:r,regex:n}}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":""}`,n=this.cache.get(r);if(n!==void 0)return n;let i=e,o=null;for(let s=0;s<this.compiled.length;s++){let{rule:a,regex:c}=this.compiled[s];if(a.condition){if(!o)o={type:e,...t};if(!a.condition(o))continue}if(c.lastIndex=0,c.test(i)){if(c.lastIndex=0,i=i.replace(c,a.replacement),c.lastIndex=0,!a.global)break}}if(this.cache.size>=lc){let s=Math.ceil(lc*0.1),a=0;for(let c of this.cache.keys()){if(a++>=s)break;this.cache.delete(c)}}return this.cache.set(r,i),i}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 n=typeof r.pattern==="string"?r.pattern:r.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?n!==e:!e.test(n)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function Ji(e={rules:[]}){return new cc(e)}function fc(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>`: ${t.map(i.trim(),r)}`)}var bm,Em,Sm,$m,xm,lc=2048,N0,L0;var uc=he(()=>{bm=[{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}],Em=[{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}],Sm=[{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}],$m=[{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}];xm=/[.*+?^${}()|[\]\\]/g;N0=Ji({rules:[]}),L0=Ji({rules:[],presets:["strict"]})});var hc;var dc=he(()=>{hc=new Set(["ANGLE_instanced_arrays","ARIAMixin","AacBitstreamFormat","AacEncoderConfig","AbortController","AbortSignal","AbortSignalEventMap","AbstractRange","AbstractWorker","AbstractWorkerEventMap","ActiveXObject","AddEventListenerOptions","AddressErrors","AddressType","AddressValue","AesCbcParams","AesCtrParams","AesDerivedKeyParams","AesGcmParams","AesKeyAlgorithm","AesKeyGenParams","AggregateError","AggregateErrorConstructor","Algorithm","AlgorithmIdentifier","AlignSetting","AllAcceptedCredentialsOptions","AllowSharedBufferSource","AlphaOption","AnalyserNode","AnalyserOptions","Animatable","Animation","AnimationEffect","AnimationEvent","AnimationEventInit","AnimationEventMap","AnimationFrameProvider","AnimationPlayState","AnimationPlaybackEvent","AnimationPlaybackEventInit","AnimationReplaceState","AnimationTimeline","AppendMode","Array","ArrayBuffer","ArrayBufferConstructor","ArrayBufferLike","ArrayBufferTypes","ArrayBufferView","ArrayConstructor","ArrayIterator","ArrayLike","AssignedNodesOptions","AsyncDisposable","AsyncDisposableStack","AsyncDisposableStackConstructor","AsyncGenerator","AsyncGeneratorFunction","AsyncGeneratorFunctionConstructor","AsyncIterable","AsyncIterableIterator","AsyncIterator","AsyncIteratorObject","Atomics","AttestationConveyancePreference","Attr","Audio","AudioBuffer","AudioBufferOptions","AudioBufferSourceNode","AudioBufferSourceOptions","AudioConfiguration","AudioContext","AudioContextLatencyCategory","AudioContextOptions","AudioContextState","AudioData","AudioDataCopyToOptions","AudioDataInit","AudioDataOutputCallback","AudioDecoder","AudioDecoderConfig","AudioDecoderEventMap","AudioDecoderInit","AudioDecoderSupport","AudioDestinationNode","AudioEncoder","AudioEncoderConfig","AudioEncoderEventMap","AudioEncoderInit","AudioEncoderSupport","AudioListener","AudioNode","AudioNodeOptions","AudioParam","AudioParamMap","AudioProcessingEvent","AudioProcessingEventInit","AudioSampleFormat","AudioScheduledSourceNode","AudioScheduledSourceNodeEventMap","AudioTimestamp","AudioWorklet","AudioWorkletNode","AudioWorkletNodeEventMap","AudioWorkletNodeOptions","AuthenticationExtensionsClientInputs","AuthenticationExtensionsClientInputsJSON","AuthenticationExtensionsClientOutputs","AuthenticationExtensionsClientOutputsJSON","AuthenticationExtensionsLargeBlobInputs","AuthenticationExtensionsLargeBlobInputsJSON","AuthenticationExtensionsLargeBlobOutputs","AuthenticationExtensionsLargeBlobOutputsJSON","AuthenticationExtensionsPRFInputs","AuthenticationExtensionsPRFInputsJSON","AuthenticationExtensionsPRFOutputs","AuthenticationExtensionsPRFOutputsJSON","AuthenticationExtensionsPRFValues","AuthenticationExtensionsPRFValuesJSON","AuthenticationResponseJSON","AuthenticatorAssertionResponse","AuthenticatorAssertionResponseJSON","AuthenticatorAttachment","AuthenticatorAttestationResponse","AuthenticatorAttestationResponseJSON","AuthenticatorResponse","AuthenticatorSelectionCriteria","AuthenticatorTransport","AutoFill","AutoFillAddressKind","AutoFillBase","AutoFillContactField","AutoFillContactKind","AutoFillCredentialField","AutoFillField","AutoFillNormalField","AutoFillSection","AutoKeyword","AutomationRate","AvcBitstreamFormat","AvcEncoderConfig","Awaited","BarProp","Base64URLString","BaseAudioContext","BaseAudioContextEventMap","BeforeUnloadEvent","BigInt","BigInt64Array","BigInt64ArrayConstructor","BigIntConstructor","BigIntToLocaleStringOptions","BigInteger","BigUint64Array","BigUint64ArrayConstructor","BinaryType","BiquadFilterNode","BiquadFilterOptions","BiquadFilterType","BitrateMode","Blob","BlobCallback","BlobEvent","BlobEventInit","BlobPart","BlobPropertyBag","Body","BodyInit","Boolean","BooleanConstructor","BroadcastChannel","BroadcastChannelEventMap","Buffer","BufferEncoding","BufferSource","BuiltinIteratorReturn","Bun","BunFile","ByteLengthQueuingStrategy","CDATASection","COSEAlgorithmIdentifier","CSS","CSSAnimation","CSSConditionRule","CSSContainerRule","CSSCounterStyleRule","CSSFontFaceRule","CSSFontFeatureValuesRule","CSSFontPaletteValuesRule","CSSGroupingRule","CSSImageValue","CSSImportRule","CSSKeyframeRule","CSSKeyframesRule","CSSKeywordValue","CSSKeywordish","CSSLayerBlockRule","CSSLayerStatementRule","CSSMathClamp","CSSMathInvert","CSSMathMax","CSSMathMin","CSSMathNegate","CSSMathOperator","CSSMathProduct","CSSMathSum","CSSMathValue","CSSMatrixComponent","CSSMatrixComponentOptions","CSSMediaRule","CSSNamespaceRule","CSSNestedDeclarations","CSSNumberish","CSSNumericArray","CSSNumericBaseType","CSSNumericType","CSSNumericValue","CSSPageDescriptors","CSSPageRule","CSSPerspective","CSSPerspectiveValue","CSSPositionTryDescriptors","CSSPositionTryRule","CSSPropertyRule","CSSRotate","CSSRule","CSSRuleList","CSSScale","CSSScopeRule","CSSSkew","CSSSkewX","CSSSkewY","CSSStartingStyleRule","CSSStyleDeclaration","CSSStyleDeclarationBase","CSSStyleProperties","CSSStyleRule","CSSStyleSheet","CSSStyleSheetInit","CSSStyleValue","CSSSupportsRule","CSSTransformComponent","CSSTransformValue","CSSTransition","CSSTranslate","CSSUnitValue","CSSUnparsedSegment","CSSUnparsedValue","CSSVariableReferenceValue","CSSViewTransitionRule","Cache","CacheQueryOptions","CacheStorage","CalendarLike","CallableFunction","CanPlayTypeResult","CanvasCaptureMediaStreamTrack","CanvasCompositing","CanvasDirection","CanvasDrawImage","CanvasDrawPath","CanvasFillRule","CanvasFillStrokeStyles","CanvasFilters","CanvasFontKerning","CanvasFontStretch","CanvasFontVariantCaps","CanvasGradient","CanvasImageData","CanvasImageSmoothing","CanvasImageSource","CanvasLineCap","CanvasLineJoin","CanvasPath","CanvasPathDrawingStyles","CanvasPattern","CanvasRect","CanvasRenderingContext2D","CanvasRenderingContext2DSettings","CanvasSettings","CanvasShadowStyles","CanvasState","CanvasText","CanvasTextAlign","CanvasTextBaseline","CanvasTextDrawingStyles","CanvasTextRendering","CanvasTransform","CanvasUserInterface","Capitalize","CaretPosition","CaretPositionFromPointOptions","ChannelCountMode","ChannelInterpretation","ChannelMergerNode","ChannelMergerOptions","ChannelSplitterNode","ChannelSplitterOptions","CharacterData","CheckVisibilityOptions","ChildNode","ClassAccessorDecoratorContext","ClassAccessorDecoratorResult","ClassAccessorDecoratorTarget","ClassDecorator","ClassDecoratorContext","ClassFieldDecoratorContext","ClassGetterDecoratorContext","ClassMemberDecoratorContext","ClassMethodDecoratorContext","ClassSetterDecoratorContext","Client","ClientQueryOptions","ClientRect","ClientTypes","Clients","Clipboard","ClipboardEvent","ClipboardEventInit","ClipboardItem","ClipboardItemData","ClipboardItemOptions","ClipboardItems","CloseEvent","CloseEventInit","CodecState","Collator","CollatorConstructor","CollatorOptions","ColorGamut","ColorSpaceConversion","CommandEvent","CommandEventInit","Comment","CompileError","CompositeOperation","CompositeOperationOrAuto","CompositionEvent","CompositionEventInit","CompressionFormat","CompressionStream","ComputedEffectTiming","ComputedKeyframe","ConcatArray","Console","ConstantSourceNode","ConstantSourceOptions","ConstrainBoolean","ConstrainBooleanOrDOMString","ConstrainBooleanOrDOMStringParameters","ConstrainBooleanParameters","ConstrainDOMString","ConstrainDOMStringParameters","ConstrainDouble","ConstrainDoubleRange","ConstrainULong","ConstrainULongRange","ConstructorParameters","ContentVisibilityAutoStateChangeEvent","ContentVisibilityAutoStateChangeEventInit","ConvolverNode","ConvolverOptions","CookieChangeEvent","CookieChangeEventInit","CookieInit","CookieList","CookieListItem","CookieSameSite","CookieStore","CookieStoreDeleteOptions","CookieStoreEventMap","CookieStoreGetOptions","CookieStoreManager","CountQueuingStrategy","Credential","CredentialCreationOptions","CredentialMediationRequirement","CredentialPropertiesOutput","CredentialRequestOptions","CredentialsContainer","Crypto","CryptoKey","CryptoKeyPair","CurrentUserDetailsOptions","CustomElementConstructor","CustomElementRegistry","CustomEvent","CustomEventInit","CustomStateSet","DOMException","DOMHighResTimeStamp","DOMImplementation","DOMMatrix","DOMMatrix2DInit","DOMMatrixInit","DOMMatrixReadOnly","DOMParser","DOMParserSupportedType","DOMPoint","DOMPointInit","DOMPointReadOnly","DOMQuad","DOMQuadInit","DOMRect","DOMRectInit","DOMRectList","DOMRectReadOnly","DOMStringList","DOMStringMap","DOMTokenList","DataTransfer","DataTransferItem","DataTransferItemList","DataView","DataViewConstructor","Date","DateConstructor","DateLikeObject","DateTimeFormat","DateTimeFormatConstructor","DateTimeFormatOptions","DateTimeFormatPart","DateTimeFormatPartTypes","DateTimeFormatPartTypesRegistry","DateTimeLikeObject","DateTimeRangeFormatPart","DateUnit","DecodeErrorCallback","DecodeSuccessCallback","DecompressionStream","DecoratorContext","DecoratorMetadata","DecoratorMetadataObject","DedicatedWorkerGlobalScope","DedicatedWorkerGlobalScopeEventMap","DelayNode","DelayOptions","DeviceMotionEvent","DeviceMotionEventAcceleration","DeviceMotionEventAccelerationInit","DeviceMotionEventInit","DeviceMotionEventRotationRate","DeviceMotionEventRotationRateInit","DeviceOrientationEvent","DeviceOrientationEventInit","DigitalCredential","DirectionSetting","Dirent","DisambiguationOptions","DisplayCaptureSurfaceType","DisplayMediaStreamOptions","DisplayNames","DisplayNamesFallback","DisplayNamesLanguageDisplay","DisplayNamesOptions","DisplayNamesType","Disposable","DisposableStack","DisposableStackConstructor","DistanceModelType","Document","DocumentEventMap","DocumentFragment","DocumentOrShadowRoot","DocumentReadyState","DocumentTimeline","DocumentTimelineOptions","DocumentType","DocumentVisibilityState","DoubleRange","DragEvent","DragEventInit","Duration","DurationConstructor","DurationFormat","DurationFormatDisplayOption","DurationFormatLocaleMatcher","DurationFormatOptions","DurationFormatPart","DurationFormatStyle","DurationFormatUnit","DurationFormatUnitSingular","DurationLike","DurationLikeObject","DurationRelativeToOptions","DurationRoundingOptions","DurationToStringOptions","DurationTotalOptions","DynamicsCompressorNode","DynamicsCompressorOptions","EXT_blend_minmax","EXT_color_buffer_float","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_sRGB","EXT_shader_texture_lod","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","EXT_texture_norm16","EcKeyAlgorithm","EcKeyGenParams","EcKeyImportParams","EcdhKeyDeriveParams","EcdsaParams","EffectTiming","Element","ElementCSSInlineStyle","ElementContentEditable","ElementCreationOptions","ElementDefinitionOptions","ElementEventMap","ElementInternals","ElementTagNameMap","EncodedAudioChunk","EncodedAudioChunkInit","EncodedAudioChunkMetadata","EncodedAudioChunkOutputCallback","EncodedAudioChunkType","EncodedVideoChunk","EncodedVideoChunkInit","EncodedVideoChunkMetadata","EncodedVideoChunkOutputCallback","EncodedVideoChunkType","EndOfStreamError","EndingType","Enumerator","EnumeratorConstructor","EpochTimeStamp","Error","ErrorCallback","ErrorConstructor","ErrorEvent","ErrorEventInit","ErrorOptions","EvalError","EvalErrorConstructor","Event","EventCounts","EventInit","EventListener","EventListenerObject","EventListenerOptions","EventListenerOrEventListenerObject","EventModifierInit","EventSource","EventSourceEventMap","EventSourceInit","EventTarget","Exception","ExceptionOptions","Exclude","ExportValue","Exports","ExtendableCookieChangeEvent","ExtendableCookieChangeEventInit","ExtendableEvent","ExtendableEventInit","ExtendableMessageEvent","ExtendableMessageEventInit","External","Extract","FetchEvent","FetchEventInit","File","FileCallback","FileList","FilePropertyBag","FileReader","FileReaderEventMap","FileReaderSync","FileSink","FileSystem","FileSystemCreateWritableOptions","FileSystemDirectoryEntry","FileSystemDirectoryHandle","FileSystemDirectoryHandleAsyncIterator","FileSystemDirectoryReader","FileSystemEntriesCallback","FileSystemEntry","FileSystemEntryCallback","FileSystemFileEntry","FileSystemFileHandle","FileSystemFlags","FileSystemGetDirectoryOptions","FileSystemGetFileOptions","FileSystemHandle","FileSystemHandleKind","FileSystemReadWriteOptions","FileSystemRemoveOptions","FileSystemSyncAccessHandle","FileSystemWritableFileStream","FileSystemWriteChunkType","FillLightMode","FillMode","FinalizationRegistry","FinalizationRegistryConstructor","FlatArray","Float16Array","Float16ArrayConstructor","Float32Array","Float32ArrayConstructor","Float32List","Float64Array","Float64ArrayConstructor","FocusEvent","FocusEventInit","FocusOptions","FontDisplay","FontFace","FontFaceDescriptors","FontFaceLoadStatus","FontFaceSet","FontFaceSetEventMap","FontFaceSetLoadEvent","FontFaceSetLoadEventInit","FontFaceSetLoadStatus","FontFaceSource","FormData","FormDataEntryValue","FormDataEvent","FormDataEventInit","FormDataIterator","FormattableTemporalObject","FragmentDirective","FrameRequestCallback","FrameType","FullscreenNavigationUI","FullscreenOptions","Function","FunctionConstructor","FunctionStringCallback","GLbitfield","GLboolean","GLclampf","GLenum","GLfloat","GLint","GLint64","GLintptr","GLsizei","GLsizeiptr","GLuint","GLuint64","GPU","GPUAdapter","GPUAdapterInfo","GPUAddressMode","GPUAutoLayoutMode","GPUBindGroup","GPUBindGroupDescriptor","GPUBindGroupEntry","GPUBindGroupLayout","GPUBindGroupLayoutDescriptor","GPUBindGroupLayoutEntry","GPUBindingCommandsMixin","GPUBindingResource","GPUBlendComponent","GPUBlendFactor","GPUBlendOperation","GPUBlendState","GPUBuffer","GPUBufferBinding","GPUBufferBindingLayout","GPUBufferBindingType","GPUBufferDescriptor","GPUBufferDynamicOffset","GPUBufferMapState","GPUBufferUsageFlags","GPUCanvasAlphaMode","GPUCanvasConfiguration","GPUCanvasContext","GPUCanvasToneMapping","GPUCanvasToneMappingMode","GPUColor","GPUColorDict","GPUColorTargetState","GPUColorWriteFlags","GPUCommandBuffer","GPUCommandBufferDescriptor","GPUCommandEncoder","GPUCommandEncoderDescriptor","GPUCompareFunction","GPUCompilationInfo","GPUCompilationMessage","GPUCompilationMessageType","GPUComputePassDescriptor","GPUComputePassEncoder","GPUComputePassTimestampWrites","GPUComputePipeline","GPUComputePipelineDescriptor","GPUCopyExternalImageDestInfo","GPUCopyExternalImageSource","GPUCopyExternalImageSourceInfo","GPUCullMode","GPUDebugCommandsMixin","GPUDepthBias","GPUDepthStencilState","GPUDevice","GPUDeviceDescriptor","GPUDeviceEventMap","GPUDeviceLostInfo","GPUDeviceLostReason","GPUError","GPUErrorFilter","GPUExtent3D","GPUExtent3DDict","GPUExternalTexture","GPUExternalTextureBindingLayout","GPUExternalTextureDescriptor","GPUFeatureName","GPUFilterMode","GPUFlagsConstant","GPUFragmentState","GPUFrontFace","GPUIndex32","GPUIndexFormat","GPUIntegerCoordinate","GPUIntegerCoordinateOut","GPUInternalError","GPULoadOp","GPUMapModeFlags","GPUMipmapFilterMode","GPUMultisampleState","GPUObjectBase","GPUObjectDescriptorBase","GPUOrigin2D","GPUOrigin2DDict","GPUOrigin3D","GPUOrigin3DDict","GPUOutOfMemoryError","GPUPipelineBase","GPUPipelineConstantValue","GPUPipelineDescriptorBase","GPUPipelineError","GPUPipelineErrorInit","GPUPipelineErrorReason","GPUPipelineLayout","GPUPipelineLayoutDescriptor","GPUPowerPreference","GPUPrimitiveState","GPUPrimitiveTopology","GPUProgrammableStage","GPUQuerySet","GPUQuerySetDescriptor","GPUQueryType","GPUQueue","GPUQueueDescriptor","GPURenderBundle","GPURenderBundleDescriptor","GPURenderBundleEncoder","GPURenderBundleEncoderDescriptor","GPURenderCommandsMixin","GPURenderPassColorAttachment","GPURenderPassDepthStencilAttachment","GPURenderPassDescriptor","GPURenderPassEncoder","GPURenderPassLayout","GPURenderPassTimestampWrites","GPURenderPipeline","GPURenderPipelineDescriptor","GPURequestAdapterOptions","GPUSampleMask","GPUSampler","GPUSamplerBindingLayout","GPUSamplerBindingType","GPUSamplerDescriptor","GPUShaderModule","GPUShaderModuleDescriptor","GPUShaderStageFlags","GPUSignedOffset32","GPUSize32","GPUSize32Out","GPUSize64","GPUSize64Out","GPUStencilFaceState","GPUStencilOperation","GPUStencilValue","GPUStorageTextureAccess","GPUStorageTextureBindingLayout","GPUStoreOp","GPUSupportedFeatures","GPUSupportedLimits","GPUTexelCopyBufferInfo","GPUTexelCopyBufferLayout","GPUTexelCopyTextureInfo","GPUTexture","GPUTextureAspect","GPUTextureBindingLayout","GPUTextureDescriptor","GPUTextureDimension","GPUTextureFormat","GPUTextureSampleType","GPUTextureUsageFlags","GPUTextureView","GPUTextureViewDescriptor","GPUTextureViewDimension","GPUUncapturedErrorEvent","GPUUncapturedErrorEventInit","GPUValidationError","GPUVertexAttribute","GPUVertexBufferLayout","GPUVertexFormat","GPUVertexState","GPUVertexStepMode","GainNode","GainOptions","Gamepad","GamepadButton","GamepadEffectParameters","GamepadEvent","GamepadEventInit","GamepadHapticActuator","GamepadHapticEffectType","GamepadHapticsResult","GamepadMappingType","Generator","GeneratorFunction","GeneratorFunctionConstructor","GenericTransformStream","Geolocation","GeolocationCoordinates","GeolocationPosition","GeolocationPositionError","GetAnimationsOptions","GetComposedRangesOptions","GetHTMLOptions","GetNotificationOptions","GetRootNodeOptions","Global","GlobalCompositeOperation","GlobalDescriptor","GlobalEventHandlers","GlobalEventHandlersEventMap","HTMLAllCollection","HTMLAnchorElement","HTMLAreaElement","HTMLAudioElement","HTMLBRElement","HTMLBaseElement","HTMLBodyElement","HTMLBodyElementEventMap","HTMLButtonElement","HTMLCanvasElement","HTMLCollection","HTMLCollectionBase","HTMLCollectionOf","HTMLDListElement","HTMLDataElement","HTMLDataListElement","HTMLDetailsElement","HTMLDialogElement","HTMLDirectoryElement","HTMLDivElement","HTMLDocument","HTMLElement","HTMLElementDeprecatedTagNameMap","HTMLElementEventMap","HTMLElementTagNameMap","HTMLEmbedElement","HTMLFieldSetElement","HTMLFontElement","HTMLFormControlsCollection","HTMLFormElement","HTMLFrameElement","HTMLFrameSetElement","HTMLFrameSetElementEventMap","HTMLHRElement","HTMLHeadElement","HTMLHeadingElement","HTMLHtmlElement","HTMLHyperlinkElementUtils","HTMLIFrameElement","HTMLImageElement","HTMLInputElement","HTMLLIElement","HTMLLabelElement","HTMLLegendElement","HTMLLinkElement","HTMLMapElement","HTMLMarqueeElement","HTMLMediaElement","HTMLMediaElementEventMap","HTMLMenuElement","HTMLMetaElement","HTMLMeterElement","HTMLModElement","HTMLOListElement","HTMLObjectElement","HTMLOptGroupElement","HTMLOptionElement","HTMLOptionsCollection","HTMLOrSVGElement","HTMLOrSVGImageElement","HTMLOrSVGScriptElement","HTMLOutputElement","HTMLParagraphElement","HTMLParamElement","HTMLPictureElement","HTMLPreElement","HTMLProgressElement","HTMLQuoteElement","HTMLScriptElement","HTMLSelectElement","HTMLSlotElement","HTMLSourceElement","HTMLSpanElement","HTMLStyleElement","HTMLTableCaptionElement","HTMLTableCellElement","HTMLTableColElement","HTMLTableDataCellElement","HTMLTableElement","HTMLTableHeaderCellElement","HTMLTableRowElement","HTMLTableSectionElement","HTMLTemplateElement","HTMLTextAreaElement","HTMLTimeElement","HTMLTitleElement","HTMLTrackElement","HTMLUListElement","HTMLUnknownElement","HTMLVideoElement","HTMLVideoElementEventMap","HardwareAcceleration","HashAlgorithmIdentifier","HashChangeEvent","HashChangeEventInit","HdrMetadataType","Headers","HeadersInit","HeadersIterator","Highlight","HighlightRegistry","HighlightType","History","HkdfParams","HmacImportParams","HmacKeyAlgorithm","HmacKeyGenParams","IArguments","IDBCursor","IDBCursorDirection","IDBCursorWithValue","IDBDatabase","IDBDatabaseEventMap","IDBDatabaseInfo","IDBFactory","IDBIndex","IDBIndexParameters","IDBKeyRange","IDBObjectStore","IDBObjectStoreParameters","IDBOpenDBRequest","IDBOpenDBRequestEventMap","IDBRequest","IDBRequestEventMap","IDBRequestReadyState","IDBTransaction","IDBTransactionDurability","IDBTransactionEventMap","IDBTransactionMode","IDBTransactionOptions","IDBValidKey","IDBVersionChangeEvent","IDBVersionChangeEventInit","IIRFilterNode","IIRFilterOptions","ITextWriter","IdleDeadline","IdleRequestCallback","IdleRequestOptions","Image","ImageBitmap","ImageBitmapOptions","ImageBitmapRenderingContext","ImageBitmapRenderingContextSettings","ImageBitmapSource","ImageBufferSource","ImageCapture","ImageData","ImageDataArray","ImageDataPixelFormat","ImageDataSettings","ImageDecodeOptions","ImageDecodeResult","ImageDecoder","ImageDecoderInit","ImageEncodeOptions","ImageOrientation","ImageSmoothingQuality","ImageTrack","ImageTrackList","Immediate","ImportAssertions","ImportAttributes","ImportCallOptions","ImportExportKind","ImportMeta","ImportNodeOptions","ImportValue","Imports","Infinity","InputDeviceInfo","InputEvent","InputEventInit","InsertPosition","Instance","InstanceType","Instant","InstantConstructor","InstantLike","InstantToStringOptions","Int16Array","Int16ArrayConstructor","Int32Array","Int32ArrayConstructor","Int32List","Int8Array","Int8ArrayConstructor","IntersectionObserver","IntersectionObserverCallback","IntersectionObserverEntry","IntersectionObserverInit","Intl","Iterable","IterableIterator","IterationCompositeOperation","Iterator","IteratorConstructor","IteratorObject","IteratorObjectConstructor","IteratorResult","IteratorReturnResult","IteratorYieldResult","JSON","JsonWebKey","KHR_parallel_shader_compile","KeyAlgorithm","KeyFormat","KeySystemTrackConfiguration","KeyType","KeyUsage","KeyboardEvent","KeyboardEventInit","Keyframe","KeyframeAnimationOptions","KeyframeEffect","KeyframeEffectOptions","LDMLPluralRule","LargestContentfulPaint","LatencyMode","LineAlignSetting","LineAndPositionSetting","LinkError","LinkStyle","ListFormat","ListFormatLocaleMatcher","ListFormatOptions","ListFormatStyle","ListFormatType","Locale","LocaleCollationCaseFirst","LocaleHourCycleKey","LocaleOptions","LocalesArgument","Location","Lock","LockGrantedCallback","LockInfo","LockManager","LockManagerSnapshot","LockMode","LockOptions","LoginStatus","Lowercase","MIDIAccess","MIDIAccessEventMap","MIDIConnectionEvent","MIDIConnectionEventInit","MIDIInput","MIDIInputEventMap","MIDIInputMap","MIDIMessageEvent","MIDIMessageEventInit","MIDIOptions","MIDIOutput","MIDIOutputMap","MIDIPort","MIDIPortConnectionState","MIDIPortDeviceState","MIDIPortEventMap","MIDIPortType","Map","MapConstructor","MapIterator","Math","MathMLElement","MathMLElementEventMap","MathMLElementTagNameMap","MediaCapabilities","MediaCapabilitiesDecodingInfo","MediaCapabilitiesEncodingInfo","MediaCapabilitiesInfo","MediaCapabilitiesKeySystemConfiguration","MediaConfiguration","MediaDecodingConfiguration","MediaDecodingType","MediaDeviceInfo","MediaDeviceKind","MediaDevices","MediaDevicesEventMap","MediaElementAudioSourceNode","MediaElementAudioSourceOptions","MediaEncodingConfiguration","MediaEncodingType","MediaEncryptedEvent","MediaEncryptedEventInit","MediaError","MediaImage","MediaKeyMessageEvent","MediaKeyMessageEventInit","MediaKeyMessageType","MediaKeySession","MediaKeySessionClosedReason","MediaKeySessionEventMap","MediaKeySessionType","MediaKeyStatus","MediaKeyStatusMap","MediaKeyStatusMapIterator","MediaKeySystemAccess","MediaKeySystemConfiguration","MediaKeySystemMediaCapability","MediaKeys","MediaKeysPolicy","MediaKeysRequirement","MediaList","MediaMetadata","MediaMetadataInit","MediaPositionState","MediaProvider","MediaQueryList","MediaQueryListEvent","MediaQueryListEventInit","MediaQueryListEventMap","MediaRecorder","MediaRecorderEventMap","MediaRecorderOptions","MediaSession","MediaSessionAction","MediaSessionActionDetails","MediaSessionActionHandler","MediaSessionPlaybackState","MediaSettingsRange","MediaSource","MediaSourceEventMap","MediaSourceHandle","MediaStream","MediaStreamAudioDestinationNode","MediaStreamAudioSourceNode","MediaStreamAudioSourceOptions","MediaStreamConstraints","MediaStreamEventMap","MediaStreamTrack","MediaStreamTrackEvent","MediaStreamTrackEventInit","MediaStreamTrackEventMap","MediaStreamTrackProcessor","MediaStreamTrackProcessorInit","MediaStreamTrackState","MediaTrackCapabilities","MediaTrackConstraintSet","MediaTrackConstraints","MediaTrackSettings","MediaTrackSupportedConstraints","Memory","MemoryDescriptor","MessageChannel","MessageEvent","MessageEventInit","MessageEventSource","MessageEventTarget","MessageEventTargetEventMap","MessagePort","MessagePortEventMap","MethodDecorator","MimeType","MimeTypeArray","Module","ModuleExportDescriptor","ModuleImportDescriptor","ModuleImports","MouseEvent","MouseEventInit","MultiCacheQueryOptions","MutationCallback","MutationObserver","MutationObserverInit","MutationRecord","MutationRecordType","NaN","NamedCurve","NamedNodeMap","NavigateEvent","NavigateEventInit","Navigation","NavigationActivation","NavigationCurrentEntryChangeEvent","NavigationCurrentEntryChangeEventInit","NavigationDestination","NavigationEventMap","NavigationFocusReset","NavigationHistoryBehavior","NavigationHistoryEntry","NavigationHistoryEntryEventMap","NavigationInterceptHandler","NavigationInterceptOptions","NavigationNavigateOptions","NavigationOptions","NavigationPrecommitController","NavigationPrecommitHandler","NavigationPreloadManager","NavigationPreloadState","NavigationReloadOptions","NavigationResult","NavigationScrollBehavior","NavigationTimingType","NavigationTransition","NavigationType","NavigationUpdateCurrentEntryOptions","Navigator","NavigatorAutomationInformation","NavigatorBadge","NavigatorConcurrentHardware","NavigatorContentUtils","NavigatorCookies","NavigatorGPU","NavigatorID","NavigatorLanguage","NavigatorLocks","NavigatorLogin","NavigatorOnLine","NavigatorPlugins","NavigatorStorage","NewableFunction","NoInfer","Node","NodeFilter","NodeIterator","NodeJS","NodeList","NodeListOf","NodeModule","NodeRequire","NonDocumentTypeChildNode","NonElementParentNode","NonNullable","Notification","NotificationDirection","NotificationEvent","NotificationEventInit","NotificationEventMap","NotificationOptions","NotificationPermission","NotificationPermissionCallback","Now","Number","NumberConstructor","NumberFormat","NumberFormatConstructor","NumberFormatOptions","NumberFormatOptionsCurrencyDisplay","NumberFormatOptionsCurrencyDisplayRegistry","NumberFormatOptionsSignDisplay","NumberFormatOptionsSignDisplayRegistry","NumberFormatOptionsStyle","NumberFormatOptionsStyleRegistry","NumberFormatOptionsUseGrouping","NumberFormatOptionsUseGroupingRegistry","NumberFormatPart","NumberFormatPartTypeRegistry","NumberFormatPartTypes","NumberFormatRangePartTypeRegistry","NumberFormatRangePartTypes","NumberRangeFormatPart","OES_draw_buffers_indexed","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","OVR_multiview2","Object","ObjectConstructor","OfflineAudioCompletionEvent","OfflineAudioCompletionEventInit","OfflineAudioContext","OfflineAudioContextEventMap","OfflineAudioContextOptions","OffscreenCanvas","OffscreenCanvasEventMap","OffscreenCanvasRenderingContext2D","OffscreenRenderingContext","OffscreenRenderingContextId","Omit","OmitThisParameter","OnBeforeUnloadEventHandler","OnBeforeUnloadEventHandlerNonNull","OnErrorEventHandler","OnErrorEventHandlerNonNull","Option","OptionalEffectTiming","OptionalPostfixToken","OptionalPrefixToken","OpusBitstreamFormat","OpusEncoderConfig","OrientationLockType","OrientationType","OscillatorNode","OscillatorOptions","OscillatorType","OverSampleType","OverconstrainedError","OverflowOptions","PageRevealEvent","PageRevealEventInit","PageSwapEvent","PageSwapEventInit","PageTransitionEvent","PageTransitionEventInit","PaintTimingMixin","PannerNode","PannerOptions","PanningModelType","ParameterDecorator","Parameters","ParentNode","Partial","PartialTemporalLike","Path2D","PayerErrors","PaymentAddress","PaymentComplete","PaymentCurrencyAmount","PaymentDetailsBase","PaymentDetailsInit","PaymentDetailsModifier","PaymentDetailsUpdate","PaymentItem","PaymentMethodChangeEvent","PaymentMethodChangeEventInit","PaymentMethodData","PaymentOptions","PaymentRequest","PaymentRequestEventMap","PaymentRequestUpdateEvent","PaymentRequestUpdateEventInit","PaymentResponse","PaymentResponseEventMap","PaymentShippingOption","PaymentShippingType","PaymentValidationErrors","Pbkdf2Params","Performance","PerformanceEntry","PerformanceEntryList","PerformanceEventMap","PerformanceEventTiming","PerformanceMark","PerformanceMarkOptions","PerformanceMeasure","PerformanceMeasureOptions","PerformanceNavigation","PerformanceNavigationTiming","PerformanceObserver","PerformanceObserverCallback","PerformanceObserverEntryList","PerformanceObserverInit","PerformancePaintTiming","PerformanceResourceTiming","PerformanceServerTiming","PerformanceTiming","PeriodicWave","PeriodicWaveConstraints","PeriodicWaveOptions","PermissionDescriptor","PermissionName","PermissionState","PermissionStatus","PermissionStatusEventMap","Permissions","PhotoCapabilities","PhotoSettings","Pick","PictureInPictureEvent","PictureInPictureEventInit","PictureInPictureWindow","PictureInPictureWindowEventMap","PlainDate","PlainDateConstructor","PlainDateLike","PlainDateTime","PlainDateTimeConstructor","PlainDateTimeLike","PlainDateTimeToStringOptions","PlainDateToStringOptions","PlainDateToZonedDateTimeOptions","PlainMonthDay","PlainMonthDayConstructor","PlainMonthDayLike","PlainMonthDayToPlainDateOptions","PlainTime","PlainTimeConstructor","PlainTimeLike","PlainTimeToStringOptions","PlainYearMonth","PlainYearMonthConstructor","PlainYearMonthLike","PlainYearMonthToPlainDateOptions","PlaneLayout","PlaybackDirection","Plugin","PluginArray","PluralRuleType","PluralRules","PluralRulesConstructor","PluralRulesOptions","PluralizeUnit","PointerEvent","PointerEventInit","PointerLockOptions","PopStateEvent","PopStateEventInit","PopoverTargetAttributes","PositionAlignSetting","PositionCallback","PositionErrorCallback","PositionOptions","PredefinedColorSpace","PremultiplyAlpha","PresentationStyle","ProcessingInstruction","ProgressEvent","ProgressEventInit","Promise","PromiseConstructor","PromiseConstructorLike","PromiseFulfilledResult","PromiseLike","PromiseRejectedResult","PromiseRejectionEvent","PromiseRejectionEventInit","PromiseSettledResult","PromiseWithResolvers","PropertyDecorator","PropertyDefinition","PropertyDescriptor","PropertyDescriptorMap","PropertyIndexedKeyframes","PropertyKey","Proxy","ProxyConstructor","ProxyHandler","PublicKeyCredential","PublicKeyCredentialClientCapabilities","PublicKeyCredentialCreationOptions","PublicKeyCredentialCreationOptionsJSON","PublicKeyCredentialDescriptor","PublicKeyCredentialDescriptorJSON","PublicKeyCredentialEntity","PublicKeyCredentialParameters","PublicKeyCredentialRequestOptions","PublicKeyCredentialRequestOptionsJSON","PublicKeyCredentialRpEntity","PublicKeyCredentialType","PublicKeyCredentialUserEntity","PublicKeyCredentialUserEntityJSON","PushEncryptionKeyName","PushEvent","PushEventInit","PushManager","PushManagerAttribute","PushMessageData","PushMessageDataInit","PushSubscription","PushSubscriptionChangeEvent","PushSubscriptionChangeEventInit","PushSubscriptionJSON","PushSubscriptionOptions","PushSubscriptionOptionsInit","QueuingStrategy","QueuingStrategyInit","QueuingStrategySize","RTCAnswerOptions","RTCBundlePolicy","RTCCertificate","RTCCertificateExpiration","RTCConfiguration","RTCDTMFSender","RTCDTMFSenderEventMap","RTCDTMFToneChangeEvent","RTCDTMFToneChangeEventInit","RTCDataChannel","RTCDataChannelEvent","RTCDataChannelEventInit","RTCDataChannelEventMap","RTCDataChannelInit","RTCDataChannelState","RTCDegradationPreference","RTCDtlsFingerprint","RTCDtlsRole","RTCDtlsTransport","RTCDtlsTransportEventMap","RTCDtlsTransportState","RTCEncodedAudioFrame","RTCEncodedAudioFrameMetadata","RTCEncodedFrameMetadata","RTCEncodedVideoFrame","RTCEncodedVideoFrameMetadata","RTCError","RTCErrorDetailType","RTCErrorEvent","RTCErrorEventInit","RTCErrorInit","RTCIceCandidate","RTCIceCandidateInit","RTCIceCandidatePair","RTCIceCandidatePairStats","RTCIceCandidateType","RTCIceComponent","RTCIceConnectionState","RTCIceGathererState","RTCIceGatheringState","RTCIceProtocol","RTCIceRole","RTCIceServer","RTCIceTcpCandidateType","RTCIceTransport","RTCIceTransportEventMap","RTCIceTransportPolicy","RTCIceTransportState","RTCInboundRtpStreamStats","RTCLocalIceCandidateInit","RTCLocalSessionDescriptionInit","RTCOfferAnswerOptions","RTCOfferOptions","RTCOutboundRtpStreamStats","RTCPeerConnection","RTCPeerConnectionErrorCallback","RTCPeerConnectionEventMap","RTCPeerConnectionIceErrorEvent","RTCPeerConnectionIceErrorEventInit","RTCPeerConnectionIceEvent","RTCPeerConnectionIceEventInit","RTCPeerConnectionState","RTCPriorityType","RTCQualityLimitationReason","RTCReceivedRtpStreamStats","RTCRtcpMuxPolicy","RTCRtcpParameters","RTCRtpCapabilities","RTCRtpCodec","RTCRtpCodecParameters","RTCRtpCodingParameters","RTCRtpContributingSource","RTCRtpEncodingParameters","RTCRtpHeaderExtensionCapability","RTCRtpHeaderExtensionParameters","RTCRtpParameters","RTCRtpReceiveParameters","RTCRtpReceiver","RTCRtpReceiverTransform","RTCRtpScriptTransform","RTCRtpScriptTransformer","RTCRtpSendParameters","RTCRtpSender","RTCRtpSenderTransform","RTCRtpStreamStats","RTCRtpSynchronizationSource","RTCRtpTransceiver","RTCRtpTransceiverDirection","RTCRtpTransceiverInit","RTCSctpTransport","RTCSctpTransportEventMap","RTCSctpTransportState","RTCSdpType","RTCSentRtpStreamStats","RTCSessionDescription","RTCSessionDescriptionCallback","RTCSessionDescriptionInit","RTCSetParameterOptions","RTCSignalingState","RTCStats","RTCStatsIceCandidatePairState","RTCStatsReport","RTCStatsType","RTCTrackEvent","RTCTrackEventInit","RTCTransformEvent","RTCTransportStats","RadioNodeList","Range","RangeError","RangeErrorConstructor","ReadableByteStreamController","ReadableStream","ReadableStreamAsyncIterator","ReadableStreamBYOBReader","ReadableStreamBYOBReaderReadOptions","ReadableStreamBYOBRequest","ReadableStreamController","ReadableStreamDefaultController","ReadableStreamDefaultReader","ReadableStreamGenericReader","ReadableStreamGetReaderOptions","ReadableStreamIteratorOptions","ReadableStreamReadDoneResult","ReadableStreamReadResult","ReadableStreamReadValueResult","ReadableStreamReader","ReadableStreamReaderMode","ReadableStreamType","ReadableWritablePair","Readonly","ReadonlyArray","ReadonlyMap","ReadonlySet","ReadonlySetLike","ReadyState","Record","RecordingState","RedEyeReduction","ReferenceError","ReferenceErrorConstructor","ReferrerPolicy","Reflect","RegExp","RegExpConstructor","RegExpExecArray","RegExpIndicesArray","RegExpMatchArray","RegExpStringIterator","RegistrationOptions","RegistrationResponseJSON","RelativeTimeFormat","RelativeTimeFormatLocaleMatcher","RelativeTimeFormatNumeric","RelativeTimeFormatOptions","RelativeTimeFormatPart","RelativeTimeFormatStyle","RelativeTimeFormatUnit","RelativeTimeFormatUnitSingular","RemotePlayback","RemotePlaybackAvailabilityCallback","RemotePlaybackEventMap","RemotePlaybackState","RenderingContext","Report","ReportBody","ReportList","ReportingObserver","ReportingObserverCallback","ReportingObserverOptions","Request","RequestCache","RequestCredentials","RequestDestination","RequestInfo","RequestInit","RequestMode","RequestPriority","RequestRedirect","Required","ResidentKeyRequirement","ResizeObserver","ResizeObserverBoxOptions","ResizeObserverCallback","ResizeObserverEntry","ResizeObserverOptions","ResizeObserverSize","ResizeQuality","ResolvedCollatorOptions","ResolvedDateTimeFormatOptions","ResolvedDisplayNamesOptions","ResolvedDurationFormatOptions","ResolvedListFormatOptions","ResolvedNumberFormatOptions","ResolvedNumberFormatOptionsUseGrouping","ResolvedPluralRulesOptions","ResolvedRelativeTimeFormatOptions","ResolvedSegmenterOptions","Response","ResponseInit","ResponseType","ReturnType","RoundingOptions","RoundingOptionsWithLargestUnit","RsaHashedImportParams","RsaHashedKeyAlgorithm","RsaHashedKeyGenParams","RsaKeyAlgorithm","RsaKeyGenParams","RsaOaepParams","RsaOtherPrimesInfo","RsaPssParams","RuntimeError","SVGAElement","SVGAngle","SVGAnimateElement","SVGAnimateMotionElement","SVGAnimateTransformElement","SVGAnimatedAngle","SVGAnimatedBoolean","SVGAnimatedEnumeration","SVGAnimatedInteger","SVGAnimatedLength","SVGAnimatedLengthList","SVGAnimatedNumber","SVGAnimatedNumberList","SVGAnimatedPoints","SVGAnimatedPreserveAspectRatio","SVGAnimatedRect","SVGAnimatedString","SVGAnimatedTransformList","SVGAnimationElement","SVGBoundingBoxOptions","SVGCircleElement","SVGClipPathElement","SVGComponentTransferFunctionElement","SVGDefsElement","SVGDescElement","SVGElement","SVGElementEventMap","SVGElementTagNameMap","SVGEllipseElement","SVGFEBlendElement","SVGFEColorMatrixElement","SVGFEComponentTransferElement","SVGFECompositeElement","SVGFEConvolveMatrixElement","SVGFEDiffuseLightingElement","SVGFEDisplacementMapElement","SVGFEDistantLightElement","SVGFEDropShadowElement","SVGFEFloodElement","SVGFEFuncAElement","SVGFEFuncBElement","SVGFEFuncGElement","SVGFEFuncRElement","SVGFEGaussianBlurElement","SVGFEImageElement","SVGFEMergeElement","SVGFEMergeNodeElement","SVGFEMorphologyElement","SVGFEOffsetElement","SVGFEPointLightElement","SVGFESpecularLightingElement","SVGFESpotLightElement","SVGFETileElement","SVGFETurbulenceElement","SVGFilterElement","SVGFilterPrimitiveStandardAttributes","SVGFitToViewBox","SVGForeignObjectElement","SVGGElement","SVGGeometryElement","SVGGradientElement","SVGGraphicsElement","SVGImageElement","SVGLength","SVGLengthList","SVGLineElement","SVGLinearGradientElement","SVGMPathElement","SVGMarkerElement","SVGMaskElement","SVGMatrix","SVGMetadataElement","SVGNumber","SVGNumberList","SVGPathElement","SVGPatternElement","SVGPoint","SVGPointList","SVGPolygonElement","SVGPolylineElement","SVGPreserveAspectRatio","SVGRadialGradientElement","SVGRect","SVGRectElement","SVGSVGElement","SVGSVGElementEventMap","SVGScriptElement","SVGSetElement","SVGStopElement","SVGStringList","SVGStyleElement","SVGSwitchElement","SVGSymbolElement","SVGTSpanElement","SVGTests","SVGTextContentElement","SVGTextElement","SVGTextPathElement","SVGTextPositioningElement","SVGTitleElement","SVGTransform","SVGTransformList","SVGURIReference","SVGUnitTypes","SVGUseElement","SVGViewElement","Sanitizer","SanitizerAttribute","SanitizerAttributeNamespace","SanitizerConfig","SanitizerElement","SanitizerElementNamespace","SanitizerElementNamespaceWithAttributes","SanitizerElementWithAttributes","SanitizerPresets","Scheduler","SchedulerPostTaskCallback","SchedulerPostTaskOptions","Screen","ScreenOrientation","ScreenOrientationEventMap","ScriptProcessorNode","ScriptProcessorNodeEventMap","ScrollAxis","ScrollBehavior","ScrollIntoViewOptions","ScrollLogicalPosition","ScrollOptions","ScrollRestoration","ScrollSetting","ScrollTimeline","ScrollTimelineOptions","ScrollToOptions","SecurityPolicyViolationEvent","SecurityPolicyViolationEventDisposition","SecurityPolicyViolationEventInit","SegmentData","SegmentIterator","Segmenter","SegmenterOptions","Segments","Selection","SelectionDirection","SelectionMode","Server","ServerWebSocket","ServiceWorker","ServiceWorkerContainer","ServiceWorkerContainerEventMap","ServiceWorkerEventMap","ServiceWorkerGlobalScope","ServiceWorkerGlobalScopeEventMap","ServiceWorkerRegistration","ServiceWorkerRegistrationEventMap","ServiceWorkerState","ServiceWorkerUpdateViaCache","Set","SetConstructor","SetIterator","ShadowRoot","ShadowRootEventMap","ShadowRootInit","ShadowRootMode","ShareData","SharedArrayBuffer","SharedArrayBufferConstructor","SharedWorker","SharedWorkerGlobalScope","SharedWorkerGlobalScopeEventMap","ShellPromise","ShowPopoverOptions","SlotAssignmentMode","Slottable","Socket","SocketHandler","SourceBuffer","SourceBufferEventMap","SourceBufferList","SourceBufferListEventMap","SpeechRecognitionAlternative","SpeechRecognitionErrorCode","SpeechRecognitionErrorEvent","SpeechRecognitionErrorEventInit","SpeechRecognitionEvent","SpeechRecognitionEventInit","SpeechRecognitionResult","SpeechRecognitionResultList","SpeechSynthesis","SpeechSynthesisErrorCode","SpeechSynthesisErrorEvent","SpeechSynthesisErrorEventInit","SpeechSynthesisEvent","SpeechSynthesisEventInit","SpeechSynthesisEventMap","SpeechSynthesisUtterance","SpeechSynthesisUtteranceEventMap","SpeechSynthesisVoice","StartViewTransitionOptions","StaticRange","StaticRangeInit","Stats","StereoPannerNode","StereoPannerOptions","Storage","StorageEstimate","StorageEvent","StorageEventInit","StorageManager","StreamPipeOptions","String","StringConstructor","StringIterator","StringNumericLiteral","StructuredSerializeOptions","StylePropertyMap","StylePropertyMapReadOnly","StylePropertyMapReadOnlyIterator","StyleSheet","StyleSheetList","SubmitEvent","SubmitEventInit","Subprocess","SubtleCrypto","SuppressedError","SuppressedErrorConstructor","SvcOutputMetadata","Symbol","SymbolConstructor","SyntaxError","SyntaxErrorConstructor","TCPSocket","Table","TableDescriptor","TableKind","Tag","TagType","TaskController","TaskControllerInit","TaskPriority","TaskPriorityChangeEvent","TaskPriorityChangeEventInit","TaskSignal","TaskSignalAnyInit","TaskSignalEventMap","TemplateStringsArray","Temporal","TexImageSource","Text","TextDecodeOptions","TextDecoder","TextDecoderCommon","TextDecoderOptions","TextDecoderStream","TextEncoder","TextEncoderCommon","TextEncoderEncodeIntoResult","TextEncoderStream","TextEvent","TextInfo","TextMetrics","TextStreamBase","TextStreamReader","TextStreamWriter","TextTrack","TextTrackCue","TextTrackCueEventMap","TextTrackCueList","TextTrackEventMap","TextTrackKind","TextTrackList","TextTrackListEventMap","TextTrackMode","ThisParameterType","ThisType","TimeLikeObject","TimeRanges","TimeUnit","TimeZoneLike","TimelineRangeOffset","Timeout","Timer","TimerHandler","ToStringRoundingOptions","ToStringRoundingOptionsWithFractionalSeconds","ToggleEvent","ToggleEventInit","TogglePopoverOptions","Touch","TouchEvent","TouchEventInit","TouchInit","TouchList","TouchType","TrackEvent","TrackEventInit","TransferFunction","Transferable","TransformStream","TransformStreamDefaultController","Transformer","TransformerFlushCallback","TransformerStartCallback","TransformerTransformCallback","TransitionEvent","TransitionEventInit","TransitionOptions","TreeWalker","TypeError","TypeErrorConstructor","TypedArray","TypedPropertyDescriptor","UIEvent","UIEventInit","ULongRange","URIError","URIErrorConstructor","URL","URLPattern","URLPatternComponentResult","URLPatternInit","URLPatternInput","URLPatternOptions","URLPatternResult","URLSearchParams","URLSearchParamsIterator","Uint16Array","Uint16ArrayConstructor","Uint32Array","Uint32ArrayConstructor","Uint32List","Uint8Array","Uint8ArrayConstructor","Uint8ClampedArray","Uint8ClampedArrayConstructor","Uncapitalize","UnderlyingByteSource","UnderlyingDefaultSource","UnderlyingSink","UnderlyingSinkAbortCallback","UnderlyingSinkCloseCallback","UnderlyingSinkStartCallback","UnderlyingSinkWriteCallback","UnderlyingSource","UnderlyingSourceCancelCallback","UnderlyingSourcePullCallback","UnderlyingSourceStartCallback","UnicodeBCP47LocaleIdentifier","UnknownCredentialOptions","Uppercase","UserActivation","UserVerificationRequirement","VBArray","VBArrayConstructor","VTTCue","VTTRegion","ValidityState","ValidityStateFlags","ValueType","ValueTypeMap","VibratePattern","VideoColorPrimaries","VideoColorSpace","VideoColorSpaceInit","VideoConfiguration","VideoDecoder","VideoDecoderConfig","VideoDecoderEventMap","VideoDecoderInit","VideoDecoderSupport","VideoEncoder","VideoEncoderBitrateMode","VideoEncoderConfig","VideoEncoderEncodeOptions","VideoEncoderEncodeOptionsForAvc","VideoEncoderEventMap","VideoEncoderInit","VideoEncoderSupport","VideoFacingModeEnum","VideoFrame","VideoFrameBufferInit","VideoFrameCallbackMetadata","VideoFrameCopyToOptions","VideoFrameInit","VideoFrameOutputCallback","VideoFrameRequestCallback","VideoMatrixCoefficients","VideoPixelFormat","VideoPlaybackQuality","VideoTransferCharacteristics","ViewTimeline","ViewTimelineOptions","ViewTransition","ViewTransitionTypeSet","ViewTransitionUpdateCallback","VisualViewport","VisualViewportEventMap","VoidFunction","WEBGL_color_buffer_float","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_pvrtc","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_multi_draw","WGSLLanguageFeatures","WSH","WScript","WakeLock","WakeLockSentinel","WakeLockSentinelEventMap","WakeLockType","WaveShaperNode","WaveShaperOptions","WeakKey","WeakKeyTypes","WeakMap","WeakMapConstructor","WeakRef","WeakRefConstructor","WeakSet","WeakSetConstructor","WebAssembly","WebAssemblyCompileOptions","WebAssemblyInstantiatedSource","WebCodecsErrorCallback","WebGL2RenderingContext","WebGL2RenderingContextBase","WebGL2RenderingContextOverloads","WebGLActiveInfo","WebGLBuffer","WebGLContextAttributes","WebGLContextEvent","WebGLContextEventInit","WebGLFramebuffer","WebGLPowerPreference","WebGLProgram","WebGLQuery","WebGLRenderbuffer","WebGLRenderingContext","WebGLRenderingContextBase","WebGLRenderingContextOverloads","WebGLSampler","WebGLShader","WebGLShaderPrecisionFormat","WebGLSync","WebGLTexture","WebGLTransformFeedback","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES","WebKitCSSMatrix","WebSocket","WebSocketEventMap","WebSocketHandler","WebTransport","WebTransportBidirectionalStream","WebTransportCloseInfo","WebTransportCongestionControl","WebTransportDatagramDuplexStream","WebTransportError","WebTransportErrorOptions","WebTransportErrorSource","WebTransportHash","WebTransportOptions","WebTransportSendOptions","WebTransportSendStreamOptions","WeekInfo","WheelEvent","WheelEventInit","Window","WindowClient","WindowEventHandlers","WindowEventHandlersEventMap","WindowEventMap","WindowLocalStorage","WindowOrWorkerGlobalScope","WindowPostMessageOptions","WindowProxy","WindowSessionStorage","WithImplicitCoercion","Worker","WorkerEventMap","WorkerGlobalScope","WorkerGlobalScopeEventMap","WorkerLocation","WorkerNavigator","WorkerOptions","WorkerType","Worklet","WorkletOptions","WritableStream","WritableStreamDefaultController","WritableStreamDefaultWriter","WriteCommandType","WriteParams","XMLDocument","XMLHttpRequest","XMLHttpRequestBodyInit","XMLHttpRequestEventMap","XMLHttpRequestEventTarget","XMLHttpRequestEventTargetEventMap","XMLHttpRequestResponseType","XMLHttpRequestUpload","XMLSerializer","XPathEvaluator","XPathEvaluatorBase","XPathExpression","XPathNSResolver","XPathResult","XSLTProcessor","YearMonthLikeObject","ZonedDateTime","ZonedDateTimeConstructor","ZonedDateTimeFromOptions","ZonedDateTimeLike","ZonedDateTimeLikeObject","ZonedDateTimeToStringOptions","global","globalThis","process","structuredClone"])});function mc(e,t={strings:!0}){let r="",n=0;while(n<e.length){let i=e.slice(n,n+2);if(i==="//"){let s=e.indexOf(`
|
|
192
|
+
`,n),a=s===-1?e.length:s;r+=" ".repeat(a-n),n=a;continue}if(i==="/*"){let s=e.indexOf("*/",n+2),a=s===-1?e.length:s+2;for(let c=n;c<a;c++)r+=e[c]===`
|
|
193
|
+
`?`
|
|
194
|
+
`:" ";n=a;continue}let o=e[n];if(t.strings&&(o==='"'||o==="'"||o==="`")){let s=o;r+=" ",n++;while(n<e.length){if(e[n]==="\\"){r+=" ",n+=2;continue}if(e[n]===s){r+=" ",n++;break}r+=e[n]===`
|
|
195
|
+
`?`
|
|
196
|
+
`:" ",n++}continue}r+=o,n++}return r}function Om(e){let t=new Set,r=[/\b(?:export\s+)?(?:declare\s+)?(?:abstract\s+)?(?:type|interface|class|enum|namespace|module)\s+([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?(?:declare\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?declare\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g];for(let n of r)for(let i of e.matchAll(n))t.add(i[1]);return t}function Rm(e){let t=new Set;for(let r of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let n=r[1],i=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(n);if(i)t.add(i[1]);let o=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let a of o.split(",")){let c=a.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let s=/\{([\s\S]*?)\}/.exec(n);if(s)for(let a of s[1].split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let f=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(c);t.add(f?f[1]:c.split(/\s+/)[0])}}for(let r of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(r[1]);return t}function Pm(e){let t=new Set,r=(i)=>{for(let o of i.split(",")){let s=o.trim().split(/\s+|=/)[0]?.trim();if(s&&/^[A-Za-z_$][\w$]*$/.test(s))t.add(s)}},n=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let i of e.matchAll(n))r(i[1]);for(let i of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))r(i[1]);for(let i of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))t.add(i[1]);for(let i of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))t.add(i[1]);return t}function km(e){let t=new Map,r=(i)=>{let o=1;for(let s=0;s<i&&s<e.length;s++)if(e.charCodeAt(s)===10)o++;return o},n=(i,o,s)=>{for(let a of i.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=a[1];if(t.has(c))continue;let f=i.slice(a.index+c.length);if(/^\s*\??:/.test(f))continue;t.set(c,{line:r(o),context:s.trim().slice(0,120)})}};for(let i of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))n(i[1],i.index+i[0].indexOf("="),i[0]);for(let i of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/:\s*([^;,){}\n=]+)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/<([^<>()]*)>/g))n(i[1],i.index,i[0]);return t}function pc(e){let t=mc(e),r=mc(e,{strings:!1}),n=new Set([...Om(t),...Rm(r),...Pm(t),...hc,...Tm]),i=[];for(let[o,s]of km(t)){if(n.has(o))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${o}\\b`).test(t))continue;i.push({name:o,line:s.line,context:s.context})}return i.sort((o,s)=>o.line-s.line||o.name.localeCompare(s.name))}var Tm;var gc=he(()=>{dc();Tm=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function Nt(e,t){let r=1,n=1;for(let i=0;i<t;i++)if(e.charCodeAt(i)===10)r++,n=1;else n++;return{line:r,column:n}}function Cc(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},o=0,s=0,a=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),h=e.charCodeAt(f+1);if(a!==-1){if(u===42&&h===47)r.push({start:a,end:f+2}),a=-1,f++;continue}if(o){if(u===92)f++;else if(u===o)r.push({start:s,end:f+1}),o=0;continue}if(u===47&&h===42){a=f,f++;continue}if(u===47&&h===47){let y=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:y,end:f});continue}if(u===39||u===34||u===96){o=u,s=f;continue}let l=e[f];if(l==="("||l==="["||l==="{")n.push({char:l,offset:f});else if(i[l]){let y=n.pop();if(!y||y.char!==i[l])t.push({...Nt(e,f),message:`Unexpected closing delimiter ${l}`,code:"DTSX1004"})}}if(o)t.push({...Nt(e,s),message:"Unterminated string literal",code:"DTSX1002"});if(a!==-1)t.push({...Nt(e,a),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...Nt(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 h of e.matchAll(f)){if(r.some((l)=>h.index>=l.start&&h.index<l.end))continue;t.push({...Nt(e,h.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((h)=>f.index>=h.start&&f.index<h.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...Nt(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...Dm(e,r)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function Dm(e,t){let r=[],n=(i)=>t.some((o)=>i>=o.start&&i<o.end);for(let i of e.matchAll(/\b(import|export)\s+(?:type\s+)?\{/g)){let o=i.index;if(n(o))continue;let s=o+i[0].length-1,a=-1;for(let u=s+1;u<e.length;u++){if(n(u))continue;let h=e[u];if(h==="{"){a=-2;break}if(h==="}"){a=u;break}}if(a<0)continue;let c=e.slice(s+1,a);if(!c.trim())continue;let f=s+1;for(let u of c.split(",")){let h=u.trim();if(h){let l=f+u.indexOf(h);if(h.includes(";"))r.push({...Nt(e,l),message:`Unexpected ';' in ${i[1]} clause \u2014 specifiers are separated by ','`,code:"DTSX1006"});else if(!Mm.test(h))r.push({...Nt(e,l),message:`Invalid ${i[1]} specifier '${h}'`,code:"DTSX1006"})}f+=u.length+1}}return r}var yc,Mm;var wc=he(()=>{yc=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,Mm=new RegExp(`^(?:type\\s+)?${yc}(?:\\s+as\\s+${yc})?$`,"u")});import{join as J0,resolve as Im}from"path";import Fm from"process";function Vo(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function qi(e,t,r="lf"){let n=t.replace(/\r\n/g,`
|
|
197
|
+
`);if(!n.endsWith(`
|
|
198
|
+
`))n+=`
|
|
199
|
+
`;if(r==="crlf")n=n.replace(/\n/g,`\r
|
|
200
|
+
`);await ds(e,n)}async function vc(e){try{let t=e?.cwd||Fm.cwd();return(await Cr(Im(t,e?.tsconfigPath||"tsconfig.json"),{allowCircular:!0}))?.isolatedDeclarations??!1}catch{return!1}}function bc(e,t){let r={isValid:!0,errors:[]};for(let n of Cc(e))r.errors.push({line:n.line,column:n.column,message:n.message,code:n.code});for(let n of pc(e))r.errors.push({line:n.line,column:1,message:`'${n.name}' is used but never declared or imported here, so it resolves to an error type for anything consuming this file. It is most likely an ambient global in the source project \u2014 import it explicitly. Referenced by: ${n.context}`,code:"dangling-type-reference"});return r.isValid=r.errors.length===0,r}function Ec(e,t,r){if(e===t)return"";let n=e.split(`
|
|
201
|
+
`),i=t.split(`
|
|
202
|
+
`),o=new Map,s=new Map;for(let u=0;u<n.length;u++)o.set(n[u],(o.get(n[u])??0)+1);for(let u=0;u<i.length;u++)s.set(i[u],(s.get(i[u])??0)+1);let a=[],c=[];for(let[u,h]of o){let l=h-(s.get(u)??0);for(let y=0;y<l;y++)a.push(u)}for(let[u,h]of s){let l=h-(o.get(u)??0);for(let y=0;y<l;y++)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(`
|
|
203
|
+
`)}function Sc(e,t,r,n){let i=e.split(`
|
|
204
|
+
`),o=[];function s(h){let l="",y=h<0?-h<<1|1:h<<1;do{let C=y&31;if(y>>>=5,y>0)C|=32;l+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[C]}while(y>0);return l}let a=0,c=0,f=0,u=n.split(`
|
|
205
|
+
`).length;for(let h=0;h<i.length;h++){if(i[h].trim()===""){o.push("");continue}a=0;let l=Math.min(h,u-1),y=[],C=0-a,S=0,x=l-c,v=0-f;y.push(s(C)+s(S)+s(x)+s(v)),a=0,c=l,f=0,o.push(y.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[n],mappings:o.join(";")}}function $c(e,t){return`${e}
|
|
206
|
+
${Vo()}${t}
|
|
207
|
+
`}var Ac=he(()=>{Ur();pn();gc();wc()});function Bm(e){let t=[],r=0;for(let n=0;n<=e.length;n++)if(n===e.length||e[n]===`
|
|
208
|
+
`){let i=r,o=n;while(i<o&&(e[i]===" "||e[i]==="\t"||e[i]==="\r"))i++;while(o>i&&(e[o-1]===" "||e[o-1]==="\t"||e[o-1]==="\r"))o--;let s=e.slice(i,o);if(r=n+1,s.startsWith("///")){if(s.indexOf("<")===-1)continue;if(Nm.test(s)||Lm.test(s)||Wm.test(s))t.push(s)}else if(s===""||s.startsWith("//"))continue;else break}return t}function Gm(e){if(e.includes(`
|
|
166
209
|
`))return`/**
|
|
167
210
|
* ${e}
|
|
168
211
|
*/
|
|
169
212
|
`;return`/** ${e} */
|
|
170
|
-
`}function
|
|
213
|
+
`}function jm(e){let t=e.indexOf("{");if(t===-1)return-1;let r=e.indexOf("<");if(r===-1||r>t)return t;let n=0,i=!1,o="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";if(!i&&(a==='"'||a==="'"||a==="`"))i=!0,o=a;else if(i&&a===o&&c!=="\\")i=!1;if(!i){if(a==="<")n++;else if(a===">")n--;else if(a==="{"&&n===0)return s}}return-1}function _m(e,t=!0){return xt(e.leadingComments,t)+e.text}function xc(e,t=!0){let r=xt(e.leadingComments,t);if(e.typeAnnotation&&!e.value)return r+e.text;let n="";if(e.isExported)n+="export ";n+="declare ";let i=e.modifiers?.[0]||"const";n+=`${i} `,n+=e.name;let{typeAnnotation:o,value:s}=e,a=!o&&s?Vi(s):null;if(a)o=a;else if(!o&&s&&s.trim().endsWith("as const"))o=Ie(s,!0);else if(!o&&s&&i==="const"){let f=s.trim(),u=f.startsWith("{")||f.startsWith("[");if(u)Fo();o=Ie(s,!u)}else if(!o&&s)o=Ie(s,i==="const");if(!o)o="unknown";let c="";if(t&&s&&!e.typeAnnotation&&!s.trim().endsWith("as const")){let f=s.trim();if(i!=="const"){if((o==="string"||o==="number"||o==="boolean")&&f.length>0)c=`@defaultValue ${f}`}else if(f.startsWith("{")||f.startsWith("[")){let u=No();if(u)if(u.includes(`
|
|
171
214
|
`))c=`@defaultValue
|
|
172
215
|
* \`\`\`ts
|
|
173
216
|
${u.split(`
|
|
174
217
|
`).map((h)=>` * ${h}`).join(`
|
|
175
218
|
`)}
|
|
176
|
-
* \`\`\``;else c=`@defaultValue \`${u}\``}}else if(t&&
|
|
219
|
+
* \`\`\``;else c=`@defaultValue \`${u}\``}}else if(t&&s&&e.typeAnnotation&&Vl(e.typeAnnotation)){Fo();let f=s.trim(),u=f.endsWith("as const")?f.slice(0,-8).trim():f;Ie(u,!1);let h=No();if(h)if(h.includes(`
|
|
177
220
|
`))c=`@defaultValue
|
|
178
221
|
* \`\`\`ts
|
|
179
222
|
${h.split(`
|
|
180
223
|
`).map((l)=>` * ${l}`).join(`
|
|
181
224
|
`)}
|
|
182
|
-
* \`\`\``;else c=`@defaultValue \`${h}\``}if(c=
|
|
225
|
+
* \`\`\``;else c=`@defaultValue \`${h}\``}if(c=Do(c),n+=`: ${o};`,c&&r&&r.includes("@defaultValue"))c="";if(c&&r){let f=r.trimEnd(),u=f.lastIndexOf("*/");if(u!==-1){let h=f.slice(0,u).trimEnd();if(h.startsWith("/** ")&&!h.includes(`
|
|
183
226
|
`))h=`/**
|
|
184
227
|
* ${h.slice(4)}`;return`${h}
|
|
185
228
|
* ${c}
|
|
@@ -188,70 +231,27 @@ ${h.split(`
|
|
|
188
231
|
* ${f.replace(/^\/\/\s*/,"")}
|
|
189
232
|
* ${c}
|
|
190
233
|
*/
|
|
191
|
-
${n}`}if(c)return`${
|
|
192
|
-
`;i+=H
|
|
193
|
-
`);if(
|
|
234
|
+
${n}`}if(c)return`${Gm(c)}${n}`;return r+n}function Vm(e,t=!0){let r=xt(e.leadingComments,t),n=e.text;if(n.startsWith("export declare interface")||n.startsWith("declare interface"))return r+n;let i="";if(e.isExported)i+="export ";if(i+="declare interface ",i+=e.name,e.generics)i+=e.generics;if(e.extends)i+=` extends ${e.extends}`;let o=jm(e.text);if(o!==-1)i+=` ${e.text.slice(o)}`;else i+=" {}";return r+i}function Um(e,t=!0){let r=xt(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return r+e.text;let n="";if(e.isExported)n+="export ";if(!e.isExported&&!e.text.includes(" from "))n+="declare ";let i=e.text.indexOf("type ");if(i!==-1){let s=e.text.slice(i),a=s.length;while(a>0&&(s.charCodeAt(a-1)===59||s.charCodeAt(a-1)===32||s.charCodeAt(a-1)===10||s.charCodeAt(a-1)===13))a--;if(a<s.length)s=s.slice(0,a);n+=s}else{if(n+=`type ${e.name}`,e.generics)n+=e.generics;n+=" = any"}let o=n.trimEnd();if(!o.endsWith(";")&&!o.endsWith("}"))n+=";";return r+n}function Km(e,t=!0){return xt(e.leadingComments,t)+e.text}function Hm(e,t=!0){let r=xt(e.leadingComments,t),n="";if(e.isExported)n+="export ";if(n+="declare ",e.modifiers?.includes("const"))n+="const ";n+="enum ",n+=e.name;let i=e.text.indexOf("{");if(i!==-1)n+=` ${e.text.slice(i)}`;else n+=" {}";return r+n}function zm(e,t=!0){let r=xt(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 o="declare module ";o+=e.name;let s=e.text.indexOf("{");if(s!==-1)o+=` ${e.text.slice(s)}`;else o+=" {}";return r+o}let n="";if(e.isExported)n+="export ";if(!e.modifiers?.includes("declare"))n+="declare ";n+="namespace ",n+=e.name;let i=e.text.indexOf("{");if(i!==-1)n+=` ${e.text.slice(i)}`;else n+=" {}";return r+n}function Jm(e){let t=jt.get(e);if(t)return jt.delete(e),jt.set(e,t),t;return null}function Tc(e,t){if(jt.set(e,t),jt.size>200){let r=0;for(let n of jt.keys()){if(r++>=20)break;jt.delete(n)}}}function qm(e){let t=e.indexOf(" from ");if(t===-1)return null;let r=e.slice(t+6).trim(),n=r[0];if(n!=='"'&&n!=="'")return null;let i=r.indexOf(n,1);if(i===-1)return null;let o=r.slice(1,i),s=e.slice(0,t).trim(),a=s.startsWith("import type ");if(s.startsWith("import "))s=s.slice(7).trim();if(s.startsWith("type "))s=s.slice(5).trim();let c=null,f=[],u=!1,h=s.indexOf("{"),l=s.lastIndexOf("}");if(h!==-1&&l!==-1){let y=s.slice(0,h).trim();if(y.endsWith(","))c=y.slice(0,-1).trim()||null;let C=s.slice(h+1,l),S=0;for(let x=0;x<=C.length;x++)if(x===C.length||C.charCodeAt(x)===44){let v=S,G=x;while(v<G&&(C.charCodeAt(v)===32||C.charCodeAt(v)===9||C.charCodeAt(v)===10))v++;while(G>v&&(C.charCodeAt(G-1)===32||C.charCodeAt(G-1)===9||C.charCodeAt(G-1)===10))G--;if(v<G)f.push(C.slice(v,G));S=x+1}}else{let y=s.trim();if(y.startsWith("* as "))c=y.slice(5).trim()||null,u=!0;else c=y||null}return{defaultName:c,namedItems:f,source:o,isTypeOnly:a,isNamespace:u}}function Ym(e){let t=Jm(e);if(t)return t;let r=[],n=e.indexOf(" from ");if(n===-1)return Tc(e,r),r;let i=e.slice(0,n).trim();if(i.startsWith("import "))i=i.slice(7).trim();if(i.startsWith("type "))i=i.slice(5).trim();let o=i.indexOf("{"),s=i.lastIndexOf("}");if(o!==-1&&s!==-1){let a=i.slice(0,o).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=i.slice(o+1,s).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 h=u.indexOf(" as ");if(h!==-1)u=u.slice(h+4).trim();if(u)r.push(u)}}else{let a=i.trim();if(a.startsWith("* as ")){let c=a.slice(5).trim();if(c)r.push(c)}else if(a)r.push(a)}return Tc(e,r),r}function Oc(e,t){throw Error(t||`Unexpected value: ${e}`)}function Zm(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function Xm(e){let t=new Set,r=0,n=e.length;while(r<n){let i=e.charCodeAt(r);if(i>=65&&i<=90||i>=97&&i<=122||i===95||i===36||i>127){let o=r;r++;while(r<n&&Zm(e.charCodeAt(r)))r++;t.add(e.substring(o,r))}else r++}return t}function Mc(e,t,r=!0,n=["bun"]){let i="",o=t.sourceCode;if(o){let k=0;while(k<o.length&&(o.charCodeAt(k)===32||o.charCodeAt(k)===9||o.charCodeAt(k)===10||o.charCodeAt(k)===13))k++;if(k<o.length-2&&o.charCodeAt(k)===47&&o.charCodeAt(k+1)===47&&o.charCodeAt(k+2)===47){let U=Bm(o);if(U.length>0)for(let H=0;H<U.length;H++){if(i)i+=`
|
|
235
|
+
`;i+=U[H]}}}let s=[],a=[],c=[],f=[],u=[],h=[],l=[],y=[],C=[];for(let k of e){let U=k.kind;switch(U){case"import":s.push(k);break;case"function":a.push(k);break;case"variable":c.push(k);break;case"interface":f.push(k);break;case"type":u.push(k);break;case"class":h.push(k);break;case"enum":l.push(k);break;case"module":y.push(k);break;case"export":C.push(k);break;case"namespace":y.push(k);break;case"unknown":break;default:Oc(U,`Unhandled declaration kind: ${U}`)}}let S=new Set,x=[],v=[],G=[],L=new Set;for(let k of C){let U=xt(k.leadingComments,r);if(k.text.startsWith("export default")){let H=k.text.endsWith(";")?k.text:`${k.text};`;G.push(U+H)}else{let H=k.text.trim();if(!H.endsWith(";"))H+=";";let O=H.match(Qm);if(O){let pe=O[1],Oe=0;for(let ie=0;ie<=pe.length;ie++)if(ie===pe.length||pe.charCodeAt(ie)===44){let ne=Oe,ue=ie;while(ne<ue&&pe.charCodeAt(ne)<=32)ne++;while(ue>ne&&pe.charCodeAt(ue-1)<=32)ue--;if(ne<ue)S.add(pe.slice(ne,ue));Oe=ie+1}}let z=U+H;if(!L.has(z))if(L.add(z),z.includes("export type"))x.push(z);else v.push(z)}}let P=new Map;if(s.length>0)for(let k of s){let U=Ym(k.text);for(let H of U)P.set(H,k)}let F=[];if(s.length>0){let k=new Set,U=[];for(let z of a)U.push(z.text);for(let z of c)if(U.push(z.text),z.typeAnnotation)U.push(z.typeAnnotation);else if(z.isExported&&z.value)U.push(xc(z,!1));for(let z of f)U.push(z.text);for(let z of u)U.push(z.text);for(let z of h)U.push(z.text);for(let z of l)U.push(z.text);for(let z of y)U.push(z.text);for(let z of C)U.push(z.text);let H=U.join(`
|
|
236
|
+
`);if(H&&P.size>0){let z=Xm(H);for(let pe of P.keys())if(z.has(pe))k.add(pe)}for(let z of S)if(P.has(z))k.add(z);for(let z of s){if(z.isSideEffect){let Z=z.text.trim(),te=Z.endsWith(";")?Z:`${Z};`;F.push(te);continue}let pe=qm(z.text);if(!pe)continue;let{defaultName:Oe,namedItems:ie,source:ne,isTypeOnly:ue,isNamespace:se}=pe,W=Oe?k.has(Oe):!1,K="",q=0;for(let Z=0;Z<ie.length;Z++){let te=ie[Z],X=te.charCodeAt(0)===116&&te.startsWith("type ")?te.slice(5).trim():te.trim(),oe=X.indexOf(" as ");if(oe!==-1)X=X.slice(oe+4).trim();if(k.has(X)){if(q>0)K+=", ";K+=te,q++}}if(W||q>0){let Z=ue?"import type ":"import ";if(W&&Oe)if(se)Z+=`* as ${Oe}`;else Z+=q>0?`${Oe}, { ${K} }`:Oe;else if(q>0)Z+=`{ ${K} }`;Z+=` from '${ne}';`,F.push(Z)}}let O=n.length;if(F.length>1){if(Rc!==n)Rc=n,Pc=n.map((ie)=>`from '${ie}`),kc=n.map((ie)=>`from "${ie}`);let z=Pc,pe=kc,Oe=new Map;for(let ie of F){let ne=O;for(let ue=0;ue<n.length;ue++)if(ie.includes(z[ue])||ie.includes(pe[ue])){ne=ue;break}Oe.set(ie,ne)}F.sort((ie,ne)=>{let ue=Oe.get(ie),se=Oe.get(ne);return ue!==se?ue-se:ie.localeCompare(ne)})}}for(let k=0;k<F.length;k++){if(i)i+=`
|
|
194
237
|
`;i+=F[k]}for(let k=0;k<x.length;k++){if(i)i+=`
|
|
195
|
-
`;i+=x[k]}let I=[a,c,f,u,h,l,y];for(let k=0;k<I.length;k++){let
|
|
196
|
-
`;i+=
|
|
197
|
-
`;i+=v[k]}for(let k=0;k<
|
|
198
|
-
`;i+=
|
|
199
|
-
|
|
200
|
-
`)
|
|
201
|
-
|
|
202
|
-
`);
|
|
203
|
-
`)}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
`)
|
|
210
|
-
`).map((
|
|
211
|
-
`)
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
${d.
|
|
215
|
-
`)}
|
|
216
|
-
}`}function ro(d){return Ct(d)||d===Se||d===Rs||d===le||d===fe}function sn(){if(l>=a)return"";let d=i.charCodeAt(l);if(d===Se){let m=l;return X(Se,ke),i.slice(m,l)}if(d===Rs)return l++,`#${j()}`;if(d===le||d===fe){let m=l;return W(d),i.slice(m,l)}return j()}function on(d){let m=l;l+=d.length,v();let p=l<a?i.charCodeAt(l):0;return l=m,p}function io(){let d=0;while(l<a){if(I())continue;let m=i.charCodeAt(l);if(m===Y||m===ae)d++;else if(m===Q||m===Ee){if(d===0)return;d--}else if(m===re&&d===0){l++;return}if(d===0&&L())return;l++}}function no(d,m,p,g,w,b){so(d,m,p,g,!1,!1,w,b)}function so(d,m,p,g,w,b,T,R){if(v(),l>=a)return;let E=i.charCodeAt(l),A=!1;if(E===Ui)A=!0,l++,v();if(l<a&&i.charCodeAt(l)===33)l++,v();let M=l<a?i.charCodeAt(l):0;if(M===ae||M===we){let U=M===we?mt():"";v();let G=Ot();v();let N=mr(),D=N.length>0;if(!N)if(T&&w)N="AsyncGenerator<unknown, void, unknown>";else if(w)N="Generator<unknown, void, unknown>";else if(T)N="Promise<void>";else N="void";if(v(),l<a&&i.charCodeAt(l)===Y){let Je=l+1;if(X(Y,Q),!D&&!w)N=hr(i.slice(Je,l-1),T,G)}else if(l<a&&i.charCodeAt(l)===re)l++;let _=Vt(G),V=A?"?":"";R.push(`${m}${d}${V}${U}${_}: ${N};`)}else if(M===ft||M===ve||M===re||M===Q||M===$e||M===xe){let U="";if(M===ft){l++,v();let D=l,_=0;while(l<a){if(I())continue;let V=i.charCodeAt(l);if(V===ae||V===Y||V===Se||V===we)_++;else if(V===Ee||V===Q||V===ke||V===pe&&!se()){if(_===0)break;_--}else if(_===0&&(V===re||V===pt))break;else if(_===0&&V===ve&&!Be())break;if(_===0&&L())break;l++}U=C(D,l)}let G="";if(l<a&&i.charCodeAt(l)===ve)if(o&&U){l++;let D=0;while(l<a){if(I())continue;let _=i.charCodeAt(l);if(_===ae||_===Y||_===Se)D++;else if(_===Ee||_===Q||_===ke){if(D===0&&_===Q)break;D--}else if(D===0&&_===re)break;if(D===0&&L())break;l++}}else{l++,v();let D=l,_=0;while(l<a){if(I())continue;let V=i.charCodeAt(l);if(V===ae||V===Y||V===Se)_++;else if(V===Ee||V===Q||V===ke){if(_===0&&V===Q)break;_--}else if(_===0&&V===re)break;if(_===0&&L())break;l++}G=C(D,l)}if(l<a&&i.charCodeAt(l)===re)l++;if(!U)if(G){let D=Br(G);if(D)U=D;else U=G.endsWith("as const")||p&&g?en(G):Qi(G)}else U="unknown";let N=A?"?":"";R.push(`${m}${d}${N}: ${U};`)}else io()}function nf(d){let m=0;for(let p=0;p<d.length;p++){let g=d.charCodeAt(p);if(g===ae||g===Y||g===Se||g===we)m++;else if(g===Ee||g===Q||g===ke||g===pe&&d.charCodeAt(p-1)!==ve)m--;else if(g===ve&&m===0&&d.charCodeAt(p+1)!==pe&&d.charCodeAt(p+1)!==ve)return!0}return!1}function sf(d,m){let p=d.slice(1,-1).trim();if(!p)return;let g=[],w=0,b=0,T=!1,R=0;for(let E=0;E<=p.length;E++){if(E===p.length){g.push(Gr(p.slice(w).trim()));break}let A=p.charCodeAt(E);if(T){if(A===nt){E++;continue}if(A===R)T=!1;continue}if(A===ee&&E+1<p.length){let M=p.charCodeAt(E+1);if(M===Ae){E+=2;while(E+1<p.length&&!(p.charCodeAt(E)===Ae&&p.charCodeAt(E+1)===ee))E++;E++;continue}if(M===ee){while(E<p.length&&p.charCodeAt(E)!==10)E++;continue}}if(A===le||A===fe||A===Fe){T=!0,R=A;continue}if(A===ae||A===Y||A===Se||A===we)b++;else if(A===Ee||A===Q||A===ke||A===pe&&!(E>0&&p.charCodeAt(E-1)===ve))b--;else if(A===pt&&b===0)g.push(Gr(p.slice(w,E).trim())),w=E+1}for(let E of g){let A=E.startsWith("public ")||E.startsWith("public\t"),M=E.startsWith("protected ")||E.startsWith("protected\t"),U=E.startsWith("private ")||E.startsWith("private\t"),G=E.includes("readonly ");if(!A&&!M&&!U&&!G)continue;if(U)continue;let N=E,D=[];if(A){let qe=6;while(qe<N.length&&Ue(N.charCodeAt(qe)))qe++;N=N.slice(qe),D.push("public")}if(M){let qe=9;while(qe<N.length&&Ue(N.charCodeAt(qe)))qe++;N=N.slice(qe),D.push("protected")}if(G){let qe=N.indexOf("readonly ");if(qe!==-1){let jt=qe+8;while(jt<N.length&&Ue(N.charCodeAt(jt)))jt++;N=N.slice(0,qe)+N.slice(jt)}D.push("readonly")}let _=D.length>0?`${D.join(" ")} `:"",V=Qs(N),Je=N.search(/[?:=]/);if(Je!==-1&&N.charCodeAt(Je)!==63&&nf(N))V=V.replace(/^([\w$]+)\?:/,"$1:");m.push(` ${_}${V};`)}}function an(d=" "){if(l>=a||i.charCodeAt(l)!==Y)return"{}";l++;let m=[];while(l<a){if(v(),l>=a)break;if(i.charCodeAt(l)===Q){l++;break}if(i.charCodeAt(l)===re){l++;continue}let p=!1;if(O("export"))p=!0,l+=6,v();if(O("declare"))l+=7,v();let g=p?"export ":"";if(O("function")||O("async")&&of("async","function")){let w=!1;if(O("async"))w=!0,l+=5,v();if(l+=8,v(),l<a&&i.charCodeAt(l)===Ae)l++,v();let b=j();v();let T=mt();v();let R=Ot();v();let E=mr();if(!E)E=w?"Promise<void>":"void";if(v(),l<a&&i.charCodeAt(l)===Y)X(Y,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let A=Vt(R);m.push(`${d}${g}function ${b}${T}${A}: ${E};`)}else if(O("const")||O("let")||O("var")){let w=O("const")?"const":O("let")?"let":"var";l+=w.length,v();let b=j();if(!b){Re(!0);continue}v();let T="";if(l<a&&i.charCodeAt(l)===ft){l++,v();let E=l,A=0;while(l<a){if(I())continue;let M=i.charCodeAt(l);if(M===ae||M===Y||M===Se||M===we)A++;else if(M===Q&&A===0)break;else if(M===Ee||M===Q||M===ke||M===pe&&!se())A--;else if(A===0&&(M===re||M===pt))break;else if(A===0&&M===ve&&!Be())break;if(A===0&&ie())break;l++}T=C(E,l)}let R="";if(l<a&&i.charCodeAt(l)===ve){l++,v();let E=l,A=0;while(l<a){if(I())continue;let M=i.charCodeAt(l);if(M===ae||M===Y||M===Se||M===we)A++;else if(M===Q&&A===0)break;else if(M===Ee||M===Q||M===ke||M===pe&&!se())A--;else if(A===0&&(M===re||M===pt))break;if(A===0&&ie())break;l++}R=C(E,l)}if(l<a&&i.charCodeAt(l)===re)l++;if(!T&&R){let E=Br(R);if(E)T=E;else if(w==="const")T=en(R);else T=Qi(R)}if(!T)T="unknown";m.push(`${d}${g}${w} ${b}: ${T};`)}else if(O("interface")){l+=9,v();let w=j();v();let b=mt();v();let T="";if(O("extends")){l+=7,v();let E=l,A=0;while(l<a){if(I())continue;let M=i.charCodeAt(l);if(M===we)A++;else if(M===pe&&!se())A--;else if(M===Y&&A===0)break;l++}T=C(E,l)}let R=Xs(Xi());m.push(`${d}${g}interface ${w}${b}${T?` extends ${T}`:""} ${R}`)}else if(O("type")){l+=4,v();let w=j();v();let b=mt();if(v(),l<a&&i.charCodeAt(l)===ve){l++,v();let T=l,R=0;while(l<a){if(I())continue;let A=i.charCodeAt(l);if(A===ae||A===Y||A===Se||A===we)R++;else if(A===Q&&R===0)break;else if(A===Ee||A===Q||A===ke||A===pe&&!se())R--;else if(R===0&&A===re)break;if(R===0&&ie())break;l++}let E=C(T,l);if(l<a&&i.charCodeAt(l)===re)l++;m.push(`${d}${g}type ${w}${b} = ${E}`)}}else if(O("class")){l+=5,v();let w=j();v();let b=mt();v();let T=l,R=0;while(l<a){if(I())continue;let U=i.charCodeAt(l);if(U===we)R++;else if(U===pe&&!se())R--;else if(U===Y&&R===0)break;l++}let E=C(T,l),A=E?` ${E}`:"",M=nn();m.push(`${d}${g}class ${w}${b}${A} ${M}`)}else if(O("enum")){l+=4,v();let w=j();v();let b=Xi();m.push(`${d}${g}enum ${w} ${b}`)}else if(O("namespace")||O("module")){let w=O("namespace")?"namespace":"module";l+=w.length,v();let b=j();v();let T=an(d);m.push(`${d}${g}${w} ${b} ${T}`)}else if(O("abstract"))if(l+=8,v(),O("class")){l+=5,v();let w=j();v();let b=mt();v();let T=l,R=0;while(l<a){if(I())continue;let U=i.charCodeAt(l);if(U===we)R++;else if(U===pe&&!se())R--;else if(U===Y&&R===0)break;l++}let E=C(T,l),A=E?` ${E}`:"",M=nn();m.push(`${d}${g}abstract class ${w}${b}${A} ${M}`)}else Re(!0);else if(p&&O("default")){l+=7,v();let w=l;Re(!0);let b=C(w,l);if(b.charCodeAt(b.length-1)===re)b=b.slice(0,-1);if(b)m.push(`${d}export default ${b};`)}else if(!p&&(i.charCodeAt(l)===le||i.charCodeAt(l)===fe||i.charCodeAt(l)===Fe))Re(!0);else Re(!0)}if(m.length===0)return"{}";return`{
|
|
217
|
-
${m.join(`
|
|
218
|
-
`)}
|
|
219
|
-
}`}function of(d,m){let p=l+d.length;while(p<a&&Ue(i.charCodeAt(p)))p++;for(let g=0;g<m.length;g++)if(p+g>=a||i.charCodeAt(p+g)!==m.charCodeAt(g))return!1;return p+m.length>=a||!Ke(i.charCodeAt(p+m.length))}function Kt(d,m,p){l+=p.length,v();let g="",w=i.charCodeAt(l);if(w===le||w===fe){let A=l;W(w),g=i.slice(A,l)}else{g=j();while(l<a&&i.charCodeAt(l)===gt)l++,g+=`.${j()}`}v();let b=l<a&&i.charCodeAt(l)===Y?an():"{}",T=`${m?"export ":""}declare ${p} ${g} ${b}`,R=tt(d),E=g.startsWith("'")||g.startsWith('"');return{kind:"module",name:g,text:T,isExported:m,source:E?g.slice(1,-1):void 0,leadingComments:R,start:d,end:l}}function oo(d,m){Re();let p=C(m,l);if(p.charCodeAt(p.length-1)===re)p=p.slice(0,-1).trimEnd();if(!p)return;let g=Ct(p.charCodeAt(0));for(let A=1;g&&A<p.length;A++)g=Ke(p.charCodeAt(A));let w=tt(d);if(g){c.push({kind:"export",name:"default",text:`export default ${p};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:d,end:l});return}let b="__dtsx_default_export__",T=1;while(i.includes(b))b=`__dtsx_default_export_${T++}__`;let R=Br(p)||Ie(p,!1),E=R==="unknown"&&bp(p)?`typeof ${p}`:R;c.push({kind:"variable",name:b,text:`declare const ${b}: ${E};`,isExported:!1,typeAnnotation:E,modifiers:["const"],start:d,end:l}),c.push({kind:"export",name:"default",text:`export default ${b};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:d,end:l})}while(l<a){if(v(),l>=a)break;let d=l,m=i.charCodeAt(l);if(m===105&&O("import"))c.push(zc(d));else if(m===101&&O("export")){l+=6,v();let p=i.charCodeAt(l);if(p===100&&O("default")){l+=7,v();let g=l,w=i.charCodeAt(l);if(w===102&&O("function")){let b=Rt(d,!0,!1,!0);if(b)c.push(b)}else if(w===97&&O("async")&&on("async")!==re)if(l+=5,v(),O("function")){let b=Rt(d,!0,!0,!0);if(b)c.push(b)}else oo(d,g);else if(w===99&&O("class")){let b=Pt(d,!0,!1,!0);c.push(b)}else if(w===97&&O("abstract")){if(l+=8,v(),O("class")){let b=Pt(d,!0,!0,!0);c.push(b)}}else oo(d,g)}else if(p===116&&O("type")){let g=l;if(l+=4,v(),l<a&&i.charCodeAt(l)===Y){Js();let w=C(d,l),b=tt(d);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Lr(w),leadingComments:b,start:d,end:l})}else if(l<a&&i.charCodeAt(l)===Ae){qs();let w=C(d,l);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Lr(w),start:d,end:l})}else{l=g;let w=rn(d,!0);c.push(w)}}else if(p===105&&O("interface")){let g=tn(d,!0);c.push(g)}else if(p===102&&O("function")){let g=Rt(d,!0,!1,!1);if(g)c.push(g)}else if(p===97&&O("async"))if(l+=5,v(),O("function")){let g=Rt(d,!0,!0,!1);if(g)c.push(g)}else Re();else if(p===99)if(O("class")){let g=Pt(d,!0,!1);c.push(g)}else if(O("const")){let g=l;if(l+=5,v(),O("enum")){l=g+5,v();let w=Ht(d,!0,!0);c.push(w)}else{l=g;let w=Wt(d,"const",!0);for(let b=0;b<w.length;b++)c.push(w[b])}}else Re();else if(p===97&&O("abstract")){if(l+=8,v(),O("class")){let g=Pt(d,!0,!0);c.push(g)}}else if(p===108&&O("let")){let g=Wt(d,"let",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else if(p===118&&O("var")){let g=Wt(d,"var",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else if(p===101&&O("enum")){let g=Ht(d,!0,!1);c.push(g)}else if(p===100&&O("declare"))l+=7,v(),lo(d,!0);else if(p===110&&O("namespace")&&Z(9)){let g=Kt(d,!0,"namespace");c.push(g)}else if(p===109&&O("module")&&Z(6)){let g=Kt(d,!0,"module");c.push(g)}else if(p===Y){Js();let g=C(d,l),w=g.includes("export type"),b=tt(d);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:w,source:Lr(g),leadingComments:b,start:d,end:l})}else if(p===Ae){qs();let g=C(d,l),w=tt(d);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:!1,source:Lr(g),leadingComments:w,start:d,end:l})}else{Re();let g=C(d,l);if(g)c.push({kind:"export",name:"",text:g,isExported:!0,start:d,end:l})}}else if(m===100&&O("declare"))l+=7,v(),lo(d,!1);else if(m===105&&O("interface")){let p=tn(d,!1);f.set(p.name,p)}else if(m===116&&O("type")){let p=rn(d,!1);f.set(p.name,p),c.push(p)}else if(m===102&&O("function")){let p=Rt(d,!1,!1,!1);if(p)y(p);else Re()}else if(m===97)if(O("async")){let p=l;if(l+=5,v(),O("function")){let g=Rt(d,!1,!0,!1);if(g)y(g);else l=p,Re()}else l=p,Re()}else if(O("abstract"))if(l+=8,v(),O("class")){let p=Pt(d,!1,!1);f.set(p.name,p),c.push(p)}else Re();else l++,Re();else if(m===99)if(O("class")){let p=Pt(d,!1,!1);f.set(p.name,p),c.push(p)}else if(O("const")){let p=l;if(l+=5,v(),O("enum")){l=p+5,v();let g=Ht(d,!1,!0);f.set(g.name,g),c.push(g)}else{l=p;let g=Wt(d,"const",!1);for(let w=0;w<g.length;w++)f.set(g[w].name,g[w])}}else l++,Re();else if(m===101&&O("enum")){let p=Ht(d,!1,!1);f.set(p.name,p),c.push(p)}else if(m===108&&O("let")||m===118&&O("var")){let p=O("let")?"let":"var",g=Wt(d,p,!1);for(let w=0;w<g.length;w++)f.set(g[w].name,g[w])}else if(m===109&&O("module")&&Z(6)){let p=Kt(d,!1,"module");c.push(p)}else if(m===110&&O("namespace")&&Z(9)){let p=Kt(d,!1,"namespace");c.push(p)}else{let p=i.charCodeAt(l);if(p===re)l++;else if(p===le||p===fe){if(W(p),l<a&&i.charCodeAt(l)===re)l++}else if(p===Fe){if(P(),l<a&&i.charCodeAt(l)===re)l++}else if(p===$p){if(l++,j(),v(),l<a&&i.charCodeAt(l)===gt)l++,j(),v();if(l<a&&i.charCodeAt(l)===ae)X(ae,Ee)}else l++,Re()}}if(h.size>0){ao(c);for(let d of u.values())ao(d)}if(f.size>0)Sp(c,f,u);return c;function ao(d){let m=new Map;for(let g of d)if(g.kind==="function")m.set(g.name,(m.get(g.name)||0)+1);let p=new Set;for(let[g,w]of m)if(w>1)p.add(g);if(p.size>0){let g=new Set;for(let w of p)for(let b=d.length-1;b>=0;b--)if(d[b].kind==="function"&&d[b].name===w&&h.has(d[b])){g.add(b);break}if(g.size>0){let w=[...g].sort((b,T)=>T-b);for(let b of w)d.splice(b,1)}}}function lo(d,m){if(O("function")){let p=Rt(d,m,!1,!1);if(p)c.push(p)}else if(O("async")){if(l+=5,v(),O("function")){let p=Rt(d,m,!0,!1);if(p)c.push(p)}}else if(O("class")){let p=Pt(d,m,!1);c.push(p)}else if(O("abstract")){if(l+=8,v(),O("class")){let p=Pt(d,m,!0);c.push(p)}}else if(O("interface")){let p=tn(d,m);c.push(p)}else if(O("type")){let p=rn(d,m);c.push(p)}else if(O("enum")){let p=Ht(d,m,!1);c.push(p)}else if(O("const")){let p=l;if(l+=5,v(),O("enum")){l=p+5,v();let g=Ht(d,m,!0);c.push(g)}else if(m){l=p;let g=Wt(d,"const",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else Re()}else if(O("let")||O("var"))if(m){let p=O("let")?"let":"var",g=Wt(d,p,!0);for(let w=0;w<g.length;w++)c.push(g[w])}else Re();else if(O("module")){let p=Kt(d,m,"module");c.push(p)}else if(O("namespace")){let p=Kt(d,m,"namespace");c.push(p)}else if(O("global")){l+=6,v();let p=`declare global ${l<a&&i.charCodeAt(l)===Y?an():"{}"}`,g=tt(d);c.push({kind:"module",name:"global",text:p,isExported:!1,leadingComments:g,start:d,end:l})}else Re()}}function fc(e,t){let r=0,n=e.length;while(r<n){let i=e.charCodeAt(r);if(i>=65&&i<=90||i>=97&&i<=122||i===95||i===36||i>127){let s=r;r++;while(r<n){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 uc(e,t){let r=0;while(r<e.length){let n=e.charCodeAt(r);if(n===le||n===fe||n===Fe){let u=n;r++;while(r<e.length)if(e.charCodeAt(r)===nt)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(n===ee&&e.charCodeAt(r+1)===ee){r+=2;while(r<e.length&&e.charCodeAt(r)!==$e&&e.charCodeAt(r)!==xe)r++;continue}if(n===ee&&e.charCodeAt(r+1)===Ae){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!Ct(n)){r++;continue}let i=r++;while(r<e.length&&Ke(e.charCodeAt(r)))r++;let s=i-1,o=r;while(s>=0&&Ue(e.charCodeAt(s)))s--;while(o<e.length&&Ue(e.charCodeAt(o)))o++;let a=s>=0?e.charCodeAt(s):0,c=o<e.length?e.charCodeAt(o):0,f=i>=3&&e.slice(i-3,i)==="...";if(c===ft||a===gt&&!f)continue;if(c===ae&&(a===Y||a===pt))continue;t.add(e.slice(i,r))}}function Sp(e,t,r){let n=new Set,i=new Set;for(let a of e)i.add(a.name);let s=new Set,o=[];for(let a=0;a<e.length;a++){let c=e[a];if(c.kind!=="import"){if(o.push(c.text),fc(c.text,s),typeof c.value==="string")uc(c.value,s)}}for(;;){let a=[];for(let[u,h]of t){if(n.has(u))continue;if(s.has(u)){if(!i.has(u)){let l=h.kind==="function"?r.get(u):void 0;if(l)for(let y of l)a.push(y);else a.push(h);i.add(u)}n.add(u)}}if(a.length===0)break;a.sort((u,h)=>(u.start??1/0)-(h.start??1/0));let c=[],f=0;for(let u=0;u<e.length;u++){let h=e[u].start??1/0;while(f<a.length&&(a[f].start??1/0)<=h)c.push(a[f++]);c.push(e[u])}while(f<a.length)c.push(a[f++]);e.length=0;for(let u=0;u<c.length;u++)e.push(c[u]);for(let u of a)if(u.kind!=="import"){if(o.push(u.text),fc(u.text,s),typeof u.value==="string")uc(u.value,s)}}}var Me=32,De=9,$e=10,xe=13,ee=47,Ae=42,le=39,fe=34,Fe=96,nt=92,Y=123,Q=125,ae=40,Ee=41,Se=91,ke=93,we=60,pe=62,re=59,ft=58,ve=61,pt=44,gt=46,Ui=63,Rs=35,$p=64,vp=36,Ps;var mc=he(()=>{Os();hn();Ps=["public","protected","private","readonly","override"]});function yc(e){return e.endsWith(".vue")}function Ap(e){let t={script:null,scriptSetup:null},r=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,n;while((n=r.exec(e))!==null){let i=n[1]||"",s=/lang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??"js",o={content:n[2]??"",attrs:i,setup:/\bsetup\b/.test(i),lang:s};if(o.setup)t.scriptSetup=o;else t.script=o}return t}function st(e,t){let r=e[t];t++;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n===r)return t+1;t++}return t}function ut(e,t){t++;let r=0;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n==="`"&&r===0)return t+1;if(n==="$"&&e[t+1]==="{"){r++,t+=2;continue}if(n==="}"){if(r>0)r--;t++;continue}t++}return t}function yt(e,t){if(e[t+1]==="/"){let r=e.indexOf(`
|
|
220
|
-
`,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 Ms(e,t){let r=e[t];if(r==='"'||r==="'")return st(e,t);if(r==="`")return ut(e,t);if(r==="/"&&(e[t+1]==="/"||e[t+1]==="*"))return yt(e,t);return t}function Ds(e){let t=e.split(""),r=0;while(r<e.length){let n=Ms(e,r);if(n>r){for(let i=r;i<n;i++)if(t[i]!==`
|
|
221
|
-
`&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function Ve(e,t,r,n){let i=0,s=t;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){s=st(e,s);continue}if(o==="`"){s=ut(e,s);continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=yt(e,s);continue}if(o===r)i++;else if(o===n){if(i--,i===0)return s}s++}return-1}function Is(e,t){let r=0,n=t;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=st(e,n);continue}if(i==="`"){n=ut(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=yt(e,n);continue}if(i==="="&&e[n+1]===">"){n+=2;continue}if(i==="<")r++;else if(i===">"){if(r--,r===0)return n}n++}return-1}function dr(e,t=","){let r=[],n=0,i="",s=0;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){let a=st(e,s);i+=e.slice(s,a),s=a;continue}if(o==="`"){let a=ut(e,s);i+=e.slice(s,a),s=a;continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=yt(e,s);continue}if(o==="{"||o==="["||o==="("||o==="<")n++;else if(o==="}"||o==="]"||o===")"||o===">")n--;if(o===t&&n===0){r.push(i),i="",s++;continue}i+=o,s++}if(i.trim()!=="")r.push(i);return r}function Pr(e){let t=e.trim();if(!t.startsWith("{"))return[];let r=Ve(t,0,"{","}");if(r===-1)return[];let n=t.slice(1,r),i=[];for(let s of dr(n)){let o=-1,a=0;for(let u=0;u<s.length;u++){let h=s[u];if(h==='"'||h==="'"){u=st(s,u)-1;continue}if(h==="`"){u=ut(s,u)-1;continue}if(h==="{"||h==="["||h==="("||h==="<")a++;else if(h==="}"||h==="]"||h===")"||h===">")a--;else if(h===":"&&a===0){o=u;break}}if(o!==-1){i.push({key:Or(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){i.push({key:Or(c[1]),value:s.trim(),isMethod:!0});continue}let f=s.trim();if(f)i.push({key:Or(f),value:"",isMethod:!1})}return i}function Or(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function Rr(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function kr(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n;while((n=r.exec(e))!==null){let i=n.index+n[0].length;while(i<e.length&&/\s/.test(e[i]))i++;let s=null;if(e[i]==="<"){let c=Is(e,i);if(c===-1)return null;s=e.slice(i+1,c).trim(),i=c+1;while(i<e.length&&/\s/.test(e[i]))i++}if(e[i]!=="(")continue;let o=Ve(e,i,"(",")");if(o===-1)return null;let a=dr(e.slice(i+1,o));return{generic:s,arg:a.length>0?a[0].trim():null}}return null}function xp(e,t){let r=Cc(e,t);if(!r)return null;return r.kind==="interface"?e.slice(r.bodyStart,r.end):e.slice(r.bodyStart,r.end).trim()}function Cc(e,t){let r=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(r){let i=r.index+r[0].length-1,s=Ve(e,i,"{","}");if(s!==-1)return{kind:"interface",start:r.index,end:s+1,bodyStart:i}}let n=new RegExp(`\\btype\\s+${t}\\b[^=]*=`,"m").exec(e);if(n){let i=n.index+n[0].length,s=0,o=i;while(i<e.length){let a=e[i];if(a==='"'||a==="'"){i=st(e,i);continue}if(a==="`"){i=ut(e,i);continue}if(a==="{"||a==="["||a==="("||a==="<")s++;else if(a==="}"||a==="]"||a===")"||a===">")s--;else if((a===";"||a===`
|
|
222
|
-
`)&&s===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:o}}return null}function Tp(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let r=e.indexOf("<",t),n=Is(e,r);if(n===-1)return null;if(e.slice(n+1).trim()!=="")return null;return e.slice(r+1,n).trim()}function ks(e){let t=e.trim(),r=Tp(t);if(r!==null)return{type:r,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let n=Ve(t,0,"[","]");if(n!==-1){let i=dr(t.slice(1,n)).map((s)=>ks(s).type).filter((s)=>s!=="unknown");return{type:i.length>0?[...new Set(i)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let n=Pr(t),i=n.find((c)=>c.key==="type"),s=n.find((c)=>c.key==="required"),o=i?ks(i.value).type:"unknown",a=!(s&&s.value.trim()==="true");return{type:o,optional:a}}if(gc[t])return{type:gc[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function Zi(e){let t=e.trim();if(t.startsWith("{")){let r=Pr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>{if(n.isMethod||n.value==="")return`${Rr(n.key)}?: unknown`;let i=ks(n.value);return`${Rr(n.key)}${i.optional?"?":""}: ${i.type}`}).join(", ")} }`}if(t.startsWith("[")){let r=Ve(t,0,"[","]");if(r===-1)return null;let n=dr(t.slice(1,r)).map((i)=>Or(i.trim())).filter((i)=>i!=="");if(n.length===0)return"{}";return`{ ${n.map((i)=>`${Rr(i)}?: unknown`).join(", ")} }`}return null}function Op(e){let t=e.trim();if(!t.startsWith("["))return null;let r=Ve(t,0,"[","]");if(r===-1)return null;let n=dr(t.slice(1,r)).map((i)=>i.trim());if(n.length===0)return"{}";if(!n.every((i)=>i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"')))return"string[]";return`[${n.map((i)=>JSON.stringify(Or(i))).join(", ")}]`}function Rp(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=Pr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>`${JSON.stringify(n.key)}: (...args: any[]) => void`).join(", ")} }`}function wc(e){return Op(e)??Rp(e)}function Pp(e){let t=[],r=0,n="",i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){let o=st(e,i);n+=e.slice(i,o),i=o;continue}if(s==="`"){let o=ut(e,i);n+=e.slice(i,o),i=o;continue}if(s==="/"&&(e[i+1]==="/"||e[i+1]==="*")){let o=yt(e,i);n+=e.slice(i,o),i=o;continue}if(s==="="&&e[i+1]===">"){n+="=>",i+=2;continue}if(s==="{"||s==="["||s==="("||s==="<")r++;else if(s==="}"||s==="]"||s===")"||s===">")r--;if((s===";"||s===","||s===`
|
|
223
|
-
`)&&r===0){if(n.trim()!=="")t.push(n.trim());n="",i++;continue}n+=s,i++}if(n.trim()!=="")t.push(n.trim());return t}function kp(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=Ve(t,0,"{","}");if(r===-1||t.slice(r+1).trim()!=="")return null;let n=Pp(t.slice(1,r));if(n.length===0)return"{}";let i=[];for(let s of n){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=st(s,a),u=s.slice(a+1,f-1),h=Ve(s,s.indexOf("(",0),"(",")");if(h===-1)return null;let l=s.slice(a,h),y=dr(l).slice(1),C=s.slice(h+1).trim();if(C.startsWith(":"))C=C.slice(1).trim();if(C==="")C="void";i.push(`${JSON.stringify(u)}: (${y.map((S)=>S.trim()).join(", ")}) => ${C}`)}return`{ ${i.join(", ")} }`}function Fs(e){let t=e;for(let r of["defineProps","defineEmits","defineExpose","defineSlots","defineOptions"])t=Mp(t,r);return t}function Mp(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n=[],i=e,s;while((s=r.exec(e))!==null){let o=e.lastIndexOf(`
|
|
224
|
-
`,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 l=Is(e,f);if(l===-1)continue;f=l+1;while(f<e.length&&/\s/.test(e[f]))f++}if(e[f]!=="(")continue;let u=Ve(e,f,"(",")");if(u===-1)continue;if(c[1]){let l=o+a.length-c[1].length,y=e.indexOf("(",l);if(y!==-1){let C=Ve(e,y,"(",")");if(C!==-1)u=C}}let h=u+1;while(h<e.length&&e[h]!==`
|
|
225
|
-
`&&/\s|;/.test(e[h]))h++;if(e[h]===`
|
|
226
|
-
`)h++;n.push([o,h])}for(let o=n.length-1;o>=0;o--)i=i.slice(0,n[o][0])+i.slice(n[o][1]);return i}function Ns(e){let t=Dp(e);if(t!==-1){let r=/^export\s+default\b/.exec(e.slice(t))?.[0];if(!r)return{options:null,script:e,passthrough:!1};let n=t+r.length;while(n<e.length&&/\s/.test(e[n]))n++;let i=-1,s=-1,o=-1;if(e[n]==="{")i=n,s=Ve(e,n,"{","}"),o=s;else if(e.startsWith("defineComponent",n)){let f=e.indexOf("(",n);if(f!==-1){let u=f+1;while(u<e.length&&/\s/.test(e[u]))u++;if(e[u]==="{")i=u,s=Ve(e,u,"{","}"),o=Ve(e,f,"(",")")}}if(i===-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,t)+e.slice(a)).trim();return{options:e.slice(i,s+1),script:c,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function Dp(e){let t=0,r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=st(e,r);continue}if(n==="`"){r=ut(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=yt(e,r);continue}if(n==="{"||n==="["||n==="(")t++;else if(n==="}"||n==="]"||n===")")t=Math.max(0,t-1);else if(t===0&&e.startsWith("export",r)){let i=r===0?"":e[r-1],s=e[r+6]??"";if(!/[\w$]/.test(i)&&!/[\w$]/.test(s)){if(/^export\s+default\b/.exec(e.slice(r)))return r}}r++}return-1}function Hi(e,t){let r=Pr(e).find((n)=>n.key===t);return r&&r.value!==""?r.value:null}function Ki(e,t){let r=Fp(e),n=e;for(let i=r.length-1;i>=0;i--){let s=r[i],o=n.slice(0,s.start)+n.slice(s.end);if(Ip(o,s.name))continue;if(new RegExp(`\\btypeof\\s+${s.name}\\b`).test(t))continue;n=o}return n}function Ip(e,t){let r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=st(e,r);continue}if(n==="`"){r=ut(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=yt(e,r);continue}if(/[A-Za-z_$]/.test(n)){let i=r+1;while(i<e.length&&/[\w$]/.test(e[i]))i++;if(e.slice(r,i)===t)return!0;r=i;continue}r++}return!1}function Fp(e){let t=[],r=Np(e),n=/^[ \t]*(const|let|var|(?:async[ \t]+)?function)[ \t]+([A-Za-z_$][\w$]*)[ \t]*(?::[^=\n]+)?=?/gm,i;while((i=n.exec(e))!==null){let s=e.lastIndexOf(`
|
|
227
|
-
`,i.index)+1;if(!r.has(s))continue;if(/\bexport\b/.test(e.slice(s,i.index)))continue;let o=i[1],a=i[2],c=i.index+i[0].length,f=-1;if(o.endsWith("function")){let u=e.indexOf("(",c);if(u===-1)continue;let h=Ve(e,u,"(",")");if(h===-1)continue;c=h+1;while(c<e.length&&/\s/.test(e[c]))c++;if(e[c]===":")while(c<e.length&&e[c]!=="{"&&e[c]!==`
|
|
228
|
-
`)c++;while(c<e.length&&/\s/.test(e[c])&&e[c]!==`
|
|
229
|
-
`)c++;if(e[c]!=="{")continue;let l=Ve(e,c,"{","}");if(l===-1)continue;f=l+1}else{let u=0;while(c<e.length){let h=e[c];if(h==='"'||h==="'"){c=st(e,c);continue}if(h==="`"){c=ut(e,c);continue}if(h==="/"&&(e[c+1]==="/"||e[c+1]==="*")){c=yt(e,c);continue}if(h==="{"||h==="["||h==="(")u++;else if(h==="}"||h==="]"||h===")")u--;else if(h===";"&&u===0){f=c+1;break}else if(h===`
|
|
230
|
-
`&&u===0){f=c;break}c++}if(f===-1)f=e.length}if(e[f]===`
|
|
231
|
-
`)f++;t.push({name:a,start:i.index,end:f})}return t}function Np(e){let t=new Set([0]),r=0,n=0;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=st(e,n);continue}if(i==="`"){n=ut(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=yt(e,n);continue}if(i==="{"||i==="["||i==="(")r++;else if(i==="}"||i==="]"||i===")")r=Math.max(0,r-1);if(i===`
|
|
232
|
-
`&&r===0)t.add(n+1);n++}return t}function ji(e,t,r){let n=e.indexOf(r);if(n===-1)return e;let i=e.lastIndexOf(`
|
|
233
|
-
`,n)+1;if(/\bexport\b/.test(e.slice(i,n)))return e;let s=e.slice(0,n)+e.slice(n+r.length);if(new RegExp(`\\b${t}\\b`).test(s))return e;return s}function Ws(e){let t="",r=0,n=()=>{for(let s=t.length-1;s>=0;s--)if(!/\s/.test(t[s]))return t[s];return""},i=(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=st(e,r);t+=e.slice(r,o),r=o;continue}if(s==="`"){let o=ut(e,r);t+=e.slice(r,o),r=o;continue}if(s==="/"&&e[r+1]==="*"){let o=yt(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]!==`
|
|
234
|
-
`)o++;let a=e.slice(r+2,o).trim();if(a!==""&&!a.includes("*/"))t+=`/* ${a} */`;r=o;continue}if(s===`
|
|
235
|
-
`){let o=n(),a=i(r+1);if(o===""||a===""){r++;continue}let c=Wp(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 Wp(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 n=r-1;n>=0;n--){let i=e[n];if(/\s/.test(i))continue;return"{;,(<:".includes(i)}return!0}function Yi(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=kr(n,"defineProps");if(!i)continue;if(i.generic){let s=i.generic;if(s.startsWith("{"))return{type:s};if(/^[A-Za-z_$][\w$]*$/.test(s)){for(let o of r){let a=Cc(o,s);if(!a)continue;let c=xp(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(i.arg){let s=Zi(i.arg);if(s!==null)return{type:s}}}return null}function Ls(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=kr(n,"defineEmits");if(!i)continue;if(i.generic)return kp(i.generic)??i.generic;if(i.arg){let s=wc(i.arg);if(s!==null)return s}}return null}function Gs(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=kr(n,"defineExpose");if(!i||!i.arg||!i.arg.startsWith("{"))continue;let s=Pr(i.arg);if(s.length===0)return null;return`{ ${s.map((o)=>{if(o.value===""&&/^[A-Za-z_$][\w$]*$/.test(o.key))return`${Rr(o.key)}: typeof ${o.key}`;let a=o.isMethod||/=>|^\s*function\b/.test(o.value);return`${Rr(o.key)}: ${a?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function $c(e){let t=Ap(e),r="",n=null,i=null;if(t.script){let x=Ns(t.script.content);if(x.passthrough)return t.scriptSetup?`${t.script.content}
|
|
236
|
-
${t.scriptSetup.content}`:t.script.content;if(r=x.script,x.options){let v=Hi(x.options,"props");if(v)n=Zi(v);let B=Hi(x.options,"emits");if(B)i=wc(B)}}let s=t.scriptSetup?.content??null,o=s!==null?Fs(s):null,a=Yi(s,s!==null?null:r),c=a?.type??n??"{}",f=Ls(s,null)??i,u=Gs(s,null),h=a?.inlinedLocal;if(h){if(r=ji(r,h.name,h.declText),o!==null)o=ji(o,h.name,h.declText)}let l=[c,u??"{}"];if(f)l.push("{}","{}","{}","{}","{}",f);let y=Ws(`DefineComponent<${l.join(", ")}>`),C=[],S=Ki(r,y);if(S.trim()!=="")C.push(S);if(o&&o.trim()!==""){let x=Ki(o,y);if(x.trim()!=="")C.push(x)}return C.push("import type { DefineComponent } from 'vue'"),C.push(`type __DtsxComponentType = ${y}`),C.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),C.push("export default __dtsx_component__"),C.join(`
|
|
237
|
-
`)}var gc;var Bs=he(()=>{gc={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 bc(e){return e.endsWith(".stx")}function Lp(e){let t=[],r=/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi,n;while((n=r.exec(e))!==null){let i=n[1]??"",s=/\blang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??(/\b(?:type\s*=\s*["'](?:text\/)?typescript["']|typescript)\b/i.test(i)?"ts":"js"),o=/\bserver\b/i.test(i)?"server":/\bclient\b/i.test(i)?"client":"universal";t.push({content:n[2]??"",kind:"script",attrs:i,context:o,lang:s,start:n.index})}return t}function Gp(e){let t=[],r=/^[ \t]*@ts[ \t]*(?:\r?\n|$)/gm,n;while((n=r.exec(e))!==null){let i=r.lastIndex,s=/^[ \t]*@endts[ \t]*(?:\r?\n|$)/gm;s.lastIndex=i;let o=s.exec(e),a=o?.index??e.length;if(t.push({content:e.slice(i,a),kind:"ts",attrs:"",context:"universal",lang:"ts",start:n.index}),!o)break;r.lastIndex=s.lastIndex}return t}function Bp(e){return[...Lp(e),...Gp(e)].sort((t,r)=>t.start-r.start)}function _p(e){if(e.kind==="ts"||e.context!=="universal"||e.lang==="ts")return!0;return/\b(?:defineProps|defineEmits|defineExpose|defineSlots)\b|\bexport\s|\b(?:interface|type)\s+[A-Za-z_$]/.test(e.content)}function Up(e){let t=/(?:\$?props)\s+as\s+/g,r;while((r=t.exec(e))!==null){let n=t.lastIndex;while(n<e.length&&/\s/.test(e[n]))n++;if(e[n]==="{"){let o=Ve(e,n,"{","}");if(o!==-1)return e.slice(n,o+1).trim();continue}let i=/^[A-Za-z_$][\w$]*/.exec(e.slice(n))?.[0];if(!i)continue;let s=n+i.length;while(s<e.length&&/\s/.test(e[s]))s++;if(e[s]==="<"){let o=Ve(e,s,"<",">");if(o!==-1)s=o+1}return e.slice(n,s).trim()}return null}function Vp(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function Hp(e){let t=/^\s*(?:\|\||\?\?)\s*([^;\n]+)/.exec(e)?.[1]?.trim();if(/^['"`]/.test(t??""))return"string";if(/^(?:true|false)\b/.test(t??""))return"boolean";if(/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)\b/.test(t??""))return"number";if(/^\[/.test(t??""))return"unknown[]";if(/^\{/.test(t??""))return"Record<string, unknown>";if(/^\s*(?:===?|!==?)\s*(?:true|false)\b/.test(e))return"boolean";return"unknown"}function Kp(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function jp(e){let t=Ds(e),r=new Map,n=/\$props(?:\.([A-Za-z_$][\w$]*)|\[\s*(['"])([^'"\n]+)\2\s*\])/g,i;while((i=n.exec(e))!==null){if(t.slice(i.index,i.index+6)!=="$props")continue;let s=i[1]??i[3],o=Hp(e.slice(n.lastIndex));r.set(s,Kp(r.get(s),o))}if(r.size===0)return null;return{type:`{ ${[...r].map(([s,o])=>`${/^[A-Za-z_$][\w$]*$/.test(s)?s:JSON.stringify(s)}?: ${o}`).join(", ")} }`}}function Zp(e){let t=Yi(e,null);if(t)return t;let r=Up(e)??Vp(e);if(!r)return jp(e);if(/^[A-Za-z_$][\w$]*$/.test(r)){let n=r.replace(/[$]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:declare\\s+)?(?:interface|type)\\s+${n}\\b`).test(e))return{type:r}}return Yi(`${e}
|
|
238
|
-
defineProps<${r}>()`,null)}function Yp(e){return Fs(e)}function vc(e){let t=Ds(e).trimStart();if(t==="")return!0;return/^(?:import\b|export\b|declare\b|interface\b|type\b|(?:export\s+)?namespace\b|(?:export\s+)?module\b|(?:abstract\s+)?class\b|const\b|let\b|var\b|(?:async\s+)?function\b)/.test(t)}function Jp(e){let t=[],r=0,n=0,i=0;while(i<e.length){let o=e[i],a=Ms(e,i);if(a>i){i=a;continue}if(o==="{"||o==="["||o==="(")n++;else if(o==="}"||o==="]"||o===")")n=Math.max(0,n-1);if((o===";"||o===`
|
|
239
|
-
`)&&n===0){let c=i+1;if(!vc(e.slice(r,c)))t.push([r,c]);r=c}i++}if(r<e.length&&!vc(e.slice(r)))t.push([r,e.length]);let s=e;for(let o=t.length-1;o>=0;o--)s=s.slice(0,t[o][0])+s.slice(t[o][1]);return s}function Ec(e){let t=Bp(e).filter(_p).map((S)=>S.content).join(`
|
|
240
|
-
`),r=null,n=Ns(t);if(n.passthrough)return t;if(t=n.script,n.options){let S=Hi(n.options,"props");if(S)r=Zi(S)}let i=t,s=Yp(t),o=Zp(i),a=o?.type??r??"{}",c=Ls(i,null),f=Gs(i,null),u=kr(i,"defineSlots")?.generic??null,h=o?.inlinedLocal;if(h)s=ji(s,h.name,h.declText);let l=`DefineComponent<${a}>`,y=[];if(c)y.push(`readonly __stxEmits?: ${c}`);if(u)y.push(`readonly __stxSlots?: ${u}`);if(f)y.push(`readonly __stxExposed?: ${f}`);if(y.length>0)l+=` & { ${y.join(", ")} }`;l=Ws(l),s=Jp(Ki(s,l));let C=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${l}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(s.trim()!=="")C.push(s);return C.join(`
|
|
241
|
-
`)}var Sc=he(()=>{Bs()});function xc(e,t,r=!0,n=!1){if(yc(t))e=$c(e);else if(bc(t))e=Ec(e);let i=xr(e),s=`${t}:${r?1:0}:${n?1:0}`,o=pr.get(s);if(o&&o.contentHash===i)return o.lastAccess=++Ac,o.declarations;let a=n?hc(e,t,r):dc(e,t,r);if(pr.set(s,{declarations:a,contentHash:i,lastAccess:++Ac}),pr.size>qp){let c=Math.max(1,Math.ceil(pr.size*0.1)),f=[];for(let[u,h]of pr)f.push([u,h.lastAccess]);f.sort((u,h)=>u[1]-h[1]);for(let u=0;u<c&&u<f.length;u++)pr.delete(f[u][0])}return a}var qp=100,Ac=0,pr;var Tc=he(()=>{mc();Sc();us();Bs();pr=new Map});function Oc(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 Rc=()=>{};function Pc(e,t,r=!0,n=!1){return xc(e,t,r,n)}var kc=he(()=>{Tc()});class Ji{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 n=await r.onStart(t);if(n)t=n}return this.config=t,t}async runOnBeforeFile(e,t){let r=t;for(let n of this.plugins)if(n.onBeforeFile){let i={filePath:e,sourceCode:t,content:r,config:this.config,log:this.createLogger(n.name)},s=await n.onBeforeFile(i);if(typeof s==="string")r=s}return r}async runOnDeclarations(e,t,r){let n=r;for(let i of this.plugins)if(i.onDeclarations){let s={filePath:e,sourceCode:t,declarations:n,config:this.config,log:this.createLogger(i.name)},o=await i.onDeclarations(s);if(o)n=o}return n}async runOnAfterFile(e,t,r){let n=r;for(let i of this.plugins)if(i.onAfterFile){let s={filePath:e,sourceCode:t,content:n,config:this.config,log:this.createLogger(i.name)},o=await i.onAfterFile(s);if(typeof o==="string")n=o}return n}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,r){for(let n of this.plugins)if(n.onError){let i={filePath:t,sourceCode:r,config:this.config,log:this.createLogger(n.name)};await n.onError(e,i)}}}function zp(e){return e}var Y0,J0;var Mc=he(()=>{Y0=new Ji;J0=zp({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(e)=>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})})});import{existsSync as Dc}from"fs";import{mkdir as Ic,readdir as Xp,realpath as Qp,rm as em}from"fs/promises";import{availableParallelism as tm}from"os";import{basename as Ks,dirname as qi,extname as rm,isAbsolute as Dr,parse as im,relative as Ge,resolve as et}from"path";function Lc(e){let t=_s.get(e);if(!t)t=Po(e),_s.set(e,t),t.catch(()=>_s.delete(e));return t}async function Fc(e,t,r,n,i,s=ki){let o=Ks(e)||"output.d.ts",a=Ge(qi(e),t),c=`${o}.map`,f=r.lastIndexOf(`
|
|
242
|
-
${fs()}`),u=f===-1?r:r.slice(0,f),h=Sl(u,o,a,n),l=`${e}.map`;return await s(l,JSON.stringify(h)),q.debug(` Generated source map: ${Ge(i,l)}`),c}async function js(e){let t=Date.now(),r={...ul,...e};if(r.logLevel)fn(r.logLevel);else if(r.verbose)fn("debug");let n=new Ji;if(r.plugins&&r.plugins.length>0){for(let P of r.plugins)n.register(P),q.debug(`Registered plugin: ${P.name}`);r=await n.runOnStart(r)}if(await sm(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await vl(r);let i=r.typeMappings?Mi(r.typeMappings):void 0,s=null,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;q.debug("Starting DTS generation..."),q.debug(`Using ${o.generationMode} declaration generation path`),q.debug("Config:",r);let c=await fm(r);cm(r,c);let f=c.slice(),u=await Lc(r),h=null;if(r.autoIncludeReExports!==!1&&f.length>0){h=await $n(f,{includeImports:!0,resolveSpecifier:u});let P=et(r.cwd,r.root),F=r.exclude||[],I=[];for(let k of h.reachable){if(f.includes(k))continue;if(!Hs(k))continue;if(k.endsWith(".d.ts"))continue;if(k.includes("node_modules"))continue;let H=r.outputStructure==="flat"&&c.some((j)=>u.isPackageLocal?.(j,k));if(!Ir(k,P)&&!H){q.warn(`Skipping auto-included source outside root: ${Ge(r.cwd,k)}`);continue}if(Vs(k,F,P))continue;I.push(k)}if(I.length>0)f=[...f,...I],q.debug(`Auto-included ${I.length} file(s) reached via relative re-exports`)}if(um(f,r),Us.set(r,new Set(f)),r.incremental){if(s=new ps(r,u.cacheKey?.(f)),r.clearCache){if(q.debug("Clearing build cache..."),!r.dryRun)s.clear()}else if(s.load()){let P=s.getStats();q.debug(`Loaded build cache with ${P.entries} entries`)}else q.debug("No existing build cache found, starting fresh");if(!r.dryRun)Ll(r.cwd)}if(s&&!r.dryRun){let P=s.prune(new Set(f),r.cwd);if(P>0)q.debug(`Pruned ${P} deleted files from cache`)}if(q.debug(`Found ${f.length} TypeScript files`),r.progress&&f.length>0){let P=r.parallel?"parallel":"sequential";q.info(`Processing ${f.length} files (${P})...`)}let l=new Map,y=new Map,C=async(P,F,I="lf")=>{y.set(P,{content:F,lineEnding:I})},S=async(P,F)=>{let I;try{let k=Fr(P,r),H=async(oe)=>{if(!r.diff)return;try{let L=await kt(k),K=El(L,oe,Ge(r.cwd,k));if(K)q.info(`
|
|
243
|
-
${K}`);else q.debug(`[no changes] ${k}`)}catch{q.info(`[new file] ${Ge(r.cwd,k)}`)}},j=(oe)=>{if(!r.validate)return 0;let L=bl(oe,k);if(L.isValid)return q.debug(`[validation] ${k} - OK`),0;q.warn(`[validation] ${Ge(r.cwd,k)} has ${L.errors.length} error(s):`);for(let K of L.errors){let J=` Line ${K.line}:${K.column}`;if(K.code)J+=` [${K.code}]`;if(J+=` - ${K.message}`,q.warn(J),K.suggestion)q.warn(` Suggestion: ${K.suggestion}`)}return L.errors.length},O=(oe)=>{q.info(`[dry-run] Would generate: ${k}`),q.debug("--- Content preview ---"),q.debug(oe.slice(0,500)+(oe.length>500?`
|
|
244
|
-
...`:"")),q.debug("--- End preview ---")};if(s){let oe=s.getCachedIfValid(P,r.cwd);if(oe){if(r.bundle)l.set(P,oe);await H(oe);let L=j(oe);if(r.dryRun)O(oe);else{if(r.declarationMap)I=F??await kt(P),await Fc(k,P,oe,I,r.cwd,C);await C(k,oe,r.lineEnding)}return q.debug(`[cached] ${Ge(r.cwd,k)}`),{success:!0,file:P,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:L}}}I=F??await kt(P);let{content:Z,declarationCount:me,importCount:Oe,exportCount:ie}=await pm(P,I,r,n,i);if(r.bundle)l.set(P,Z);let ne=Z;if(r.prettier||r.indentStyle||r.indentSize){let oe=await _o(ne,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},k);ne=oe.content;for(let L of oe.warnings??[])q.warn(`[format] ${L}`)}if(r.declarationMap){let oe=`${Ks(k)||"output.d.ts"}.map`;ne=Al(ne,oe)}await H(ne);let ue=j(ne);if(r.dryRun)O(ne);else{if(r.declarationMap&&I)await Fc(k,P,ne,I,r.cwd,C);if(await C(k,ne,r.lineEnding),s&&I)s.update(P,I,ne,r.cwd);q.debug(`Generated: ${k}`)}return{success:!0,file:P,declarationCount:me,importCount:Oe,exportCount:ie,validationErrorCount:ue}}catch(k){let H=Tl(k,P,I);if(r.plugins&&r.plugins.length>0)await n.runOnError(k instanceof Error?k:Error(String(k)),P,I||"");return{success:!1,file:P,declarationCount:0,importCount:0,exportCount:0,dtsError:H,validationErrorCount:0}}},x=r.parallel||r.parallel!==!1&&f.length>=10,v=Oc(r.concurrency,tm?.()??8),B=new Map;if(x&&f.length>1){let P=f.map(async(F)=>{try{let I=await kt(F);return{file:F,source:I}}catch{return{file:F,source:null}}});for(let F of await Promise.all(P))if(F.source!==null)B.set(F.file,F.source)}let W=(P)=>{if(o.filesProcessed++,P.success){if(P.cached)a++;else o.filesGenerated++,o.declarationsFound+=P.declarationCount,o.importsProcessed+=P.importCount,o.exportsProcessed+=P.exportCount;if(r.validate){if(o.filesValidated++,P.validationErrorCount)o.validationErrors+=P.validationErrorCount}}else if(o.filesFailed++,P.dtsError){o.errors.push(P.dtsError);let F=Ol(P.dtsError);if(r.continueOnError)q.warn(F);else throw q.error(F),Error(P.dtsError.message)}};if(x)for(let P=0;P<f.length;P+=v){let F=f.slice(P,P+v),I=await Promise.all(F.map((k)=>S(k,B.get(k))));for(let k of I)W(k);if(r.progress){let k=Math.round(o.filesProcessed/f.length*100);q.info(`[${o.filesProcessed}/${f.length}] ${k}%`)}}else for(let P of f){let F=await S(P);if(W(F),r.progress){let I=Math.round(o.filesProcessed/f.length*100),k=F.cached?"[cached]":"";q.info(`[${o.filesProcessed}/${f.length}] ${I}% - ${Ge(r.cwd,P)} ${k}`)}}if(!r.dryRun){if(r.clean)await am(r);for(let[P,F]of y)await Ic(qi(P),{recursive:!0}),await ki(P,F.content,F.lineEnding)}if(s&&!r.dryRun)s.save(),q.debug("Saved build cache");if(!r.bundle){let P=[];if(h)for(let F of h.unresolved)P.push({from:F.from,specifier:F.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&f.length>0){let F=new Set(f);for(let I of f){let k;try{k=await kt(I)}catch{continue}for(let H of jr(k)){let j=u(H.specifier,I);if(!j.isRelative)continue;if(!j.resolved)P.push({from:I,specifier:H.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(j.resolved)&&!F.has(j.resolved))P.push({from:I,specifier:H.specifier,reason:"not-emitted"})}}}if(P.length>0){let F=[];F.push(`Found ${P.length} re-export(s) pointing at siblings that won't be in the output:`);for(let k of P){let H=Ge(r.cwd,k.from);if(k.reason==="missing")F.push(` ${H} \u2192 '${k.specifier}' (path not found on disk)`);else F.push(` ${H} \u2192 '${k.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let I=F.join(`
|
|
245
|
-
`);if(r.failOnUnresolvedReExport)throw Error(I);q.warn(I),q.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{q.debug("Bundling declarations...");let P=c.length===1&&!!r.bundleOutput;for(let F of c){let I=await $n([F],{includeImports:!0,resolveSpecifier:u}),k=new Set;for(let Z of I.reachable){if(Z.endsWith(".d.ts"))continue;if(Z.includes("node_modules"))continue;k.add(Z)}let H=f.filter((Z)=>k.has(Z));if(!H.includes(F))H.push(F);let j=Fo(F,H,l,{cwd:r.cwd,keepComments:r.keepComments});for(let Z of new Set(j.warnings))q.warn(`[bundle] ${Z}`);let O=P?et(r.cwd,r.outdir,r.bundleOutput):Fr(F,r);if(r.dryRun)q.info(`[dry-run] Would bundle ${j.files.length} files to: ${Ge(r.cwd,O)}`);else await Ic(qi(O),{recursive:!0}),await ki(O,j.content,r.lineEnding),q.info(`Bundled ${j.files.length} files to: ${Ge(r.cwd,O)}`);if(P)break}}catch(P){let F=P instanceof Error?P.message:String(P);q.error(`Bundle failed: ${F}`)}if(o.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(o,null,2));else{if(q.info(`
|
|
246
|
-
--- Generation Statistics ---`),q.info(`Files processed: ${o.filesProcessed}`),q.info(`Files generated: ${o.filesGenerated}`),a>0)q.info(`Files cached: ${a}`);if(o.filesFailed>0)q.info(`Files failed: ${o.filesFailed}`);if(q.info(`Declarations found: ${o.declarationsFound}`),q.info(`Imports processed: ${o.importsProcessed}`),q.info(`Exports processed: ${o.exportsProcessed}`),o.filesValidated>0){if(q.info(`Files validated: ${o.filesValidated}`),o.validationErrors>0)q.info(`Validation errors: ${o.validationErrors}`)}if(q.info(`Duration: ${o.durationMs}ms`),o.errors.length>0){q.info(`
|
|
247
|
-
Errors:`);for(let P of o.errors){let F=` - ${P.file}`;if(P.location)F+=`:${P.location.line}:${P.location.column}`;if(P.code)F+=` [${P.code}]`;if(F+=`: ${P.message}`,q.info(F),P.suggestion)q.info(` Suggestion: ${P.suggestion}`)}}q.info(`-----------------------------
|
|
248
|
-
`)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(o);return q.debug("DTS generation complete!"),o}async function Nc(e){try{return await Qp(e)}catch{return et(e)}}async function sm(e){let t=et(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(Dr(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=et(t,e.bundleOutput);if(!Ir(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===im(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([Nc(t),Nc(et(e.cwd,e.root))]);if(Ir(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function om(e){let t=Mr.get(e);if(!t){if(t=new Wc(e),Mr.set(e,t),Mr.size>nm){let r=Mr.keys().next().value;if(r!==void 0)Mr.delete(r)}}return t}async function am(e){let t=et(e.cwd,e.outdir);async function r(n){let i;try{i=await Xp(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(s)=>{let o=et(n,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 em(o,{force:!0})}))}await r(t)}function Vs(e,t,r){if(!t||t.length===0)return!1;let n=Ge(r,e);for(let i of t){let s=om(i);if(s.match(n)||s.match(e))return!0}return!1}function cm(e,t){let r=et(e.cwd,e.root),n=` root: ${r}
|
|
249
|
-
entrypoints: ${e.entrypoints.map((s)=>JSON.stringify(s)).join(", ")||"(none)"}
|
|
250
|
-
`+(e.exclude?.length?` exclude: ${e.exclude.map((s)=>JSON.stringify(s)).join(", ")}
|
|
251
|
-
`:"")+"Entrypoints are resolved relative to --root. Pass several by repeating --entrypoints or separating them with commas.";if(t.length===0){if(e.entrypoints.filter((s)=>Dr(s)&&Dc(s)&&!Ir(s,r)).length===e.entrypoints.length)return;throw Error(`No source files matched. Nothing was generated.
|
|
252
|
-
${n}`)}let i=e.entrypoints.filter((s)=>{if(lm.test(s))return!1;return!Dc(Dr(s)?s:et(r,s))});if(i.length>0)throw Error(`Entrypoint${i.length>1?"s":""} not found: ${i.map((s)=>JSON.stringify(s)).join(", ")}
|
|
253
|
-
${n}`)}async function fm(e){let t=[],r=et(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let s of i)if(Dr(s)&&Hs(s)){if(!s.includes("node_modules")){if(!Ir(s,r)&&e.outputStructure!=="flat")q.warn(`Skipping entrypoint outside root: ${Ge(e.cwd,s)}`);else if(!Vs(s,n,r))t.push(s)}}else{let o=new Wc(s);for await(let a of o.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(Hs(a)&&!a.includes("node_modules")){if(!Vs(a,n,r))t.push(a)}}return[...new Set(t.map((s)=>et(s)))].sort()}function Ir(e,t){let r=Ge(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Dr(r)}function um(e,t){let r=new Map;for(let n of e){let i=Fr(n,t),s=r.get(i);if(s&&s!==n)throw Error(`Output path collision: ${Ge(t.cwd,s)} and ${Ge(t.cwd,n)} both emit ${Ge(t.cwd,i)}`);r.set(i,n)}}function Hs(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function Fr(e,t){let r=et(t.cwd,t.root),n=Ge(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(i)=>{if(i===".mts"||i===".mjs")return".d.mts";if(i===".cts"||i===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return et(t.cwd,t.outdir,n);else{let i=Ks(n);return et(t.cwd,t.outdir,i)}}function hm(e,t,r=""){let n=Ge(qi(e),t).replace(/\\/g,"/");if(n=n.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)n+=r;if(!n.startsWith("."))n=`./${n}`;return n}async function dm(e,t,r){let n=await Lc(r),i=Fr(t,r);return Mo(e,(s)=>{let o=n(s,t);if(!o.isRelative||!o.resolved)return s;if(/\.d\.(?:ts|mts|cts)$/.test(o.resolved))return s;if(o.isAlias&&Us.has(r)&&!Us.get(r).has(o.resolved))throw Error(`Local alias ${JSON.stringify(s)} from ${t} targets a declaration excluded from this package build: ${o.resolved}`);let a=o.isAlias?o.suffix??"":s.match(/[?#].*$/)?.[0]??"",c=a?s.slice(0,-a.length):s,f=rm(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return hm(i,Fr(o.resolved,r),u)+a})}async function pm(e,t,r,n,i){let s=t;if(n)s=await n.runOnBeforeFile(e,t);let o=Pc(s,e,r.keepComments,r.isolatedDeclarations??!1);if(n)o=await n.runOnDeclarations(e,s,o);let a=0,c=0;for(let u=0;u<o.length;u++){let h=o[u];if(h.kind==="import")a++;if(h.kind==="export"||h.isExported)c++}let f=lc(o,{filePath:e,sourceCode:s,declarations:o},r.keepComments,r.importOrder);if(f=await dm(f,e,r),i)f=Ml(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=Go(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)f=await n.runOnAfterFile(e,s,f);return{content:f,declarationCount:o.length,importCount:a,exportCount:c}}var Wc,_s,Us,nm=50,Mr,lm;var Gc=he(()=>{No();vn();Bo();Uo();xl();hl();Rl();Dl();Gl();Ur();un();cc();kc();Rc();Mc();({Glob:Wc}=globalThis.Bun),_s=new WeakMap,Us=new WeakMap;Mr=new Map;lm=/[*?[\]{}!]/});var Bc=he(()=>{Gc()});import{createHash as gm}from"crypto";import{existsSync as ym,readFileSync as Cm,writeFileSync as wm}from"fs";import{dirname as $m,join as vm,relative as _c,resolve as Nr,sep as zi}from"path";import Vc from"process";class Hc{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},n=this.listeners.get(e)||[];for(let i of n)await i(r)}}class Kc{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=vm(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(ym(this.manifestPath)){let t=JSON.parse(Cm(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}=mm("fs");e(this.cacheDir,{recursive:!0}),wm(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 bm(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return gm("md5").update(JSON.stringify(t)).digest("hex")}function jc(e={}){let{onSuccess:t,onError:r,failOnError:n=!0,incremental:i=!1,cacheDir:s=".dtsx-cache",on:o,timeout:a=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,h=new Hc;if(o){for(let[l,y]of Object.entries(o))if(y)h.on(l,y)}return{name:"bun-plugin-dtsx",async setup(l){let y=Date.now(),C=null,S=0;try{let x=Am(u,l),v=bm(x);if(x.clean){let F=Nr(x.cwd??Vc.cwd(),x.outdir??"./dist");if(Uc.has(F))x.clean=!1;else Uc.add(F)}if(i)C=new Kc(Nr(s),v);if(await h.emit("start",{type:"start",files:x.entrypoints||[],config:x}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),i)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let W=await(async()=>new Promise((F,I)=>{let k=setTimeout(()=>{I(new Wr(`Generation timed out after ${a}ms`,"TIMEOUT_ERROR",{timeout:a}))},a);js(x).then((H)=>{clearTimeout(k),F(H)}).catch((H)=>{clearTimeout(k),I(H)})}))(),P=Date.now()-y;if(C)C.save();if(await h.emit("complete",{type:"complete",stats:W,duration:P,fromCache:S}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${P}ms`),S>0)console.log(`[bun-plugin-dtsx] ${S} files served from cache`)}if(t)await t(W)}catch(x){let v=Em(x);if(await h.emit("error",{type:"error",error:v}),r)await r(v);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${v.code}`),console.error(` Message: ${v.message}`),v.context)console.error(` Context: ${JSON.stringify(v.context)}`);if(f&&v.stack)console.error(` Stack: ${v.stack}`)}if(n&&!c)throw v}}}}function Em(e){if(e instanceof Wr)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 Wr(e.message,t,{originalError:e.name},e)}return new Wr(String(e),"GENERATION_ERROR")}function Sm(e){let t=e.map((n)=>$m(n).split(zi)),r=t[0];for(let n of t.slice(1)){let i=0;while(i<r.length&&i<n.length&&r[i]===n[i])i++;r=r.slice(0,i)}return r.join(zi)||zi}function Am(e,t){let r=e.cwd||Vc.cwd(),n=t?.config?.entrypoints,i=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",s=e.root||e.build?.config.root||t?.config.root;if(!s&&n?.length){let a=Sm(n.map((c)=>Nr(r,c)));s=_c(r,a)||"."}s=s||"./src";let o=e.entrypoints;if(!o)if(n?.length){let a=Nr(r,s),c=[];for(let f of n){let u=Nr(r,f);if(u===a||u.startsWith(a+zi))c.push(_c(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:i,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}var mm,Wr,Uc;var Zc=he(()=>{Bc();mm=import.meta.require;Wr=class Wr extends Error{code;context;cause;constructor(e,t,r,n){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=r,this.cause=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};Uc=new Set});import{mkdir as xm,stat as Tm}from"fs/promises";import{bold as Zs,dim as Ys,green as Om,italic as Yc,log as Rm}from"@stacksjs/cli";import{path as ot}from"@stacksjs/path";import{glob as Jc}from"@stacksjs/storage";function ln(e){let t=new Map;for(let o of e){if(t.has(o.name))throw Error(`duplicate package name: ${o.name}`);t.set(o.name,o)}let r=new Map,n=new Set,i=(o,a)=>{let c=r.get(o);if(c!==void 0)return c;if(n.has(o))throw Error(`dependency cycle: ${[...a,o].join(" -> ")}`);n.add(o);let f=t.get(o).dependencies.filter((h)=>h!==o&&t.has(h)),u=f.length?1+Math.max(...f.map((h)=>i(h,[...a,o]))):0;return n.delete(o),r.set(o,u),u},s=[];for(let o of[...e].sort((a,c)=>a.name.localeCompare(c.name)))(s[i(o.name,[])]||=[]).push(o);return s.filter(Boolean)}import{existsSync as lf,readdirSync as cf,readFileSync as co}from"fs";import{join as cn}from"path";function ff(e){return[...cf(e,{withFileTypes:!0}).filter((r)=>r.isDirectory()).map((r)=>cn(e,r.name)),e].filter((r)=>{let n=cn(r,"package.json");if(!lf(n))return!1;let i=JSON.parse(co(n,"utf8"));return!i.private&&!!i.scripts?.build})}async function uf(e){let t=e.map((i)=>{let s=JSON.parse(co(cn(i,"package.json"),"utf8"));if(!s.name||!s.scripts?.build)throw Error(`Not a buildable workspace package: ${i}`);return{name:s.name,dir:i,dependencies:Object.keys(s.dependencies??{})}}),r=ln(t),n=[];for(let{name:i,dir:s,dependencies:o}of r.flat()){let a=n.filter((f)=>f.exitCode!==0&&o.includes(f.name)).map((f)=>f.name);if(a.length){console.error(`Cannot build ${s}: dependencies failed: ${a.join(", ")}`),n.push({name:i,dir:s,exitCode:null,blockedBy:a});continue}console.log(`Building ${s}`);let c=Bun.spawn([process.execPath,"run","build"],{cwd:s,stdout:"inherit",stderr:"inherit"});n.push({name:i,dir:s,exitCode:await c.exited,blockedBy:[]})}return n}async function Pm(e){let t=await Jc([ot.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let n of t){let i=await Bun.file(n).text();try{r.transformSync(i)}catch(s){throw Error(`Invalid declaration generated at ${n}: ${s instanceof Error?s.message:String(s)}`)}}}async function km(e){let t=ot.resolve(e,"dist","index.js");if(!await Bun.file(t).exists())return;let r=Bun.spawnSync({cmd:[process.execPath,"-e",`try { await import(${JSON.stringify(t)}) } catch (error) { console.error(error); process.exit(1) }`],stdout:"ignore",stderr:"pipe",env:{...process.env,NODE_ENV:"test"}});if(r.exitCode===0)return;let n=new TextDecoder().decode(r.stderr??new Uint8Array),i=/SyntaxError|needs to refer to a top-level declared variable|does not provide an export named|Export named .* not found/i;if(i.test(n)){let s=n.split(`
|
|
254
|
-
`).find((o)=>i.test(o))??n.trim().split(`
|
|
255
|
-
`)[0];throw Error(`Built package at ${t} cannot be imported: ${s}
|
|
256
|
-
Fix the generated module at its source before publishing.`)}}async function LC(e){let r=Date.now()-e.startTime,n=e.pkgName??`@stacksjs/${ot.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 Bun.write(ot.resolve(e.dir,"dist","tsconfig.json"),`${JSON.stringify({compilerOptions:{paths:{}}},null,2)}
|
|
257
|
-
`),await Pm(e.dir),await km(e.dir);let i=await Jc([ot.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of i){let o=await Tm(s),a;if(o.size<1048576)a=`${(o.size/1024).toFixed(2)}kb`;else a=`${(o.size/1024/1024).toFixed(2)}mb`;let c=ot.relative(e.dir,s).replace("dist/","");console.log(`${Zs(Ys(`[${a}]`))} ${Ys("dist/")}${c}`)}console.log(`${Zs(Ys(`[${r}ms]`))} Built ${Yc(Zs(Om(n)))}`)}async function GC(e){let t=e.pkgName??`@stacksjs/${ot.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else Rm.info(`Building ${Yc(t)}...`);return{startTime:Date.now()}}async function BC(e){await Promise.resolve().then(() => Zc());let r=ot.resolve(e.dir,"src"),n=ot.resolve(e.dir,"dist"),i=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((o)=>!o.endsWith(".d.ts")).filter((o)=>!o.endsWith(".test.ts")&&!o.endsWith(".spec.ts")).filter((o)=>!o.split(/[\\/]/).some((a)=>a==="tests"||a==="__tests__"));await Bun.build({entrypoints:i.map((o)=>ot.resolve(r,o)),outdir:n,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??Dm(),plugins:[jc({root:r,outdir:n})]});let s=new Bun.Transpiler({loader:"ts",target:"bun",minifyWhitespace:!0,define:{"process.env.NODE_ENV":"process.env.NODE_ENV"}});for(let o of i){let a=s.transformSync(await Bun.file(ot.resolve(r,o)).text());a=Mm(a);let c=ot.resolve(n,o.replace(/\.ts$/,".js"));await xm(ot.dirname(c),{recursive:!0}),await Bun.write(c,a)}}function Mm(e){return e.replace(/(['"])(\.\.?\/[^'"]+?)(?<!\.d)\.tsx?\1/g,"$1$2.js$1")}function Dm(e=[]){let t=[];try{let r=af("fs"),n=JSON.parse(r.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(n.dependencies??{}),...Object.keys(n.peerDependencies??{}),...Object.keys(n.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,...t.map((r)=>`${r}/*`),"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{uf as buildWorkspacePackages,ln as dependencyLayers,Dm as frameworkExternal,GC as intro,LC as outro,Mm as rewriteRelativeTsSpecifiers,BC as transpilePackage,Pm as validateDeclarations,km as validateRuntimeExports,ff as workspaceBuildTargets};
|
|
238
|
+
`;i+=x[k]}let I=[a,c,f,u,h,l,y];for(let k=0;k<I.length;k++){let U=I[k];for(let H=0;H<U.length;H++){let O=U[H],z="",pe=O.kind;switch(pe){case"function":z=_m(O,r);break;case"variable":z=xc(O,r);break;case"interface":z=Vm(O,r);break;case"type":z=Um(O,r);break;case"class":z=Km(O,r);break;case"enum":z=Hm(O,r);break;case"module":case"namespace":z=zm(O,r);break;case"import":case"export":case"unknown":break;default:Oc(pe,`Unhandled declaration kind in processor: ${pe}`)}if(z){if(i)i+=`
|
|
239
|
+
`;i+=z}}}for(let k=0;k<v.length;k++){if(i)i+=`
|
|
240
|
+
`;i+=v[k]}for(let k=0;k<G.length;k++){if(i)i+=`
|
|
241
|
+
`;i+=G[k]}if(!i&&(s.length>0||C.length>0))return"export {};";return i}var Nm,Lm,Wm,jt,Qm,Rc=null,Pc,kc;var Dc=he(()=>{Go();Nm=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,Lm=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,Wm=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;jt=new Map;Qm=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,Pc=[],kc=[]});import{existsSync as Ic}from"fs";import{mkdir as Fc,readdir as ep,realpath as tp,rm as rp}from"fs/promises";import{availableParallelism as ip}from"os";import{basename as Jo,dirname as Yi,extname as np,isAbsolute as Fr,parse as op,relative as Be,resolve as et}from"path";function Bc(e){let t=Uo.get(e);if(!t)t=Ms(e),Uo.set(e,t),t.catch(()=>Uo.delete(e));return t}async function Nc(e,t,r,n,i,o=qi){let s=Jo(e)||"output.d.ts",a=Be(Yi(e),t),c=`${s}.map`,f=r.lastIndexOf(`
|
|
242
|
+
${Vo()}`),u=f===-1?r:r.slice(0,f),h=Sc(u,s,a,n),l=`${e}.map`;return await o(l,JSON.stringify(h)),Y.debug(` Generated source map: ${Be(i,l)}`),c}async function qo(e){let t=Date.now(),r={...gl,...e};if(r.logLevel)fn(r.logLevel);else if(r.verbose)fn("debug");let n=new zi;if(r.plugins&&r.plugins.length>0){for(let P of r.plugins)n.register(P),Y.debug(`Registered plugin: ${P.name}`);r=await n.runOnStart(r)}if(await ap(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await vc(r);let i=r.typeMappings?Ji(r.typeMappings):void 0,o=null,s={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;Y.debug("Starting DTS generation..."),Y.debug(`Using ${s.generationMode} declaration generation path`),Y.debug("Config:",r);let c=await hp(r);up(r,c);let f=c.slice(),u=await Bc(r),h=null;if(r.autoIncludeReExports!==!1&&f.length>0){h=await vn(f,{includeImports:!0,resolveSpecifier:u});let P=et(r.cwd,r.root),F=r.exclude||[],I=[];for(let k of h.reachable){if(f.includes(k))continue;if(!zo(k))continue;if(k.endsWith(".d.ts"))continue;if(k.includes("node_modules"))continue;let U=r.outputStructure==="flat"&&c.some((H)=>u.isPackageLocal?.(H,k));if(!Nr(k,P)&&!U){Y.warn(`Skipping auto-included source outside root: ${Be(r.cwd,k)}`);continue}if(Ho(k,F,P))continue;I.push(k)}if(I.length>0)f=[...f,...I],Y.debug(`Auto-included ${I.length} file(s) reached via relative re-exports`)}if(dp(f,r),Ko.set(r,new Set(f)),r.incremental){if(o=new xn(r,u.cacheKey?.(f)),r.clearCache){if(Y.debug("Clearing build cache..."),!r.dryRun)o.clear()}else if(o.load()){let P=o.getStats();Y.debug(`Loaded build cache with ${P.entries} entries`)}else Y.debug("No existing build cache found, starting fresh");if(!r.dryRun)Vs(r.cwd)}if(o&&!r.dryRun){let P=o.prune(new Set(f),r.cwd);if(P>0)Y.debug(`Pruned ${P} deleted files from cache`)}if(Y.debug(`Found ${f.length} TypeScript files`),r.progress&&f.length>0){let P=r.parallel?"parallel":"sequential";Y.info(`Processing ${f.length} files (${P})...`)}let l=new Map,y=new Map,C=async(P,F,I="lf")=>{y.set(P,{content:F,lineEnding:I})},S=async(P,F)=>{let I;try{let k=Lr(P,r),U=async(se)=>{if(!r.diff)return;try{let W=await Pt(k),K=Ec(W,se,Be(r.cwd,k));if(K)Y.info(`
|
|
243
|
+
${K}`);else Y.debug(`[no changes] ${k}`)}catch{Y.info(`[new file] ${Be(r.cwd,k)}`)}},H=(se)=>{if(!r.validate)return 0;let W=bc(se,k);if(W.isValid)return Y.debug(`[validation] ${k} - OK`),0;Y.warn(`[validation] ${Be(r.cwd,k)} has ${W.errors.length} error(s):`);for(let K of W.errors){let q=` Line ${K.line}:${K.column}`;if(K.code)q+=` [${K.code}]`;if(q+=` - ${K.message}`,Y.warn(q),K.suggestion)Y.warn(` Suggestion: ${K.suggestion}`)}return W.errors.length},O=(se)=>{Y.info(`[dry-run] Would generate: ${k}`),Y.debug("--- Content preview ---"),Y.debug(se.slice(0,500)+(se.length>500?`
|
|
244
|
+
...`:"")),Y.debug("--- End preview ---")};if(o){let se=o.getCachedIfValid(P,r.cwd);if(se){if(r.bundle)l.set(P,se);await U(se);let W=H(se);if(r.dryRun)O(se);else{if(r.declarationMap)I=F??await Pt(P),await Nc(k,P,se,I,r.cwd,C);await C(k,se,r.lineEnding)}return Y.debug(`[cached] ${Be(r.cwd,k)}`),{success:!0,file:P,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:W}}}I=F??await Pt(P);let{content:z,declarationCount:pe,importCount:Oe,exportCount:ie}=await gp(P,I,r,n,i);if(r.bundle)l.set(P,z);let ne=z;if(r.prettier||r.indentStyle||r.indentSize){let se=await tc(ne,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},k);ne=se.content;for(let W of se.warnings??[])Y.warn(`[format] ${W}`)}if(r.declarationMap){let se=`${Jo(k)||"output.d.ts"}.map`;ne=$c(ne,se)}await U(ne);let ue=H(ne);if(r.dryRun)O(ne);else{if(r.declarationMap&&I)await Nc(k,P,ne,I,r.cwd,C);if(await C(k,ne,r.lineEnding),o&&I)o.update(P,I,ne,r.cwd);Y.debug(`Generated: ${k}`)}return{success:!0,file:P,declarationCount:pe,importCount:Oe,exportCount:ie,validationErrorCount:ue}}catch(k){let U=Cl(k,P,I);if(r.plugins&&r.plugins.length>0)await n.runOnError(k instanceof Error?k:Error(String(k)),P,I||"");return{success:!1,file:P,declarationCount:0,importCount:0,exportCount:0,dtsError:U,validationErrorCount:0}}},x=r.parallel||r.parallel!==!1&&f.length>=10,v=Ks(r.concurrency,ip?.()??8),G=new Map;if(x&&f.length>1){let P=f.map(async(F)=>{try{let I=await Pt(F);return{file:F,source:I}}catch{return{file:F,source:null}}});for(let F of await Promise.all(P))if(F.source!==null)G.set(F.file,F.source)}let L=(P)=>{if(s.filesProcessed++,P.success){if(P.cached)a++;else s.filesGenerated++,s.declarationsFound+=P.declarationCount,s.importsProcessed+=P.importCount,s.exportsProcessed+=P.exportCount;if(r.validate){if(s.filesValidated++,P.validationErrorCount)s.validationErrors+=P.validationErrorCount}}else if(s.filesFailed++,P.dtsError){s.errors.push(P.dtsError);let F=wl(P.dtsError);if(r.continueOnError)Y.warn(F);else throw Y.error(F),Error(P.dtsError.message)}};if(x)for(let P=0;P<f.length;P+=v){let F=f.slice(P,P+v),I=await Promise.all(F.map((k)=>S(k,G.get(k))));for(let k of I)L(k);if(r.progress){let k=Math.round(s.filesProcessed/f.length*100);Y.info(`[${s.filesProcessed}/${f.length}] ${k}%`)}}else for(let P of f){let F=await S(P);if(L(F),r.progress){let I=Math.round(s.filesProcessed/f.length*100),k=F.cached?"[cached]":"";Y.info(`[${s.filesProcessed}/${f.length}] ${I}% - ${Be(r.cwd,P)} ${k}`)}}if(!r.dryRun){if(r.clean)await cp(r);for(let[P,F]of y)await Fc(Yi(P),{recursive:!0}),await qi(P,F.content,F.lineEnding)}if(o&&!r.dryRun)o.save(),Y.debug("Saved build cache");if(!r.bundle){let P=[];if(h)for(let F of h.unresolved)P.push({from:F.from,specifier:F.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&f.length>0){let F=new Set(f);for(let I of f){let k;try{k=await Pt(I)}catch{continue}for(let U of Jr(k)){let H=u(U.specifier,I);if(!H.isRelative)continue;if(!H.resolved)P.push({from:I,specifier:U.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(H.resolved)&&!F.has(H.resolved))P.push({from:I,specifier:U.specifier,reason:"not-emitted"})}}}if(P.length>0){let F=[];F.push(`Found ${P.length} re-export(s) pointing at siblings that won't be in the output:`);for(let k of P){let U=Be(r.cwd,k.from);if(k.reason==="missing")F.push(` ${U} \u2192 '${k.specifier}' (path not found on disk)`);else F.push(` ${U} \u2192 '${k.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let I=F.join(`
|
|
245
|
+
`);if(r.failOnUnresolvedReExport)throw Error(I);Y.warn(I),Y.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(r.bundle&&(s.filesGenerated>0||a>0)&&c.length>0)try{Y.debug("Bundling declarations...");let P=c.length===1&&!!r.bundleOutput;for(let F of c){let I=await vn([F],{includeImports:!0,resolveSpecifier:u}),k=new Set;for(let z of I.reachable){if(z.endsWith(".d.ts"))continue;if(z.includes("node_modules"))continue;k.add(z)}let U=f.filter((z)=>k.has(z));if(!U.includes(F))U.push(F);let H=Ls(F,U,l,{cwd:r.cwd,keepComments:r.keepComments});for(let z of new Set(H.warnings))Y.warn(`[bundle] ${z}`);let O=P?et(r.cwd,r.outdir,r.bundleOutput):Lr(F,r);if(r.dryRun)Y.info(`[dry-run] Would bundle ${H.files.length} files to: ${Be(r.cwd,O)}`);else await Fc(Yi(O),{recursive:!0}),await qi(O,H.content,r.lineEnding),Y.info(`Bundled ${H.files.length} files to: ${Be(r.cwd,O)}`);if(P)break}}catch(P){let F=P instanceof Error?P.message:String(P);Y.error(`Bundle failed: ${F}`)}if(s.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(s,null,2));else{if(Y.info(`
|
|
246
|
+
--- Generation Statistics ---`),Y.info(`Files processed: ${s.filesProcessed}`),Y.info(`Files generated: ${s.filesGenerated}`),a>0)Y.info(`Files cached: ${a}`);if(s.filesFailed>0)Y.info(`Files failed: ${s.filesFailed}`);if(Y.info(`Declarations found: ${s.declarationsFound}`),Y.info(`Imports processed: ${s.importsProcessed}`),Y.info(`Exports processed: ${s.exportsProcessed}`),s.filesValidated>0){if(Y.info(`Files validated: ${s.filesValidated}`),s.validationErrors>0)Y.info(`Validation errors: ${s.validationErrors}`)}if(Y.info(`Duration: ${s.durationMs}ms`),s.errors.length>0){Y.info(`
|
|
247
|
+
Errors:`);for(let P of s.errors){let F=` - ${P.file}`;if(P.location)F+=`:${P.location.line}:${P.location.column}`;if(P.code)F+=` [${P.code}]`;if(F+=`: ${P.message}`,Y.info(F),P.suggestion)Y.info(` Suggestion: ${P.suggestion}`)}}Y.info(`-----------------------------
|
|
248
|
+
`)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(s);return Y.debug("DTS generation complete!"),s}async function Lc(e){try{return await tp(e)}catch{return et(e)}}async function ap(e){let t=et(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(Fr(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=et(t,e.bundleOutput);if(!Nr(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===op(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([Lc(t),Lc(et(e.cwd,e.root))]);if(Nr(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function lp(e){let t=Ir.get(e);if(!t){if(t=new Wc(e),Ir.set(e,t),Ir.size>sp){let r=Ir.keys().next().value;if(r!==void 0)Ir.delete(r)}}return t}async function cp(e){let t=et(e.cwd,e.outdir);async function r(n){let i;try{i=await ep(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(o)=>{let s=et(n,o.name);if(o.isDirectory()){await r(s);return}if(o.name.endsWith(".d.ts")||o.name.endsWith(".d.mts")||o.name.endsWith(".d.cts")||o.name.endsWith(".d.ts.map")||o.name.endsWith(".d.mts.map")||o.name.endsWith(".d.cts.map"))await rp(s,{force:!0})}))}await r(t)}function Ho(e,t,r){if(!t||t.length===0)return!1;let n=Be(r,e);for(let i of t){let o=lp(i);if(o.match(n)||o.match(e))return!0}return!1}function up(e,t){let r=et(e.cwd,e.root),n=` root: ${r}
|
|
249
|
+
entrypoints: ${e.entrypoints.map((o)=>JSON.stringify(o)).join(", ")||"(none)"}
|
|
250
|
+
`+(e.exclude?.length?` exclude: ${e.exclude.map((o)=>JSON.stringify(o)).join(", ")}
|
|
251
|
+
`:"")+"Entrypoints are resolved relative to --root. Pass several by repeating --entrypoints or separating them with commas.";if(t.length===0){if(e.entrypoints.filter((o)=>Fr(o)&&Ic(o)&&!Nr(o,r)).length===e.entrypoints.length)return;throw Error(`No source files matched. Nothing was generated.
|
|
252
|
+
${n}`)}let i=e.entrypoints.filter((o)=>{if(fp.test(o))return!1;return!Ic(Fr(o)?o:et(r,o))});if(i.length>0)throw Error(`Entrypoint${i.length>1?"s":""} not found: ${i.map((o)=>JSON.stringify(o)).join(", ")}
|
|
253
|
+
${n}`)}async function hp(e){let t=[],r=et(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let o of i)if(Fr(o)&&zo(o)){if(!o.includes("node_modules")){if(!Nr(o,r)&&e.outputStructure!=="flat")Y.warn(`Skipping entrypoint outside root: ${Be(e.cwd,o)}`);else if(!Ho(o,n,r))t.push(o)}}else{let s=new Wc(o);for await(let a of s.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(zo(a)&&!a.includes("node_modules")){if(!Ho(a,n,r))t.push(a)}}return[...new Set(t.map((o)=>et(o)))].sort()}function Nr(e,t){let r=Be(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Fr(r)}function dp(e,t){let r=new Map;for(let n of e){let i=Lr(n,t),o=r.get(i);if(o&&o!==n)throw Error(`Output path collision: ${Be(t.cwd,o)} and ${Be(t.cwd,n)} both emit ${Be(t.cwd,i)}`);r.set(i,n)}}function zo(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function Lr(e,t){let r=et(t.cwd,t.root),n=Be(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(i)=>{if(i===".mts"||i===".mjs")return".d.mts";if(i===".cts"||i===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return et(t.cwd,t.outdir,n);else{let i=Jo(n);return et(t.cwd,t.outdir,i)}}function mp(e,t,r=""){let n=Be(Yi(e),t).replace(/\\/g,"/");if(n=n.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)n+=r;if(!n.startsWith("."))n=`./${n}`;return n}async function pp(e,t,r){let n=await Bc(r),i=Lr(t,r);return Is(e,(o)=>{let s=n(o,t);if(!s.isRelative||!s.resolved)return o;if(/\.d\.(?:ts|mts|cts)$/.test(s.resolved))return o;if(s.isAlias&&Ko.has(r)&&!Ko.get(r).has(s.resolved))throw Error(`Local alias ${JSON.stringify(o)} from ${t} targets a declaration excluded from this package build: ${s.resolved}`);let a=s.isAlias?s.suffix??"":o.match(/[?#].*$/)?.[0]??"",c=a?o.slice(0,-a.length):o,f=np(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return mp(i,Lr(s.resolved,r),u)+a})}async function gp(e,t,r,n,i){let o=t;if(n)o=await n.runOnBeforeFile(e,t);let s=Ql(o,e,r.keepComments,r.isolatedDeclarations??!1);if(n)s=await n.runOnDeclarations(e,o,s);let a=0,c=0;for(let u=0;u<s.length;u++){let h=s[u];if(h.kind==="import")a++;if(h.kind==="export"||h.isExported)c++}let f=Mc(s,{filePath:e,sourceCode:o,declarations:s},r.keepComments,r.importOrder);if(f=await pp(f,e,r),i)f=fc(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=sc(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)f=await n.runOnAfterFile(e,o,f);return{content:f,declarationCount:s.length,importCount:a,exportCount:c}}var Wc,Uo,Ko,sp=50,Ir,fp;var Gc=he(()=>{Ur();un();bn();Ws();Us();Hs();yl();vl();ec();rc();ic();ac();uc();Ac();Dc();({Glob:Wc}=globalThis.Bun),Uo=new WeakMap,Ko=new WeakMap;Ir=new Map;fp=/[*?[\]{}!]/});var jc=he(()=>{Gc()});import{createHash as Cp}from"crypto";import{existsSync as wp,readFileSync as vp,writeFileSync as bp}from"fs";import{dirname as Ep,join as Sp,relative as _c,resolve as Wr,sep as Zi}from"path";import Uc from"process";class Kc{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},n=this.listeners.get(e)||[];for(let i of n)await i(r)}}class Hc{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=Sp(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(wp(this.manifestPath)){let t=JSON.parse(vp(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}=yp("fs");e(this.cacheDir,{recursive:!0}),bp(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 $p(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return Cp("md5").update(JSON.stringify(t)).digest("hex")}function zc(e={}){let{onSuccess:t,onError:r,failOnError:n=!0,incremental:i=!1,cacheDir:o=".dtsx-cache",on:s,timeout:a=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,h=new Kc;if(s){for(let[l,y]of Object.entries(s))if(y)h.on(l,y)}return{name:"bun-plugin-dtsx",async setup(l){let y=Date.now(),C=null,S=0;try{let x=Tp(u,l),v=$p(x);if(x.clean){let F=Wr(x.cwd??Uc.cwd(),x.outdir??"./dist");if(Vc.has(F))x.clean=!1;else Vc.add(F)}if(i)C=new Hc(Wr(o),v);if(await h.emit("start",{type:"start",files:x.entrypoints||[],config:x}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),i)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let L=await(async()=>new Promise((F,I)=>{let k=setTimeout(()=>{I(new Br(`Generation timed out after ${a}ms`,"TIMEOUT_ERROR",{timeout:a}))},a);qo(x).then((U)=>{clearTimeout(k),F(U)}).catch((U)=>{clearTimeout(k),I(U)})}))(),P=Date.now()-y;if(C)C.save();if(await h.emit("complete",{type:"complete",stats:L,duration:P,fromCache:S}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${P}ms`),S>0)console.log(`[bun-plugin-dtsx] ${S} files served from cache`)}if(t)await t(L)}catch(x){let v=Ap(x);if(await h.emit("error",{type:"error",error:v}),r)await r(v);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${v.code}`),console.error(` Message: ${v.message}`),v.context)console.error(` Context: ${JSON.stringify(v.context)}`);if(f&&v.stack)console.error(` Stack: ${v.stack}`)}if(n&&!c)throw v}}}}function Ap(e){if(e instanceof Br)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 Br(e.message,t,{originalError:e.name},e)}return new Br(String(e),"GENERATION_ERROR")}function xp(e){let t=e.map((n)=>Ep(n).split(Zi)),r=t[0];for(let n of t.slice(1)){let i=0;while(i<r.length&&i<n.length&&r[i]===n[i])i++;r=r.slice(0,i)}return r.join(Zi)||Zi}function Tp(e,t){let r=e.cwd||Uc.cwd(),n=t?.config?.entrypoints,i=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",o=e.root||e.build?.config.root||t?.config.root;if(!o&&n?.length){let a=xp(n.map((c)=>Wr(r,c)));o=_c(r,a)||"."}o=o||"./src";let s=e.entrypoints;if(!s)if(n?.length){let a=Wr(r,o),c=[];for(let f of n){let u=Wr(r,f);if(u===a||u.startsWith(a+Zi))c.push(_c(a,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${o}": ${f}`)}s=c.length?c:["index.ts"]}else s=["index.ts"];return{...e,cwd:r,root:o,entrypoints:s,outdir:i,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}var yp,Br,Vc;var Jc=he(()=>{jc();yp=import.meta.require;Br=class Br extends Error{code;context;cause;constructor(e,t,r,n){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=r,this.cause=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};Vc=new Set});import{mkdir as Op,stat as Rp}from"fs/promises";import{bold as Yo,dim as Zo,green as Pp,italic as qc,log as kp}from"@stacksjs/cli";import{path as ot}from"@stacksjs/path";import{glob as Yc}from"@stacksjs/storage";function ln(e){let t=new Map;for(let s of e){if(t.has(s.name))throw Error(`duplicate package name: ${s.name}`);t.set(s.name,s)}let r=new Map,n=new Set,i=(s,a)=>{let c=r.get(s);if(c!==void 0)return c;if(n.has(s))throw Error(`dependency cycle: ${[...a,s].join(" -> ")}`);n.add(s);let f=t.get(s).dependencies.filter((h)=>h!==s&&t.has(h)),u=f.length?1+Math.max(...f.map((h)=>i(h,[...a,s]))):0;return n.delete(s),r.set(s,u),u},o=[];for(let s of[...e].sort((a,c)=>a.name.localeCompare(c.name)))(o[i(s.name,[])]||=[]).push(s);return o.filter(Boolean)}import{existsSync as cf,readdirSync as ff,readFileSync as hs}from"fs";import{join as cn}from"path";function uf(e){return[...ff(e,{withFileTypes:!0}).filter((r)=>r.isDirectory()).map((r)=>cn(e,r.name)),e].filter((r)=>{let n=cn(r,"package.json");if(!cf(n))return!1;let i=JSON.parse(hs(n,"utf8"));return!i.private&&!!i.scripts?.build})}async function hf(e){let t=e.map((i)=>{let o=JSON.parse(hs(cn(i,"package.json"),"utf8"));if(!o.name||!o.scripts?.build)throw Error(`Not a buildable workspace package: ${i}`);return{name:o.name,dir:i,dependencies:Object.keys(o.dependencies??{})}}),r=ln(t),n=[];for(let{name:i,dir:o,dependencies:s}of r.flat()){let a=n.filter((f)=>f.exitCode!==0&&s.includes(f.name)).map((f)=>f.name);if(a.length){console.error(`Cannot build ${o}: dependencies failed: ${a.join(", ")}`),n.push({name:i,dir:o,exitCode:null,blockedBy:a});continue}console.log(`Building ${o}`);let c=Bun.spawn([process.execPath,"run","build"],{cwd:o,stdout:"inherit",stderr:"inherit"});n.push({name:i,dir:o,exitCode:await c.exited,blockedBy:[]})}return n}async function Mp(e){let t=await Yc([ot.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let n of t){let i=await Bun.file(n).text();try{r.transformSync(i)}catch(o){throw Error(`Invalid declaration generated at ${n}: ${o instanceof Error?o.message:String(o)}`)}}}async function Dp(e){let t=ot.resolve(e,"dist","index.js");if(!await Bun.file(t).exists())return;let r=Bun.spawnSync({cmd:[process.execPath,"-e",`try { await import(${JSON.stringify(t)}) } catch (error) { console.error(error); process.exit(1) }`],stdout:"ignore",stderr:"pipe",env:{...process.env,NODE_ENV:"test"}});if(r.exitCode===0)return;let n=new TextDecoder().decode(r.stderr??new Uint8Array),i=/SyntaxError|needs to refer to a top-level declared variable|does not provide an export named|Export named .* not found/i;if(i.test(n)){let o=n.split(`
|
|
254
|
+
`).find((s)=>i.test(s))??n.trim().split(`
|
|
255
|
+
`)[0];throw Error(`Built package at ${t} cannot be imported: ${o}
|
|
256
|
+
Fix the generated module at its source before publishing.`)}}async function GC(e){let r=Date.now()-e.startTime,n=e.pkgName??`@stacksjs/${ot.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 o=e.result.logs?.[0]||"Unknown build error";throw console.log(o),Error(`Build failed: ${o}`)}await Bun.write(ot.resolve(e.dir,"dist","tsconfig.json"),`${JSON.stringify({compilerOptions:{paths:{}}},null,2)}
|
|
257
|
+
`),await Mp(e.dir),await Dp(e.dir);let i=await Yc([ot.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let o of i){let s=await Rp(o),a;if(s.size<1048576)a=`${(s.size/1024).toFixed(2)}kb`;else a=`${(s.size/1024/1024).toFixed(2)}mb`;let c=ot.relative(e.dir,o).replace("dist/","");console.log(`${Yo(Zo(`[${a}]`))} ${Zo("dist/")}${c}`)}console.log(`${Yo(Zo(`[${r}ms]`))} Built ${qc(Yo(Pp(n)))}`)}async function jC(e){let t=e.pkgName??`@stacksjs/${ot.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else kp.info(`Building ${qc(t)}...`);return{startTime:Date.now()}}async function _C(e){await Promise.resolve().then(() => Jc());let r=ot.resolve(e.dir,"src"),n=ot.resolve(e.dir,"dist"),i=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((s)=>!s.endsWith(".d.ts")).filter((s)=>!s.endsWith(".test.ts")&&!s.endsWith(".spec.ts")).filter((s)=>!s.split(/[\\/]/).some((a)=>a==="tests"||a==="__tests__"));await Bun.build({entrypoints:i.map((s)=>ot.resolve(r,s)),outdir:n,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??Fp(),plugins:[zc({root:r,outdir:n})]});let o=new Bun.Transpiler({loader:"ts",target:"bun",minifyWhitespace:!0,define:{"process.env.NODE_ENV":"process.env.NODE_ENV"}});for(let s of i){let a=o.transformSync(await Bun.file(ot.resolve(r,s)).text());a=Ip(a);let c=ot.resolve(n,s.replace(/\.ts$/,".js"));await Op(ot.dirname(c),{recursive:!0}),await Bun.write(c,a)}}function Ip(e){return e.replace(/(['"])(\.\.?\/[^'"]+?)(?<!\.d)\.tsx?\1/g,"$1$2.js$1")}function Fp(e=[]){let t=[];try{let r=lf("fs"),n=JSON.parse(r.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(n.dependencies??{}),...Object.keys(n.peerDependencies??{}),...Object.keys(n.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,...t.map((r)=>`${r}/*`),"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{hf as buildWorkspacePackages,ln as dependencyLayers,Fp as frameworkExternal,jC as intro,GC as outro,Ip as rewriteRelativeTsSpecifiers,_C as transpilePackage,Mp as validateDeclarations,Dp as validateRuntimeExports,uf as workspaceBuildTargets};
|