@stacksjs/build 0.75.457 → 0.75.459
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 +171 -172
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,80 +1,80 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`,r)+1,i=
|
|
4
|
-
`,f+2);f=
|
|
5
|
-
`;r++}r=Math.min(r+2,e.length);continue}if(i===44){let s=r+1;while(s<e.length){while(s<e.length&&e.charCodeAt(s)<=32)s++;if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10&&e.charCodeAt(s)!==13)s++;continue}if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===42){s+=2;while(s+1<e.length&&!(e.charCodeAt(s)===42&&e.charCodeAt(s+1)===47))s++;s=Math.min(s+2,e.length);continue}break}let o=e.charCodeAt(s);if(o===93||o===125){r++;continue}}t+=e[r++]}return t}var
|
|
6
|
-
`||u==="\r"?u:" ":u;continue}if(c===o)break}t.push({start:
|
|
7
|
-
`||e[i]==="\r"?e[i]:" ",i++;if(i<r)n+=" ",i+=2;continue}if(
|
|
8
|
-
`,
|
|
9
|
-
`){if(e[
|
|
10
|
-
`){let
|
|
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 s=i.text.replace(/;\s*$/,"").trim(),o=s.match(/^import\s+(type\s+)?([\s\S]+?)\s+from\s+(['"])([^'"]+)\3/);if(o){let c=
|
|
13
|
-
`;while(n<i){let o=e[n];if(o==="/"&&e[n+1]==="*"){let
|
|
14
|
-
`,n),c=
|
|
15
|
-
`){if(e[
|
|
16
|
-
`||!/\s/.test(o))s=o;n++}return r}function
|
|
17
|
-
export { ${
|
|
18
|
-
}`),z}let
|
|
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 af=import.meta.require;import{readFile as hf,stat as _m,writeFile as df}from"fs/promises";async function fo(e,t){if(_r)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await df(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function kt(e){if(_r)return globalThis.Bun.file(e).text();return hf(e,"utf-8")}var _r,Um;var Ur=he(()=>{_r=typeof globalThis.Bun<"u",Um=!_r&&typeof process<"u"&&!!process.versions?.node});function Zt(e){return uo[e]>=uo[Vr]}function gf(){if(!mf)return"";return`[${new Date().toISOString().slice(11,23)}] `}function yf(e,t){let r=gf();if(e||r)return[`${r}${e}`,...t];return t}function Yt(e,t,r){let n=yf(t,r);if(ho){ho(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 po(e){return{debug:(...t)=>{if(Zt("debug"))Yt("debug",e,t)},info:(...t)=>{if(Zt("info"))Yt("info",e,t)},warn:(...t)=>{if(Zt("warn"))Yt("warn",e,t)},error:(...t)=>{if(Zt("error"))Yt("error",e,t)},setLevel:(t)=>{Vr=t},getLevel:()=>Vr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return po(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(Zt("debug"))Yt("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Zt("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Yt("info",e,[t])}}}function fn(e){Vr=e}var uo,Vr="info",pf="[dtsx]",mf=!1,ho=null,q;var un=he(()=>{uo={debug:0,info:1,warn:2,error:3,silent:4};q=po(pf)});function Ct(e){return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36||e>127}function Ke(e){return Ct(e)||e>=48&&e<=57}function mo(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 s=e.lastIndexOf("/*",r-2);if(s===-1)return-1;r=s-1;continue}let n=e.lastIndexOf(`
|
|
3
|
+
`,r)+1,i=Cf(e,n,r);if(i!==-1){r=i-1;continue}return r}}function Cf(e,t,r){let n=0;for(let i=t;i<=r;i++){let s=e.charCodeAt(i);if(n){if(s===92){i++;continue}if(s===n)n=0;continue}if(s===39||s===34||s===96){n=s;continue}if(s===47&&i+1<=r&&e.charCodeAt(i+1)===47)return i}return-1}function go(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 yo(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 wf(e,t){let r=[],n=[],i=0,s=!1,o="",a="",c=!0,f=0,u=(h,l=!1)=>{a=o,o=h,c=l};while(f<=t){let h=e.charCodeAt(f);if(s){if(h===92){f+=2;continue}if(h===96)s=!1,u("literal");else if(h===36&&e.charCodeAt(f+1)===123)n.push(i++),s=!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){s=!0,f++;continue}if(Ct(h)||h===35&&Ct(e.charCodeAt(f+1))){let l=f++;while(Ke(e.charCodeAt(f)))f++;let y=e.slice(l,f);u(y,o!=="."&&yo(y));continue}if(h===40){let l=a!=="."&&(o==="if"||o==="while"||o==="for"||o==="with"||o==="switch"||o==="catch"||o==="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(),s=!0}u(e[f],h===47||go(h))}f++}return!1}function Hr(e,t){let r=mo(e,t-1);if(r<0)return!0;let n=e.charCodeAt(r);if(n===41)return wf(e,r);if(go(n))return!0;if(Ke(n)){let i=r;while(i>=0&&Ke(e.charCodeAt(i)))i--;let s=e.charCodeAt(mo(e,i));if(s===46||s===35)return!1;return yo(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 s=e.charCodeAt(r);if(s===92){r+=2;continue}if(i){if(s===93)i=!1;r++;continue}if(s===91){i=!0,r++;continue}if(s===47){r++;break}if(s===10||s===13)break;r++}while(r<n&&Ke(e.charCodeAt(r)))r++;return r}var hn=()=>{};function Co(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 s=r+1;while(s<e.length){while(s<e.length&&e.charCodeAt(s)<=32)s++;if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10&&e.charCodeAt(s)!==13)s++;continue}if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===42){s+=2;while(s+1<e.length&&!(e.charCodeAt(s)===42&&e.charCodeAt(s+1)===47))s++;s=Math.min(s+2,e.length);continue}break}let o=e.charCodeAt(s);if(o===93||o===125){r++;continue}}t+=e[r++]}return t}var wo=()=>{};import{readFileSync as $f,statSync as vf}from"fs";import{readFile as bf}from"fs/promises";import{createRequire as Ef}from"module";import{dirname as yr,isAbsolute as Sf,join as dn,resolve as pn}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(vf(r).isFile())return r}catch{}return null}function Af(e,t){if(Sf(e)||e.startsWith("."))return Jt(pn(yr(t),e));let r=Ef(t),n=e.startsWith("@")?/^@[^/]+\/[^/]+/.exec(e)?.[0]:e.split("/")[0];if(n)for(let i of r.resolve.paths(n)??[]){let s=Jt(dn(i,n,"package.json"));if(!s)continue;let o=JSON.parse($f(s,"utf8"));if(e===n){if(o.tsconfig!==void 0){if(typeof o.tsconfig!=="string")throw Error(`Invalid tsconfig field in ${s}`);let c=Jt(pn(yr(s),o.tsconfig));if(!c)throw Error(`Cannot resolve tsconfig ${JSON.stringify(o.tsconfig)} from ${s}`);return c}let a=Jt(dn(yr(s),"tsconfig.json"));if(a)return a}break}for(let i of[`${e}/tsconfig.json`,e])try{let s=r.resolve(i),o=s.endsWith(".json")?Jt(s):null;if(o)return o}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),s=JSON.parse(Co(await bf(n,"utf8"))),o=typeof s.extends==="string"?[s.extends]:s.extends??[];if(!Array.isArray(o)||o.some((f)=>typeof f!=="string"))throw Error(`Invalid tsconfig extends in ${n}`);let a={};for(let f of o){let u=Af(f,n);if(!u)throw Error(`Cannot resolve tsconfig extends ${JSON.stringify(f)} from ${n}`);a={...a,...await Cr(u,t,i)}}let c=s.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=pn(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 mn=he(()=>{wo()});import{existsSync as yn,readFileSync as $o,realpathSync as wr,statSync as xf}from"fs";import{builtinModules as Tf}from"module";import{dirname as Cn,extname as Of,isAbsolute as wn,join as xo,relative as To,resolve as qt}from"path";function Kr(e){try{return xf(e).isFile()}catch{return!1}}function zt(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(Kr(i))return{resolved:i,isRelative:!0};let s=Of(i),o=Rf[s];if(o){let a=i.slice(0,-s.length);for(let c of o){let f=a+c;if(Kr(f))return{resolved:f,isRelative:!0}}}for(let a of vo){let c=i+a;if(Kr(c))return{resolved:c,isRelative:!0}}if(yn(i))for(let a of vo){let c=xo(i,`index${a}`);if(Kr(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function Oo(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 Ro(e,t){if(Object.hasOwn(e,t))return e[t]!==null;let r=Object.keys(e).filter((n)=>n.includes("*")&&Oo(n,t)).sort((n,i)=>i.indexOf("*")-n.indexOf("*")||i.length-n.length)[0];return r!==void 0&&e[r]!==null}function bo(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 Ro(n,r)}function gn(e,t){let r=To(e,t);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!wn(r)}async function Po(e){let t=await Cr(qt(e.cwd,e.tsconfigPath||"tsconfig.json")),r=Object.entries(t?.paths??{});if(r.length===0)return zt;let n=t?.baseUrl??t?.pathsBasePath??e.cwd,i=qt(e.cwd,e.root),s=new Map,o=new Set([...Tf,"bun"]),a=(f)=>{let u=Cn(f),h=[];while(!0){if(s.has(u)){let C=s.get(u);for(let S of h)s.set(S,C);return C}h.push(u);let l=xo(u,"package.json");if(yn(l)){let C={...JSON.parse($o(l,"utf8")),directory:wr(u)};for(let S of h)s.set(S,C);return C}let y=Cn(u);if(y===u)return;u=y}},c=(f,u)=>{if(f.startsWith(".")||wn(f))return zt(f,u);if(f.startsWith("node:")||f.startsWith("bun:")||o.has(f))return{resolved:null,isRelative:!1};let h=a(u),l=f.startsWith("@")?/^@[^/]+\/[^/]+/.exec(f)?.[0]:f.split("/")[0];if(h&&(bo(h,f)||Ro(h.imports??{},f)||l&&[h.dependencies,h.devDependencies,h.peerDependencies,h.optionalDependencies].some((B)=>Object.hasOwn(B??{},l))))return{resolved:null,isRelative:!1};let y=r.filter(([B])=>Oo(B,f)).sort(([B],[W])=>{if(!B.includes("*"))return-1;if(!W.includes("*"))return 1;return W.indexOf("*")-B.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 B of S){let W=qt(n,B.replace("*",v)),P=a(W);if(P&&bo(P,f)&&!P.private&&P.directory!==h?.directory)return{resolved:null,isRelative:!1};let F=zt(W,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 q.debug(`Resolved local declaration alias ${f} from ${u} to ${I}`),{resolved:e.outputStructure==="flat"?F.resolved:qt(i,To(wr(i),I)),isRelative:!0,isAlias:!0,suffix:W.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($o(l,"utf8"),{includeImports:!0}).map((y)=>({specifier:y.specifier,resolution:c(y.specifier,l)}))})),h=[...new Set(s.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 ko(e,t=[]){let r=e.length,n="",i=0;while(i<r){let s=e.charCodeAt(i);if(s===34||s===39||s===96){let o=s,a=i;n+=e[i++];while(i<r){let c=e.charCodeAt(i),f=e[i++];if(n+=o===96&&c!==o?c===10||c===13?f:" ":f,c===92&&i<r){let u=e[i++];n+=o===96?u===`
|
|
6
|
+
`||u==="\r"?u:" ":u;continue}if(c===o)break}t.push({start:a,end:i});continue}if(s===47&&i+1<r){let o=e.charCodeAt(i+1);if(o===47){n+=" ",i+=2;while(i<r&&e.charCodeAt(i)!==10)n+=" ",i++;continue}if(o===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=ko(e,n),s=(a)=>n.some((c)=>a>c.start&&a<c.end);Eo.lastIndex=0;let o;while((o=Eo.exec(i))!==null){if(s(o.index))continue;let a=!!o[1],c=o[3],f=o[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){Ao.lastIndex=0;while((o=Ao.exec(i))!==null){if(s(o.index))continue;r.push({specifier:o[3],kind:"import",isTypeOnly:!!o[1]})}}if(t.includeImports){So.lastIndex=0;while((o=So.exec(i))!==null)if(!s(o.index))r.push({specifier:o[2],kind:"import",isTypeOnly:!1})}return r}function Mo(e,t){let r=[],n=ko(e,r),i=/\b(?:from\s*|import\s*(?:\(\s*)?)(['"])([^'"]+)\1/g,s=[],o;while((o=i.exec(n))!==null){if(r.some((u)=>o.index>u.start&&o.index<u.end))continue;let c=o.index+o[0].lastIndexOf(`${o[1]}${o[2]}${o[1]}`)+1,f=t(o[2]);if(f!==o[2])s.push({start:c,end:c+o[2].length,value:f})}let a=e;for(let c of s.reverse())a=a.slice(0,c.start)+c.value+a.slice(c.end);return a}async function $n(e,t={}){let r=new Set,n=new Map,i=[],s=[];for(let o of e){let a=qt(o);if(!r.has(a))r.add(a),s.push(a)}while(s.length>0){let o=s.shift(),a;try{a=await kt(o)}catch{continue}let c=jr(a,t);n.set(o,c);for(let f of c){let u=(t.resolveSpecifier??zt)(f.specifier,o);if(!u.isRelative)continue;if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),s.push(u.resolved)}else i.push({from:o,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:r,reExports:n,unresolved:i}}var vo,Rf,Eo,So,Ao;var vn=he(()=>{Ur();un();hn();mn();vo=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],Rf={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};Eo=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,So=/\bimport\s*\(\s*(['"])([^'"]+)\1/g,Ao=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";]+?\s+from\s+)?(['"])([^'"]+)\2/g});import{relative as Lt}from"path";function Pf(e){let t=[],r=[],n=0,i=0,s=[],o=!1,a=0,c=e.length,f=(u)=>{let h=e.slice(n,u).trim();if(n=u,!h)return;if(kf(h)){r.push(h);return}t.push({text:h,comments:r}),r=[]};while(a<c){let u=e[a];if(o){if(u==="\\"){a+=2;continue}if(u==="`"){o=!1,a++;continue}if(u==="$"&&e[a+1]==="{"){s.push(i),i++,o=!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
|
+
`,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==="`"){o=!0,a++;continue}if(u==="("||u==="["||u==="{"){i++,a++;continue}if(u===")"||u==="]"||u==="}"){if(i--,s.length>0&&u==="}"&&i===s[s.length-1])s.pop(),o=!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 kf(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 bn(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 Mf(e){let t={named:[]},r=e.trim().replace(/^type\s+/,""),n=r.match(/\{([\s\S]*)\}/);if(n){for(let o of bn(n[1]))t.named.push({imported:o.local,local:o.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 s=r.replace(/,/g,"").trim();if(s&&Io.test(s))t.defaultName=s;return t}function If(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,s)=>`${s.trimEnd()} ${t}`);if(/^(?:interface|type)\b/.test(r)||/^declare\b/.test(r))return r;return`declare ${r}`}function Ff(e,t){let r={file:e,declarations:[],declared:new Set,imports:new Map,localExports:new Map,namedReExports:[],starReExports:[],namespaceReExports:[],verbatim:[],directives:[]},n=Pf(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 s=i.text.replace(/;\s*$/,"").trim(),o=s.match(/^import\s+(type\s+)?([\s\S]+?)\s+from\s+(['"])([^'"]+)\3/);if(o){let c=Mf(o[2]),f=o[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(s)){r.verbatim.push(i);continue}if(o=s.match(/^export\s+(?:type\s+)?\*\s+as\s+([\w$]+)\s+from\s+(['"])([^'"]+)\2/),o){r.namespaceReExports.push({specifier:o[3],exported:o[1]});continue}if(o=s.match(/^export\s+(?:type\s+)?\*\s+from\s+(['"])([^'"]+)\1/),o){r.starReExports.push(o[2]);continue}if(o=s.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}\s+from\s+(['"])([^'"]+)\2/),o){for(let c of bn(o[1]))r.namedReExports.push({specifier:o[3],imported:c.local,exported:c.exported});continue}if(o=s.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}$/),o){for(let c of bn(o[1]))r.localExports.set(c.exported,c.local);continue}if(o=s.match(/^export\s+default\s+([\w$]+)$/),o&&Io.test(o[1])){r.localExports.set("default",o[1]);continue}if(/^export\s+as\s+namespace\b/.test(s)||/^(?:export\s+)?declare\s+(?:global\b|module\s+['"])/.test(s)){r.verbatim.push(i);continue}let a=s.match(Df);if(a){let c=!!a[1],f=a[4]??(c?"_default":null);if(f){if(r.declared.add(f),/^export\s/.test(s))r.localExports.set(c?"default":f,f);r.declarations.push({statement:i,name:f,emit:If(i.text,f)});continue}}r.declarations.push({statement:i,name:null,emit:i.text})}return r}function Do(e,t){if(t.size===0)return e;let r="",n=0,i=e.length,s=`
|
|
13
|
+
`;while(n<i){let o=e[n];if(o==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2),c=a===-1?i:a+2;r+=e.slice(n,c),n=c;continue}if(o==="/"&&e[n+1]==="/"){let a=e.indexOf(`
|
|
14
|
+
`,n),c=a===-1?i:a;r+=e.slice(n,c),n=c;continue}if(o==="'"||o==='"'){let a=n+1;while(a<i&&e[a]!==o&&e[a]!==`
|
|
15
|
+
`){if(e[a]==="\\")a++;a++}r+=e.slice(n,a+1),n=a+1,s=o;continue}if(/[A-Z_$]/i.test(o)){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&&s!=="."){let u=a;while(u<i&&(e[u]===" "||e[u]==="\t"))u++;let h=(e[u]===":"||e[u]==="?"&&e[u+1]===":")&&/[{;,(\n]/.test(s);r+=h?c:f}else r+=c;s="a",n=a;continue}if(r+=o,o===`
|
|
16
|
+
`||!/\s/.test(o))s=o;n++}return r}function Fo(e,t,r,n){let i=[],s=new Map,o=[e,...t.filter((L)=>L!==e)];for(let L of o){let K=r.get(L);if(K===void 0){i.push(`No declarations were generated for ${Lt(n.cwd,L)}; it is left out of the bundle`);continue}s.set(L,Ff(L,K))}let a=(L,K)=>{if(!L.startsWith(".")&&!L.startsWith("/"))return null;let J=zt(L,K).resolved;return J&&s.has(J)?J:null},c=(L)=>L.startsWith(".")||L.startsWith("/"),f=new Set,u=(L)=>{let K=L;for(let J=1;f.has(K);J++)K=`${L}_${J}`;return f.add(K),K},h=new Map;for(let[L,K]of s){let J=new Map;for(let z of K.declared)J.set(z,u(z));h.set(L,J)}let l=new Map,y=(L,K,J)=>{let z=`${L}\x00${K}`,te=l.get(z);if(!te)te=u(J),l.set(z,te);return te},C=new Map,S=new Map,x=new Set,v=(L,K,J)=>{let z=a(K,L.file);if(z){if(J==="*")return{kind:"namespace",file:z};let te=W(z).get(J);if(!te)i.push(`${Lt(n.cwd,L.file)}: '${J}' is not exported by '${K}'`);return te??null}if(c(K))return i.push(`${Lt(n.cwd,L.file)}: '${K}' is not part of the bundle`),null;return J==="*"?{kind:"external-namespace",source:K}:{kind:"external",source:K,imported:J}},B=(L,K)=>{if(L.declared.has(K))return{kind:"local",name:h.get(L.file).get(K)};let J=L.imports.get(K);if(J)return v(L,J.specifier,J.imported);return i.push(`${Lt(n.cwd,L.file)}: cannot resolve exported name '${K}'`),null};function W(L){let K=C.get(L);if(K)return K;let J=new Map,z=s.get(L);if(!z||x.has(L))return J;x.add(L);let te=new Set;for(let[X,se]of z.localExports){let Be=B(z,se);if(Be)J.set(X,Be)}for(let X of z.namedReExports){let se=v(z,X.specifier,X.imported);if(se)J.set(X.exported,se)}for(let X of z.namespaceReExports){let se=v(z,X.specifier,"*");if(se)J.set(X.exported,se)}for(let X of z.starReExports){let se=a(X,L);if(se){for(let[Be,He]of W(se))if(Be!=="default"&&!J.has(Be))J.set(Be,He);for(let Be of S.get(se)??[])te.add(Be)}else if(c(X))i.push(`${Lt(n.cwd,L)}: '${X}' is not part of the bundle`);else te.add(X)}return x.delete(L),C.set(L,J),S.set(L,te),J}let P=new Map,F=[],I=(L,K)=>{switch(L.kind){case"local":return L.name;case"external":return y(L.source,L.imported,L.imported==="default"?K:L.imported);case"external-namespace":return y(L.source,"*",K);case"namespace":return k(L.file,K)}};function k(L,K){let J=P.get(L);if(J)return J;let z=u(K);P.set(L,z);let te=[];for(let[X,se]of W(L)){if(X==="default")continue;let Be=I(se,X);te.push(Be===X?X:`${Be} as ${X}`)}if(S.get(L)?.size)i.push(`${Lt(n.cwd,L)}: 'export * from' an external module cannot be expressed inside namespace '${z}'`);return F.push(`declare namespace ${z} {
|
|
17
|
+
export { ${te.join(", ")} };
|
|
18
|
+
}`),z}let H=[],j=[],O=new Set;for(let[L,K]of s){for(let te of K.directives)O.add(te);let J=new Map;for(let[te,X]of h.get(L))if(te!==X)J.set(te,X);for(let[te,X]of K.imports){if(K.declared.has(te))continue;let se=v(K,X.specifier,X.imported);if(!se)continue;let Be=I(se,te);if(Be!==te)J.set(te,Be)}let z=[];for(let te of K.declarations){if(n.keepComments)z.push(...te.statement.comments);let X=Do(te.emit,J);if(!/[;}]$/.test(X))X+=";";z.push(X)}for(let te of K.verbatim){if(n.keepComments)j.push(...te.comments);j.push(Do(te.text,J))}if(z.length>0)H.push(`// From: ${Lt(n.cwd,L)}
|
|
19
19
|
${z.join(`
|
|
20
|
-
`)}`)}let
|
|
21
|
-
`));if(
|
|
20
|
+
`)}`)}let Z=W(e),me=[],Oe=[];for(let[L,K]of Z){if(K.kind==="external"){Oe.push(`export { ${K.imported===L?L:`${K.imported} as ${L}`} } from '${K.source}';`);continue}if(K.kind==="external-namespace"){Oe.push(`export * as ${L} from '${K.source}';`);continue}let J=I(K,L==="default"?"_default":L);me.push(J===L?L:`${J} as ${L}`)}for(let L of S.get(e)??[])Oe.push(`export * from '${L}';`);let ie=new Map;for(let[L,K]of l){let[J,z]=L.split("\x00"),te=ie.get(J)??{named:[],defaults:[],namespaces:[]};if(ie.set(J,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[L,K]of[...ie].sort(([J],[z])=>J.localeCompare(z))){for(let J of K.defaults)ne.push(`import ${J} from '${L}';`);for(let J of K.namespaces)ne.push(`import * as ${J} from '${L}';`);if(K.named.length>0)ne.push(`import { ${K.named.join(", ")} } from '${L}';`)}let ue=[];if(O.size>0)ue.push([...O].join(`
|
|
21
|
+
`));if(ue.push(`/**
|
|
22
22
|
* Bundled TypeScript declarations
|
|
23
23
|
* Generated from ${s.size} source files
|
|
24
|
-
*/`),
|
|
25
|
-
`));if(
|
|
26
|
-
`));if(j.length>0)
|
|
27
|
-
`));let
|
|
28
|
-
`)),{content:`${
|
|
24
|
+
*/`),ne.length>0)ue.push(ne.join(`
|
|
25
|
+
`));if(ue.push(...H),F.length>0)ue.push(F.join(`
|
|
26
|
+
`));if(j.length>0)ue.push(j.join(`
|
|
27
|
+
`));let oe=[];if(me.length>0)oe.push(`export { ${me.join(", ")} };`);if(oe.push(...Oe),oe.length===0)oe.push("export {};");return ue.push(oe.join(`
|
|
28
|
+
`)),{content:`${ue.join(`
|
|
29
29
|
|
|
30
30
|
`)}
|
|
31
|
-
`,files:[...s.keys()],exportCount:
|
|
31
|
+
`,files:[...s.keys()],exportCount:Z.size,warnings:i}}var Io,Df;var No=he(()=>{vn();Io=/^[A-Z_$][\w$]*$/i;Df=/^(?: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 Go(e,t={}){let{lineEnding:r="lf",trailingNewline:n=!0,maxBlankLines:i=1,trimTrailingWhitespace:s=!0,normalizeIndentation:o=!0,indent:a={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:h=!0}=t,l=e;if(l=Lf(l,r),f?.enabled!==!1)l=Vf(l,f||{});if(c)l=Hf(l,c);if(s)l=Gf(l);if(l=Bf(l,i),o)l=Uf(l,a);if(n||h)l=_f(l);return l}function Lf(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
|
|
32
32
|
`)!==-1)r=r.replace(/\r\n/g,`
|
|
33
33
|
`);if(r.indexOf("\r")!==-1)r=r.replace(/\r/g,`
|
|
34
34
|
`)}if(t==="crlf")r=r.replace(/\n/g,`\r
|
|
35
|
-
`);return r}function
|
|
35
|
+
`);return r}function Gf(e){return e.split(`
|
|
36
36
|
`).map((t)=>t.replace(/[\t ]+$/,"")).join(`
|
|
37
|
-
`)}function
|
|
38
|
-
`.repeat(t+1))}function
|
|
39
|
-
`}function
|
|
40
|
-
`),o=[];for(let
|
|
41
|
-
`)}function
|
|
42
|
-
`),o=[],
|
|
43
|
-
`)}function
|
|
44
|
-
`),o=[],
|
|
45
|
-
`)}function
|
|
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
46
|
`)!==-1)f=f.replace(/\r\n/g,`
|
|
47
47
|
`);if(o){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
|
|
48
48
|
|
|
49
49
|
|
|
50
50
|
`)!==-1)f=f.replace(/\n{3,}/g,`
|
|
51
51
|
|
|
52
|
-
`);f=
|
|
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
53
|
`))f+=`
|
|
54
|
-
`;return f}function
|
|
55
|
-
`),n=[];for(let i of r){let s=i.match(/^(\s*)(.*)$/);if(!s){n.push(i);continue}let[,o,
|
|
56
|
-
`)}function
|
|
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
|
|
58
|
-
`)}function
|
|
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]||"",
|
|
60
|
-
`)}function Qf(e,t,r){let n=e.match(Xf);if(!n)return null;let[,i,s,o,l]=n,c=o.split(",").map((a)=>a.trim()).filter(Boolean);if(c.length<=1)return[e];let f=`${t}${i}${s??""} {`,u=l?`${t}} ${l};`:`${t}};`;return[f,...c.map((a)=>`${r}${a},`),u]}function eu(e,t,r,n){let i=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!i)return[e];let[,,s,o,l,c]=i,f=l.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 tu(e,t,r,n){let i=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!i)return[e];let[,,s,o]=i,l=o.split(/\s*\|\s*/).filter((c)=>c.trim());if(l.length<=2)return[e];return[`${r}${s}`,...l.map((c,f)=>`${n}${f>0?"| ":" "}${c.trim()}`)]}async function Go(e,t={},r){let n=[];if(t.usePrettier!==!1){if(await Hf())try{let i={...await jf(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await Kf(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:Zf(e,t.builtIn),usedPrettier:!1,warnings:n.length>0?n:void 0}}var jr=null,Pt=null,Xf;var Bo=de(()=>{Xf=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/});import ru from"process";import{existsSync as _o,statSync as Uo}from"fs";import{existsSync as iu,mkdirSync as hg,readdirSync as dg,readFileSync as nu,writeFileSync as pg}from"fs";import{homedir as qt}from"os";import{dirname as yg,resolve as st}from"path";import Ai from"process";import{existsSync as Vo,statSync as Ho}from"fs";import{existsSync as _n,mkdirSync as su,readdirSync as ou,writeFileSync as au}from"fs";import{homedir as zt}from"os";import{dirname as jo,resolve as qe}from"path";import Wt from"process";import{join as lu,relative as cu,resolve as Ko}from"path";import ui from"process";import{existsSync as Ta,mkdirSync as Tg,readdirSync as Og,writeFileSync as Rg}from"fs";import{homedir as bn}from"os";import{dirname as Mg,resolve as Je}from"path";import wr from"process";import{join as fu,relative as uu,resolve as Zo}from"path";import hi from"process";import{existsSync as Oa,mkdirSync as Wg,readdirSync as Lg,writeFileSync as Gg}from"fs";import{dirname as _g,resolve as di}from"path";import Un from"process";import{Buffer as kt}from"buffer";import{createCipheriv as hu,createDecipheriv as du,randomBytes as En}from"crypto";import{closeSync as Sn,createReadStream as Yo,createWriteStream as pu,existsSync as An,fsyncSync as Jo,openSync as qo,writeFileSync as mu}from"fs";import{access as gu,constants as zo,mkdir as yu,readdir as Kr,rename as Xo,stat as Xt,unlink as Zr,writeFile as xn}from"fs/promises";import{join as Qt}from"path";import He from"process";import{pipeline as Cu}from"stream/promises";import{createGzip as Qo}from"zlib";import er from"process";import $t from"process";import{Buffer as yt}from"buffer";import{createCipheriv as wu,createDecipheriv as $u,randomBytes as Tn}from"crypto";import{closeSync as On,createReadStream as ea,createWriteStream as vu,existsSync as Yr,fsyncSync as ta,openSync as ra,writeFileSync as bu}from"fs";import{access as Eu,constants as ia,mkdir as Su,readdir as Jr,rename as na,stat as tr,unlink as qr,writeFile as Rn}from"fs/promises";import{isAbsolute as Au,join as rr,resolve as xu}from"path";import ye from"process";import{pipeline as Tu}from"stream/promises";import{createGzip as sa}from"zlib";import ir from"process";import vt from"process";import zr from"process";import{existsSync as Xr}from"fs";import{resolve as Pn}from"path";import{existsSync as Ou}from"fs";import{existsSync as Ru,readdirSync as Pu}from"fs";import{extname as kn,resolve as oa}from"path";import ku from"process";import{join as Mu,relative as Du,resolve as aa}from"path";import pi from"process";import{Buffer as Ct}from"buffer";import{createCipheriv as Iu,createDecipheriv as Fu,randomBytes as Mn}from"crypto";import{closeSync as Dn,createReadStream as la,createWriteStream as Nu,existsSync as Qr,fsyncSync as ca,openSync as fa,writeFileSync as Wu}from"fs";import{access as Lu,constants as ua,mkdir as Gu,readdir as ei,rename as ha,stat as nr,unlink as ti,writeFile as In}from"fs/promises";import{isAbsolute as Bu,join as sr,resolve as _u}from"path";import Ce from"process";import{pipeline as Uu}from"stream/promises";import{createGzip as da}from"zlib";import or from"process";import bt from"process";import ri from"process";import{existsSync as ii}from"fs";import{resolve as Fn}from"path";import{existsSync as Vu}from"fs";class Ra{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(!_o(e))return!0;return Uo(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=_o(r)?Uo(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 Pa{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 Ku(e,t){this[e]=ju.bind(null,t)}class es{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 ts{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 Ju(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function qu(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function zu(e){return e.getStats().size*2}function rs(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Oe(t[0])&&"id"in t[0]&&t[0].id===3&&Oe(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Oe(t)&&Oe(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Oe(e)&&"arr"in e&&Array.isArray(e.arr)&&Oe(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Oe(t[0])&&Oe(e[0])){let n=[...t];for(let i of e)if(Oe(i)&&"name"in i){if(!n.find((s)=>Oe(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Oe(i)&&"path"in i){if(!n.find((s)=>Oe(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>gi(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(!Oe(t)||!Oe(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(Oe(i)&&Oe(r[n]))r[n]=rs(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Oe(i[0])&&Oe(r[n][0])){let s=[...i];for(let o of r[n])if(Oe(o)&&"name"in o){if(!s.find((l)=>Oe(l)&&("name"in l)&&l.name===o.name))s.push(o)}else if(Oe(o)&&"path"in o){if(!s.find((l)=>Oe(l)&&("path"in l)&&l.path===o.path))s.push(o)}else if(!s.some((l)=>gi(l,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 gi(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(!gi(e[r],t[r]))return!1;return!0}if(Oe(e)&&Oe(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(!gi(e[i],t[i]))return!1}return!0}return!1}function Oe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Xu(e,t){if(!Oa(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 rs(t,n)}catch{return null}}catch{return null}}async function Qu({name:e="",cwd:t,defaultConfig:r}){let n=t||Un.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let l of i){let c=di(n,`${o}${l}`),f=await Xu(c,r);if(f!==null)return f}try{let o=di(n,"package.json");if(Oa(o)){let l=(await import(o))[e];if(l&&typeof l==="object"&&!Array.isArray(l))try{return rs(r,l)}catch{}}}catch{}return r}function eh(e,t={}){let r=hi.cwd();while(r.includes("storage"))r=Zo(r,"..");let n=Zo(r,e||"");if(t?.relative)return uu(hi.cwd(),n);return n}async function th(){try{let e=await Qu({name:"clarity",defaultConfig:ai,cwd:hi.cwd(),endpoint:"",headers:{}});return{...ai,...e}}catch{return ai}}function Re(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function rh(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let e=$t.type;if(e==="renderer"||e==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class Ma{async format(e){let t=await rh(),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:er.pid,hostname:t(),environment:er.env.NODE_ENV||"development",platform:er.platform,version:er.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:er.env.NODE_ENV||er.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yi{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={...Hn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ma,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??He.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{...li,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...li};return{...li,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Hn.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 gu(this.config.logDirectory,zo.F_OK|zo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await yu(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 l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:kt.from(e);try{if(!An(this.currentLogFile))await xn(this.currentLogFile,"",{mode:420});if(n=qo(this.currentLogFile,"a",420),mu(n,l,{flag:"a"}),Jo(n),n!==void 0)Sn(n),n=void 0;if((await Xt(this.currentLogFile)).size===0){if(await xn(this.currentLogFile,l,{flag:"w",mode:420}),(await Xt(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 a=o*2**i;await new Promise((m)=>setTimeout(m,a)),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{Sn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(l){if(i===s-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}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 Qt(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 Qt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Qt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Re())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],[,l])=>l.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 En(16).toString("hex")}generateKey(){return En(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=En(16),n=hu("aes-256-gcm",t,r),i=kt.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:kt.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Qo(),i=[];n.on("data",(s)=>i.push(s)),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(Re())return;let e=await Xt(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 Kr(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,l=`${r}.${o}`;if(await Xt(r).catch(()=>null))try{if(await Xo(r,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Zr(l)}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 xn(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 Xt(r).catch(()=>null))await Xo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Kr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Zr(Qt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Yo(e),n=pu(t),i=Qo();await Cu(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()})),An(this.currentLogFile))try{let e=qo(this.currentLogFile,"r+");Jo(e),Sn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Re()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Kr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Zr(Qt(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:s,showTimestamp:o=!0}=e,l=(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=He.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} ${Ee.cyan(i)}`;if(!o)return f.trim();let u=l(f).trim().length,a=l(t).length,m=Math.max(1,c-2-u-a);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let l=t[n++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return 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,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!Re()){let f=Ua[e],u=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",a;switch(e){case"debug":a=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ee.gray(o),level:e}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(a);break;case"success":a=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ee.green(o),level:e}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(a),l){let m=l.split(`
|
|
61
|
-
`);for(let y of
|
|
62
|
-
`;if(
|
|
63
|
-
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!
|
|
64
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
65
|
-
`),o=Math.max(...s.map((u)=>u.length))+2,
|
|
66
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(
|
|
67
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||
|
|
68
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Re()||!He.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Re()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Kr(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=Qt(this.config.logDirectory,n);if(e.before)try{if((await Xt(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 Zr(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 oi(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&we(t[0])&&"id"in t[0]&&t[0].id===3&&we(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(we(t)&&we(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(we(e)&&"arr"in e&&Array.isArray(e.arr)&&we(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&we(t[0])&&we(e[0])){let n=[...t];for(let i of e)if(we(i)&&"name"in i){if(!n.find((s)=>we(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(we(i)&&"path"in i){if(!n.find((s)=>we(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(!we(t)||!we(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(we(i)&&we(r[n]))r[n]=oi(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&we(i[0])&&we(r[n][0])){let s=[...i];for(let o of r[n])if(we(o)&&"name"in o){if(!s.find((l)=>we(l)&&("name"in l)&&l.name===o.name))s.push(o)}else if(we(o)&&"path"in o){if(!s.find((l)=>we(l)&&("path"in l)&&l.path===o.path))s.push(o)}else if(!s.some((l)=>Ci(l,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 is(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:oi(e,t);if(Array.isArray(e))return r==="replace"?t:oi(e,t);if(!we(t)||!we(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]=oi(o,s);else if(we(s)&&we(o))n[i]=is(o,s,r);else n[i]=s}return n}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(we(e)&&we(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 we(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ni(e,t,r="replace"){if(!Ta(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 is(t,i,r)}catch{return null}}catch{return null}}function ih(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,l=[]){let c={...o};for(let[f,u]of Object.entries(o)){let a=[...l,f],m=(C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${n}_${a.map(m).join("_")}`,w=`${n}_${a.map((C)=>C.toUpperCase()).join("_")}`;if(r)Ke.info(`Checking environment variable ${y} for config ${e}.${a.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,a);else{let C=wr.env[y]||wr.env[w];if(C!==void 0){if(r)Ke.info(`Using environment variable ${C?y:w} for config ${e}.${a.join(".")}`);if(typeof u==="number")c[f]=Number(C);else if(typeof u==="boolean")c[f]=C.toLowerCase()==="true";else if(Array.isArray(u))try{let x=JSON.parse(C);if(Array.isArray(x))c[f]=x;else c[f]=C.split(",").map((k)=>k.trim())}catch{c[f]=C.split(",").map((x)=>x.trim())}else c[f]=C}}}return c}return s(i)}async function nh({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:l="replace"}){let c=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?ih(e,i,s):i,f=r||wr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Ke.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let a=[e,`.${e}`].filter(Boolean),m=[`${e}.config`,`.${e}.config`].filter(Boolean),y=t?[t,`.${t}`]:[],w=t?[`${t}.config`,`.${t}.config`]:[],C=Array.from(new Set([f,Je(f,"config"),Je(f,".config"),n?Je(f,n):void 0].filter(Boolean)));for(let x of C){if(s)Ke.info(`Searching for configuration in: ${x}`);let k=[Je(f,"config"),Je(f,".config")].concat(n?[Je(f,n)]:[]).includes(x)?[...a,...m,...y,...w]:[...m,...a,...w,...y];for(let L of k)for(let G of u){let T=Je(x,`${L}${G}`),D=await ni(T,c,l);if(D!==null){if(s)Ke.success(`Configuration loaded from: ${T}`);return D}}}if(e){let x=Je(bn(),".config",e),k=["config",`${e}.config`];if(t)k.push(`${t}.config`);if(s)Ke.info(`Checking user config directory: ${x}`);for(let L of k)for(let G of u){let T=Je(x,`${L}${G}`),D=await ni(T,c,l);if(D!==null){if(s)Ke.success(`Configuration loaded from user config directory: ${T}`);return D}}}if(e){let x=Je(bn(),".config"),k=[`.${e}.config`];if(t)k.push(`.${t}.config`);if(s)Ke.info(`Checking user config directory for dotfile configs: ${x}`);for(let L of k)for(let G of u){let T=Je(x,`${L}${G}`),D=await ni(T,c,l);if(D!==null){if(s)Ke.success(`Configuration loaded from user config directory dotfile: ${T}`);return D}}}if(e){let x=bn(),k=[`.${e}.config`,`.${e}`];if(t)k.push(`.${t}.config`),k.push(`.${t}`);if(s)Ke.info(`Checking user home directory for dotfile configs: ${x}`);for(let L of k)for(let G of u){let T=Je(x,`${L}${G}`),D=await ni(T,c,l);if(D!==null){if(s)Ke.success(`Configuration loaded from user home directory: ${T}`);return D}}}try{let x=Je(f,"package.json");if(Ta(x)){let k=await import(x),L=k[e];if(!L&&t){if(L=k[t],L&&s)Ke.success(`Using alias "${t}" configuration from package.json`)}if(L&&typeof L==="object"&&!Array.isArray(L))try{if(s)Ke.success(`Configuration loaded from package.json: ${L===k[e]?e:t}`);return is(c,L,l)}catch(G){if(s)Ke.warn("Failed to merge package.json config:",G)}}}catch(x){if(s)Ke.warn("Failed to load package.json:",x)}if(s)Ke.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function sh(e,t={}){let r=ui.cwd();while(r.includes("storage"))r=Ko(r,"..");let n=Ko(r,e||"");if(t?.relative)return cu(ui.cwd(),n);return n}async function oh(){try{let e=await nh({name:"clarity",alias:"logging",defaultConfig:ci,cwd:ui.cwd()});return{...ci,...e||{}}}catch{return ci}}function Ne(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ah(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vt<"u"){let e=vt.type;if(e==="renderer"||e==="worker")return!1;return!!(vt.versions&&(vt.versions.node||vt.versions.bun))}return!1}class Da{async format(e){let t=await ah(),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:ir.pid,hostname:t(),environment:ir.env.NODE_ENV||"development",platform:ir.platform,version:ir.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ir.env.NODE_ENV||ir.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;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 Da,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},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{...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: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 Eu(this.config.logDirectory,ia.F_OK|ia.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Su(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 l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:yt.from(e);try{if(!Yr(this.currentLogFile))await Rn(this.currentLogFile,"",{mode:420});if(n=ra(this.currentLogFile,"a",420),bu(n,l,{flag:"a"}),ta(n),n!==void 0)On(n),n=void 0;if((await tr(this.currentLogFile)).size===0){if(await Rn(this.currentLogFile,l,{flag:"w",mode:420}),(await tr(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 a=o*2**i;await new Promise((m)=>setTimeout(m,a)),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{On(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(l){if(i===s-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}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 rr(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 rr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return rr(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],[,l])=>l.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 Tn(16).toString("hex")}generateKey(){return Tn(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=Tn(16),n=wu("aes-256-gcm",t,r),i=yt.isBuffer(e)?e:yt.from(e,"utf8"),s=n.update(i),o=n.final(),l=s.length+o.length,c=n.getAuthTag(),f=yt.allocUnsafe(16+l+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+l),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=sa(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(yt.from(yt.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 tr(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 Jr(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,l=`${r}.${o}`;if(await tr(r).catch(()=>null))try{if(await na(r,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await qr(l)}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 Rn(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 tr(r).catch(()=>null))await na(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Jr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await qr(rr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=ea(e),n=vu(t),i=sa();await Tu(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()})),Yr(this.currentLogFile))try{let e=ra(this.currentLogFile,"r+");ta(e),On(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 Jr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await qr(rr(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()?fe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ne())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,l=(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} ${fe.cyan(i)}`;if(!o)return f.trim();let u=l(f).trim().length,a=l(t).length,m=Math.max(1,c-2-u-a);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let l=t[n++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return 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=fe.underline(fe.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\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)=>fe.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>fe.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>fe.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>fe.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>fe.strikethrough(n)),t}supportsHyperlinks(){if(Ne())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(Au(t)||t.startsWith("./")||t.startsWith("../"))t=xu(t);else return null;return Yr(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,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let a=this.options.showIcons===!1?"":Va[e],m=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:fe.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:fe.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.error(y),l){let w=l.split(`
|
|
69
|
-
`);for(let
|
|
70
|
-
`;if(
|
|
71
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};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()&&
|
|
72
|
-
`);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Ne()&&
|
|
73
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?
|
|
74
|
-
`),c=Math.max(...
|
|
75
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Ne())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${
|
|
76
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
77
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ne()||!
|
|
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}
|
|
62
|
+
`;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?be.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:be.blue("\u25D0"),tag:r,message:`${be.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
64
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!Pe()){let f=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:be.green("\u2713"),tag:f,message:`${s}${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 wi(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(!xn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return qo(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=Dt.isBuffer(e)?e:Dt.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),a=mu("aes-256-gcm",r,i);return a.setAuthTag(s),Dt.concat([a.update(o),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 s=e.split(`
|
|
65
|
+
`),o=Math.max(...s.map((u)=>u.length))+2,a=`\u250C${"\u2500".repeat(o)}\u2510`,c=`\u2514${"\u2500".repeat(o)}\u2518`,f=s.map((u)=>{let h=" ".repeat(o-u.length-2);return`\u2502 ${u}${h} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:be.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:be.cyan(a)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:be.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:be.cyan(c),showTimestamp:!1}))}else if(!Pe())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
66
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(Pe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${be.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();je.stdin.removeListener("data",r);try{if(typeof je.stdin.setRawMode==="function")je.stdin.setRawMode(!1)}catch{}je.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof je.stdin.setRawMode==="function")je.stdin.setRawMode(!0)}catch{}je.stdin.resume(),je.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,s=0;if(r=e.replace(i,(o,a)=>{if(a==="%")return"%";if(s>=t.length)return o;let c=t[s++];switch(a){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}}),s<t.length)r+=` ${t.slice(s).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}if(this.fancy&&!Pe()){let i=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"",s=be.blue("\u25D0");console.error(`${s} ${i} ${be.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
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 s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},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;je.stdout.write(`${"\r".padEnd(je.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()||!je.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=be.green("\u2501".repeat(n)),o=be.gray("\u2501".repeat(i)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||r===100?be.green("\u2713"):be.blue("\u25B6"),h=this.options.showTags!==!1&&this.name?` ${be.gray(this.formatTag(this.name))}`:"",l=`\r${u}${h} ${a} ${c}${f}`,y=je.stdout.columns||80,C=" ".repeat(Math.max(0,y-l.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${l}${C}`,je.stdout.write(e.lastRenderedLine),t)je.stdout.write(`
|
|
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(o))console.error(this.formatConsoleMessage({timestamp:i,message:ce.gray(` ${S}`),level:e,showTimestamp:!1}))}break}}else if(!Ne()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
70
|
+
`;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,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};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,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Ne()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!Ne()&&ge.stdout.isTTY)ge.stdout.write(`
|
|
72
|
+
`);if(this[s==="warning"?"warn":s](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),s=`${e} completed in ${i}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
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:`${s}${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 vi(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 ra(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),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),a=bu("aes-256-gcm",r,i);a.setAuthTag(s);let c=a.update(o),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 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:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=i.split(`
|
|
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] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
75
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}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 o=/%([sdijfo%])/g,a=0;if(r=e.replace(o,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${ce.blue("\u25D0")} `;console.error(`${a}${o} ${ce.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
76
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}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,s=ce.green("\u2501".repeat(n)),o=ce.gray("\u2501".repeat(i)),a=`[${s}${o}]`,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(`
|
|
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 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=nr(this.config.logDirectory,n);if(e.before)try{if((await ir(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 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)}}}async function Na(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!i(o))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Wa(e){return e instanceof rt}function fh(e){return e instanceof bi}function uh(e){if(Wa(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 Oi{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose: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:s,customParsers:o,verbose:a,configName:e}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Sr.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,s]of Object.entries(e)){let o=[...t,i],a=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${a.join("_")}`,f=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Qr.env[c]||(f?Qr.env[f]:void 0);if(u!==void 0){if(n.verbose){let h=Qr.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof s,c,n.customParsers,n.configName)}catch(h){if(h instanceof Ei)throw h;throw It.envVar(c,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw It.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Qr.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:a,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
78
78
|
|
|
79
79
|
`;for(let n of e)r+=`${n.key}
|
|
80
80
|
`,r+=` Type: ${n.type}
|
|
@@ -86,25 +86,25 @@ ${z.join(`
|
|
|
86
86
|
`;r+=`| Variable | Type | Description | Example |
|
|
87
87
|
`,r+=`|----------|------|-------------|----------|
|
|
88
88
|
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
89
|
-
`;return r}}function fh(e,t){let r=Ba("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Na(e,t,r={}){return Wa(e,t,r,new WeakMap)}function Wa(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 l=o(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return La(e,t,i,n);if(!ot(t)||!ot(e))return t;return ph(e,t,r,n)}function La(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 uh(e,t);case"smart":return hh(e,t,n);default:return t}return t}function uh(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Vn(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(ot(t[0])&&ot(e[0]))return dh(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 dh(e,t,r){let n=[...t];for(let i of e){if(!ot(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let l of s)if(l in i){if(n.find((c)=>ot(c)&&(l in c)&&c[l]===i[l])){o=!0;break}}if(!o)n.push(i)}return n}function ph(e,t,r,n){let i=t;if(ot(i)&&n.has(i))return n.get(i);let s={...e};if(ot(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let l=i[o],c=s[o];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){s[o]=l;continue}if(ot(l)&&ot(c))s[o]=Wa(c,l,r,n);else if(Array.isArray(l)||Array.isArray(c))s[o]=La(c,l,r.arrayMergeMode||"smart",n);else s[o]=l}return s}function ns(e,t,r="replace"){return Na(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Vn(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(!Vn(e[r],t[r]))return!1;return!0}if(ot(e)&&ot(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(!Vn(e[i],t[i]))return!1}return!0}return!1}function ot(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ti{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:l=!1}=r;if(i){let f=ar.getWithFileCheck("file",e);if(f){if(l)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Xr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),a=u.default||u,m="default"in u,y=Object.keys(u).length>0;if(!m&&!y)throw new $r(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof a!=="object"||a===null||Array.isArray(a))throw new $r(e,Error("Configuration must export a valid object"),"unknown");let w={config:ns(t,a,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)ar.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?Mt.configLoad(e,f):Mt.configLoad(e,Error(String(f)))}};if(o)return br.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(Pn(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 Ia(async()=>Xr(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Xr(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let l=Pn(e,`${s}${o}`);if(await this.checkFileAccess(l))n.push(l)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let l=Pn(e,o);if(await this.checkFileAccess(l))n.push(l)}}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(!Xr(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 ss{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:l=!0,verbose:c=!1}=r,f=async()=>{let u=[],a=[],m={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:l,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,m);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],m);else return this.validateWithJSONSchema(e,t,m)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:a}}};if(l)return await br.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Ou(t))throw new vr(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 vr(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,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(o)){if(n.push({path:r,message:`Expected type ${l.join(" or ")}, got ${o}`,expected:l.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 l=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,l,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 l of t.required)if(!(l in o)){if(n.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[l,c]of Object.entries(t.properties))if(l in o){let f=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(o[l],c,f,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!l.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),l=this.validateWithRule(o,s,s.path);if(n.push(...l),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:ja},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class os{fileLoader=new Ti;envProcessor=new xi;validator=new ss;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 l;try{l=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;l={...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"),a=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),m=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(m||u))throw c;if(a&&(!f||!m))l={...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)l={...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 l={...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(l.config,i,s,o.name);if(r?.enabled&&l)this.cacheResult(o.name||"",l,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)ft.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);l.metrics=c}return l}catch(l){let c=Date.now()-t;throw ft.error(`Configuration loading failed after ${c}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:l,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,a=s||Wt.cwd(),m=[],y=await this.loadLocalConfiguration(n,i,a,o,l,f,u,c,r);if(y)return m.push(...this.getLocalSearchPaths(n,i,a,o)),this.finalizeResult(y,m,c,n,u);let w=await this.loadHomeConfiguration(n,i,l,f,u,c);if(w)return m.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,m,c,n,u);let C=await this.loadPackageJsonConfiguration(n,i,a,l,f,u,c);if(C)return m.push(qe(a,"package.json")),this.finalizeResult(C,m,c,n,u);if(m.push(...this.getAllSearchPaths(n,i,a,o)),t)throw Mt.configNotFound(n,m,i);return{...await this.applyEnvironmentVariables(n,l,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,l,c){let f=l?Cr(e,i,o):i,u=this.getLocalDirectories(r,n);for(let a of u){if(o)ft.info(`Searching for configuration in: ${a}`);let m=this.fileLoader.generateConfigPaths(e,a,t),y=await this.fileLoader.tryLoadFromPaths(m,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(o)ft.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?Cr(e,r,i):r,l=[qe(zt(),".config",e),qe(zt(),".config"),zt()];for(let c of l){if(i)ft.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)ft.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let l=o?Cr(e,n,s):n;try{let c=qe(r,"package.json");if(!_n(c))return null;let f=await import(c),u=f[e],a=e;if(!u&&t)u=f[t],a=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)ft.success(`Configuration loaded from package.json: ${a}`);return{config:ns(l,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)ft.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:Cr(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 Mt.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ar.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);ar.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,qe(e,"config"),qe(e,".config"),t?qe(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(qe(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=[qe(zt(),".config",e),qe(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 pa(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 mh(e){return Et.loadConfig({...e,__strictErrorHandling:!0})}async function Ga(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Et.loadConfig(e);else n=await Et.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)ft.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 Et.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function gh(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Et.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"&&pa(r)))return(await Et.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Et.loadConfig({...e,cwd:e.cwd||Wt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&pa(t)))return(await Et.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function yh(e,t,r="replace"){let n=new Ti;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Cr(e,t,r=!1){let n=new xi,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,l=[]){let c={...o};for(let[f,u]of Object.entries(o)){let a=[...l,f],m=[`${i}_${a.join("_").toUpperCase()}`,`${i}_${a.map((C)=>C.toUpperCase()).join("")}`,`${i}_${a.map((C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,w;for(let C of m)if(y=Wt.env[C],y!==void 0){w=C;break}if(y!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let C=Number(y);if(!Number.isNaN(C))c[f]=C}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((C)=>C.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,a)}return c}return s(t)}function Ch(e){let t=qe(Wt.cwd(),e.configDir),r=qe(Wt.cwd(),e.generatedDir),n=qe(r,"config-types.ts");if(!_n(jo(n)))su(jo(n),{recursive:!0,mode:511});let i=_n(t)?ou(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${Zh}
|
|
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}
|
|
90
90
|
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
91
|
-
`;
|
|
92
|
-
${i.map((c)=>{let f=
|
|
91
|
+
`;cu(n,s,{mode:438})}function vh(e){let t=null,r=null,n=()=>{if(!r)r=_a(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)ht.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let a=i[o];return n(),a},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,a){if(!t)t={...i};return t[o]=a,!0}})}function bh(e){let t=la(Du.cwd(),e?.configDir||"./config");function r(){if(!ku(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=Mu(t).filter((c)=>i.has(Mn(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),a=new Map;for(let{base:c,file:f}of o){let u=Mn(f).toLowerCase(),h=a.get(c);if(!h){a.set(c,f);continue}let l=Mn(h).toLowerCase();if(s.indexOf(u)<s.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(),s=i.map((c)=>c.base),o=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",a=i.length?`{
|
|
92
|
+
${i.map((c)=>{let f=la(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
|
|
93
93
|
`)}
|
|
94
94
|
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
95
|
-
export type ConfigByName = ${
|
|
95
|
+
export type ConfigByName = ${a}
|
|
96
96
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
97
97
|
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 Jh(e,t={}){let r=pi.cwd();while(r.includes("storage"))r=aa(r,"..");let n=aa(r,e||"");if(t?.relative)return Du(pi.cwd(),n);return n}function Le(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zh(){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 Ja{async format(e){let t=await zh(),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:or.pid,hostname:t(),environment:or.env.NODE_ENV||"development",platform:or.platform,version:or.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:or.env.NODE_ENV||or.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Oi{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={...bi},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ja,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Ce.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{...Bn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Bn};return{...Bn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:bi.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 Lu(this.config.logDirectory,ua.F_OK|ua.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Gu(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 l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ct.from(e);try{if(!Qr(this.currentLogFile))await In(this.currentLogFile,"",{mode:420});if(n=fa(this.currentLogFile,"a",420),Wu(n,l,{flag:"a"}),ca(n),n!==void 0)Dn(n),n=void 0;if((await nr(this.currentLogFile)).size===0){if(await In(this.currentLogFile,l,{flag:"w",mode:420}),(await nr(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 a=o*2**i;await new Promise((m)=>setTimeout(m,a)),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(l){if(i===s-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}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 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(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],[,l])=>l.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 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=Iu("aes-256-gcm",t,r),i=Ct.isBuffer(e)?e:Ct.from(e,"utf8"),s=n.update(i),o=n.final(),l=s.length+o.length,c=n.getAuthTag(),f=Ct.allocUnsafe(16+l+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+l),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=da(),i=[];n.on("data",(s)=>i.push(s)),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(Le())return;if(!this.shouldWriteToFile())return;let e=await nr(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),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,l=`${r}.${o}`;if(await nr(r).catch(()=>null))try{if(await ha(r,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await ti(l)}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 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,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await nr(r).catch(()=>null))await ha(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await ei(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await ti(sr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=la(e),n=Nu(t),i=da();await Uu(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=fa(this.currentLogFile,"r+");ca(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(!Le()&&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(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()?pe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Le())return!1;let e=typeof Ce.env.NO_COLOR<"u",t=Ce.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof Ce.stderr<"u"&&Ce.stderr.isTTY||typeof Ce.stdout<"u"&&Ce.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,l=(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=Ce.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} ${pe.cyan(i)}`;if(!o)return f.trim();let u=l(f).trim().length,a=l(t).length,m=Math.max(1,c-2-u-a);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let l=t[n++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return 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=pe.underline(pe.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\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)=>pe.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>pe.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>pe.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>pe.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>pe.strikethrough(n)),t}supportsHyperlinks(){if(Le())return!1;let e=Ce.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=Ce.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Bu(t)||t.startsWith("./")||t.startsWith("../"))t=_u(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){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let a=this.options.showIcons===!1?"":rd[e],m=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:pe.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:pe.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.error(y),l){let w=l.split(`
|
|
99
|
-
`);for(let
|
|
100
|
-
`;if(
|
|
101
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};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()&&!Le()&&
|
|
102
|
-
`);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Le()&&
|
|
103
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?
|
|
104
|
-
`),c=Math.max(...
|
|
105
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Le())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${
|
|
106
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
107
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Le()||!
|
|
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(o))console.error(this.formatConsoleMessage({timestamp:i,message:de.gray(` ${S}`),level:e,showTimestamp:!1}))}break}}else if(!Le()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
100
|
+
`;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,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};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()&&!Le()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Le()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!Le()&&ye.stdout.isTTY)ye.stdout.write(`
|
|
102
|
+
`);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Le()&&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),s=`${e} completed in ${i}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
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:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Le())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 Pi(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(Le())throw Error("createReadStream is not supported in browser environments");if(!ti(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return fa(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=$t.isBuffer(e)?e:$t.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),a=Wu("aes-256-gcm",r,i);a.setAuthTag(s);let c=a.update(o),f=a.final(),u=c.length+f.length,h=$t.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 Le()}isServerMode(){return!Le()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=i.split(`
|
|
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(!Le())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
105
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Le())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 o=/%([sdijfo%])/g,a=0;if(r=e.replace(o,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?de.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${de.blue("\u25D0")} `;console.error(`${a}${o} ${de.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
106
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}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,s=de.green("\u2501".repeat(n)),o=de.gray("\u2501".repeat(i)),a=`[${s}${o}]`,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(`
|
|
107
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Le()||!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(Le()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ri(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=ar(this.config.logDirectory,n);if(e.before)try{if((await or(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 ii(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 sd(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!i(o))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class cs{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose: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:s,customParsers:o,verbose:a,configName:e}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return es.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,s]of Object.entries(e)){let o=[...t,i],a=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${a.join("_")}`,f=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=ni.env[c]||(f?ni.env[f]:void 0);if(u!==void 0){if(n.verbose){let h=ni.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof s,c,n.customParsers,n.configName)}catch(h){if(h instanceof ls)throw h;throw fr.envVar(c,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw fr.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(ni.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:a,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
108
108
|
|
|
109
109
|
`;for(let n of e)r+=`${n.key}
|
|
110
110
|
`,r+=` Type: ${n.type}
|
|
@@ -116,143 +116,142 @@ export type ConfigOf = Config
|
|
|
116
116
|
`;r+=`| Variable | Type | Description | Example |
|
|
117
117
|
`,r+=`|----------|------|-------------|----------|
|
|
118
118
|
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
119
|
-
`;return r}}function nd(e,t,r={}){return il(e,t,r,new WeakMap)}function il(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 l=o(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return nl(e,t,i,n);if(!at(t)||!at(e))return t;return ld(e,t,r,n)}function nl(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 sd(e,t);case"smart":return od(e,t,n);default:return t}return t}function sd(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Xn(i,n)))r.push(n);return r}function od(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(at(t[0])&&at(e[0]))return ad(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 ad(e,t,r){let n=[...t];for(let i of e){if(!at(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let l of s)if(l in i){if(n.find((c)=>at(c)&&(l in c)&&c[l]===i[l])){o=!0;break}}if(!o)n.push(i)}return n}function ld(e,t,r,n){let i=t;if(at(i)&&n.has(i))return n.get(i);let s={...e};if(at(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let l=i[o],c=s[o];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){s[o]=l;continue}if(at(l)&&at(c))s[o]=il(c,l,r,n);else if(Array.isArray(l)||Array.isArray(c))s[o]=nl(c,l,r.arrayMergeMode||"smart",n);else s[o]=l}return s}function sl(e,t,r="replace"){return nd(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Xn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Xn(e[r],t[r]))return!1;return!0}if(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(!Xn(e[i],t[i]))return!1}return!0}return!1}function at(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ol{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:l=!1}=r;if(i){let f=mi.getWithFileCheck("file",e);if(f){if(l)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),a=u.default||u,m="default"in u,y=Object.keys(u).length>0;if(!m&&!y)throw new Ei(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof a!=="object"||a===null||Array.isArray(a))throw new Ei(e,Error("Configuration must export a valid object"),"unknown");let w={config:sl(t,a,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)mi.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?lr.configLoad(e,f):lr.configLoad(e,Error(String(f)))}};if(o)return Qn.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(Fn(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 id(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 s of i)for(let o of this.extensions){let l=Fn(e,`${s}${o}`);if(await this.checkFileAccess(l))n.push(l)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let l=Fn(e,o);if(await this.checkFileAccess(l))n.push(l)}}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"),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 al{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:l=!0,verbose:c=!1}=r,f=async()=>{let u=[],a=[],m={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:l,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,m);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],m);else return this.validateWithJSONSchema(e,t,m)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:a}}};if(l)return await Qn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Vu(t))throw new Si(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 Si(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,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(o)){if(n.push({path:r,message:`Expected type ${l.join(" or ")}, got ${o}`,expected:l.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 l=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,l,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 l of t.required)if(!(l in o)){if(n.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[l,c]of Object.entries(t.properties))if(l in o){let f=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(o[l],c,f,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!l.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),l=this.validateWithRule(o,s,s.path);if(n.push(...l),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:cd},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function fd(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 ll{fileLoader=new ol;envProcessor=new ls;validator=new al;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 l;try{l=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;l={...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"),a=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),m=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(m||u))throw c;if(a&&(!f||!m))l={...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)l={...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 l={...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(l.config,i,s,o.name);if(r?.enabled&&l)this.cacheResult(o.name||"",l,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)wt.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);l.metrics=c}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let c=Date.now()-t;throw wt.error(`Configuration loading failed after ${c}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:l,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,a=s||Ai.cwd(),m=[],y=await this.loadLocalConfiguration(n,i,a,o,l,f,u,c,r);if(y)return m.push(...this.getLocalSearchPaths(n,i,a,o)),this.finalizeResult(y,m,c,n,u);let w=await this.loadHomeConfiguration(n,i,l,f,u,c);if(w)return m.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,m,c,n,u);let C=await this.loadPackageJsonConfiguration(n,i,a,l,f,u,c);if(C)return m.push(st(a,"package.json")),this.finalizeResult(C,m,c,n,u);if(m.push(...this.getAllSearchPaths(n,i,a,o)),t)throw lr.configNotFound(n,m,i);return{...await this.applyEnvironmentVariables(n,l,c,u),warnings:[`No configuration file found for "${n}"${fd(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,l,c){let f=l?si(e,i,o):i,u=this.getLocalDirectories(r,n);for(let a of u){if(o)wt.info(`Searching for configuration in: ${a}`);let m=this.fileLoader.generateConfigPaths(e,a,t),y=await this.fileLoader.tryLoadFromPaths(m,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(o)wt.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?si(e,r,i):r,l=[st(qt(),".config",e),st(qt(),".config"),qt()];for(let c of l){if(i)wt.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)wt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let l=o?si(e,n,s):n;try{let c=st(r,"package.json");if(!iu(c))return null;let f={};try{f=JSON.parse(nu(c,"utf8"))}catch(m){if(s)wt.warn("Failed to parse package.json:",[m instanceof Error?m:Error(String(m))]);return null}let u=f[e],a=e;if(!u&&t){let m=Array.isArray(t)?t:[t];for(let y of m){if(!y)continue;if(f[y]){u=f[y],a=y;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)wt.success(`Configuration loaded from package.json: ${a}`);return{config:sl(l,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)wt.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:si(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 lr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return mi.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);mi.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),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[st(qt(),".config",e),st(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 si(e,t,r=!1){let n=new ls,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,l=[]){let c={...o};for(let[f,u]of Object.entries(o)){let a=[...l,f],m=[`${i}_${a.join("_").toUpperCase()}`,`${i}_${a.map((C)=>C.toUpperCase()).join("")}`,`${i}_${a.map((C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,w;for(let C of m)if(y=Ai.env[C],y!==void 0){w=C;break}if(y!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let C=Number(y);if(!Number.isNaN(C))c[f]=C}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((C)=>C.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,a)}return c}return s(t)}var mi,Qn,Hu,ju=(e)=>e,Zu=(e,t)=>{for(var r in t)Hu(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Ku.bind(t,r)})},Yu=(e,t)=>()=>(e&&(t=e(e=0)),t),ka,Ba,ar,br,_a,vh,bh,ma,ai,Hn,je,Ee,Eh,ga,Sh,ya,Ah,xh,Nn,Th,Ca,wa,Wn,Oh,Rh,Ph,kh,li,Ua,Mh,Ke,Dh,Ih,$a,ci,jn,We,fe,Fh,va,Nh,ba,Wh,Lh,Ln,Gh,Ea,Sa,Bh,Gn,_h,Uh,Vh,Hh,jh,fi,Va,Kh,Zh="0.15.6",et,$i,$r,Kn,Zn,vi,Yn,Jn,vr,qn,zn,Mt,Ha,ja,ft,Et,Ka,Za,Yh,qh,Ya,bi,My,Be,pe,Dy,Xh,Iy,Qh,Fy,Ny,Aa,Wy,ed,td,Ly,xa,Gy,By,_y,Uy,Vy,Bn,rd,Hy,ut,qa,Ei,za,Xa,as,Qa,el,Si,tl,rl,lr,cd,wt,jy,Ky,Zy,ud,cl;var fl=de(()=>{mi=new Ra,Qn=new Pa,Hu=Object.defineProperty;ka={};Zu(ka,{withErrorRecovery:()=>Ia,tryLoadConfig:()=>yh,loadConfigWithResult:()=>mh,loadConfig:()=>Ga,isRetryableError:()=>ch,isConfigNotFoundError:()=>lh,isBunfigError:()=>Fa,globalPerformanceMonitor:()=>br,globalCache:()=>ar,getEnvOrDefault:()=>fh,generateConfigTypes:()=>Ch,defaultGeneratedDir:()=>Za,defaultConfigDir:()=>Ka,deepMergeWithArrayStrategy:()=>ns,deepMerge:()=>Na,createLibraryConfig:()=>wh,config:()=>gh,bunfigPlugin:()=>$h,applyEnvVarsToConfig:()=>Cr,TypeGenerationError:()=>Jn,SchemaValidationError:()=>vr,PluginError:()=>zn,PerformanceMonitor:()=>ts,FileSystemError:()=>Yn,ErrorFactory:()=>Mt,EnvVarError:()=>vi,EnvProcessor:()=>xi,ConfigValidator:()=>ss,ConfigValidationError:()=>Kn,ConfigNotFoundError:()=>$i,ConfigMergeError:()=>Zn,ConfigLoader:()=>os,ConfigLoadError:()=>$r,ConfigFileLoader:()=>Ti,ConfigCache:()=>es,CacheUtils:()=>_a,BunfigError:()=>et,BrowserConfigError:()=>qn,ArrayMergeStrategies:()=>Ha});Yh=Yu(async()=>{Ba=import.meta.require,ar=new es,br=new ts,_a={createKey:Ju,isEquivalent:qu,estimateMemoryUsage:zu},vh=di(Un.cwd(),"config"),bh=di(Un.cwd(),"src/generated"),ma=hi.env.CLARITY_LOG_DIR||fu(eh(),"logs"),ai={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ma,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Hn=await th(),je={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=je,Eh=je.red,ga=je.green,Sh=je.yellow,ya=je.blue,Ah=je.magenta,xh=je.cyan,Nn=je.white,Th=je.gray,Ca=je.bgRed,wa=je.bgYellow,Wn=je.bold,Oh=je.dim,Rh=je.italic,Ph=je.underline,kh=je.reset,li={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ua={debug:"\uD83D\uDD0D",info:ya("\u2139"),success:ga("\u2713"),warning:wa(Nn(Wn(" WARN "))),error:Ca(Nn(Wn(" ERROR ")))},Mh=new yi("stacks"),Ke=new yi("bunfig",{showTags:!0}),Dh=Je(wr.cwd(),"config"),Ih=Je(wr.cwd(),"src/generated"),$a=ui.env.CLARITY_LOG_DIR||lu(sh(),"logs"),ci={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$a,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 oh(),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"},fe=We,Fh=We.red,va=We.green,Nh=We.yellow,ba=We.blue,Wh=We.magenta,Lh=We.cyan,Ln=We.white,Gh=We.gray,Ea=We.bgRed,Sa=We.bgYellow,Bh=We.bgGray,Gn=We.bold,_h=We.dim,Uh=We.italic,Vh=We.underline,Hh=We.strikethrough,jh=We.reset,fi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Va={debug:"\uD83D\uDD0D",info:ba("\u2139"),success:va("\u2713"),warning:Sa(Ln(Gn(" WARN "))),error:Ea(Ln(Gn(" ERROR ")))},Kh=new wi("stacks"),et=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}`}},$i=class extends et{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 et{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Kn=class extends et{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Zn=class extends et{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}},vi=class extends et{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})}},Yn=class extends et{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Jn=class extends et{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},vr=class extends et{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},qn=class extends et{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})}},zn=class extends et{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Mt={configNotFound(e,t,r){return new $i(e,t,r)},configLoad(e,t,r){return new $r(e,t,r)},configValidation(e,t,r){return new Kn(e,t,r)},configMerge(e,t,r,n){return new Zn(e,t,r,n)},envVar(e,t,r,n){return new vi(e,t,r,n)},fileSystem(e,t,r){return new Yn(e,t,r)},typeGeneration(e,t,r){return new Jn(e,t,r)},schemaValidation(e,t,r){return new vr(e,t,r)},browserConfig(e,t,r,n){return new qn(e,t,r,n)},plugin(e,t,r){return new zn(e,t,r)}},Ha={replace:"replace",concat:"concat",smart:"smart"},ja=/^https?:\/\//,ft=new wi("bunfig",{showTags:!0}),Et=new os,Ka=qe(Wt.cwd(),"config"),Za=qe(Wt.cwd(),"src/generated")});qh=pi.env.CLARITY_LOG_DIR||Mu(Jh(),"logs"),Ya={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:qh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bi={...Ya},My=(async()=>{try{let{loadConfig:e}=await Yh().then(()=>ka),t=await e({name:"clarity",alias:"logging",defaultConfig:Ya,cwd:pi.cwd()});if(t)Object.assign(bi,t)}catch{}return bi})();Be={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"},pe=Be,Dy=Be.red,Xh=Be.green,Iy=Be.yellow,Qh=Be.blue,Fy=Be.magenta,Ny=Be.cyan,Aa=Be.white,Wy=Be.gray,ed=Be.bgRed,td=Be.bgYellow,Ly=Be.bgGray,xa=Be.bold,Gy=Be.dim,By=Be.italic,_y=Be.underline,Uy=Be.strikethrough,Vy=Be.reset,Bn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},rd={debug:"\uD83D\uDD0D",info:Qh("\u2139"),success:Xh("\u2713"),warning:td(Aa(xa(" WARN "))),error:ed(Aa(xa(" ERROR ")))};Hy=new Oi("stacks");ut=class ut 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}`}};qa=class qa extends ut{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})}};Ei=class Ei extends ut{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}};za=class za extends ut{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Xa=class Xa extends ut{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}};as=class as extends ut{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})}};Qa=class Qa extends ut{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}};el=class el extends ut{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}};Si=class Si extends ut{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})}};tl=class tl extends ut{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})}};rl=class rl extends ut{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}};lr={configNotFound(e,t,r){return new qa(e,t,r)},configLoad(e,t,r){return new Ei(e,t,r)},configValidation(e,t,r){return new za(e,t,r)},configMerge(e,t,r,n){return new Xa(e,t,r,n)},envVar(e,t,r,n){return new as(e,t,r,n)},fileSystem(e,t,r){return new Qa(e,t,r)},typeGeneration(e,t,r){return new el(e,t,r)},schemaValidation(e,t,r){return new Si(e,t,r)},browserConfig(e,t,r,n){return new tl(e,t,r,n)},plugin(e,t,r){return new rl(e,t,r)}};cd=/^https?:\/\//;wt=new Oi("bunfig",{showTags:!0});jy=new ll;Ky=st(Ai.cwd(),"config"),Zy=st(Ai.cwd(),"src/generated"),ud={cwd:ru.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},cl=ud});function Dt(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 hl(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},s=0,o=0,l=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),a=e.charCodeAt(f+1);if(l!==-1){if(u===42&&a===47)r.push({start:l,end:f+2}),l=-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&&a===42){l=f,f++;continue}if(u===47&&a===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 m=e[f];if(m==="("||m==="["||m==="{")n.push({char:m,offset:f});else if(i[m]){let y=n.pop();if(!y||y.char!==i[m])t.push({...Dt(e,f),message:`Unexpected closing delimiter ${m}`,code:"DTSX1004"})}}if(s)t.push({...Dt(e,o),message:"Unterminated string literal",code:"DTSX1002"});if(l!==-1)t.push({...Dt(e,l),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...Dt(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 a of e.matchAll(f)){if(r.some((m)=>a.index>=m.start&&a.index<m.end))continue;t.push({...Dt(e,a.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((a)=>f.index>=a.start&&f.index<a.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...Dt(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...dd(e,r)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function dd(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,l=-1;for(let u=o+1;u<e.length;u++){if(n(u))continue;let a=e[u];if(a==="{"){l=-2;break}if(a==="}"){l=u;break}}if(l<0)continue;let c=e.slice(o+1,l);if(!c.trim())continue;let f=o+1;for(let u of c.split(",")){let a=u.trim();if(a){let m=f+u.indexOf(a);if(a.includes(";"))r.push({...Dt(e,m),message:`Unexpected ';' in ${i[1]} clause \u2014 specifiers are separated by ','`,code:"DTSX1006"});else if(!hd.test(a))r.push({...Dt(e,m),message:`Invalid ${i[1]} specifier '${a}'`,code:"DTSX1006"})}f+=u.length+1}}return r}var ul,hd;var dl=de(()=>{ul=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,hd=new RegExp(`^(?:type\\s+)?${ul}(?:\\s+as\\s+${ul})?$`,"u")});var pl;var ml=de(()=>{pl=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 gl(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
|
-
`,n),
|
|
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
|
+
`,n),a=o===-1?e.length:o;r+=" ".repeat(a-n),n=a;continue}if(i==="/*"){let o=e.indexOf("*/",n+2),a=o===-1?e.length:o+2;for(let c=n;c<a;c++)r+=e[c]===`
|
|
121
121
|
`?`
|
|
122
|
-
`:" ";n=
|
|
122
|
+
`:" ";n=a;continue}let s=e[n];if(t.strings&&(s==='"'||s==="'"||s==="`")){let o=s;r+=" ",n++;while(n<e.length){if(e[n]==="\\"){r+=" ",n+=2;continue}if(e[n]===o){r+=" ",n++;break}r+=e[n]===`
|
|
123
123
|
`?`
|
|
124
|
-
`:" ",n++}continue}r+=s,n++}return r}function
|
|
124
|
+
`:" ",n++}continue}r+=s,n++}return r}function yd(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 Cd(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 s=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let a of s.split(",")){let c=a.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let o=/\{([\s\S]*?)\}/.exec(n);if(o)for(let a of o[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 wd(e){let t=new Set,r=(i)=>{for(let s of i.split(",")){let o=s.trim().split(/\s+|=/)[0]?.trim();if(o&&/^[A-Za-z_$][\w$]*$/.test(o))t.add(o)}},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 $d(e){let t=new Map,r=(i)=>{let s=1;for(let o=0;o<i&&o<e.length;o++)if(e.charCodeAt(o)===10)s++;return s},n=(i,s,o)=>{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(s),context:o.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 wl(e){let t=Cl(e),r=Cl(e,{strings:!1}),n=new Set([...yd(t),...Cd(r),...wd(t),...gl,...gd]),i=[];for(let[s,o]of $d(t)){if(n.has(s))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${s}\\b`).test(t))continue;i.push({name:s,line:o.line,context:o.context})}return i.sort((s,o)=>s.line-o.line||s.name.localeCompare(o.name))}var gd;var $l=he(()=>{yl();gd=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});import{join as C0,resolve as vd}from"path";import bd from"process";function fs(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function ki(e,t,r="lf"){let n=t.replace(/\r\n/g,`
|
|
125
125
|
`);if(!n.endsWith(`
|
|
126
126
|
`))n+=`
|
|
127
127
|
`;if(r==="crlf")n=n.replace(/\n/g,`\r
|
|
128
|
-
`);await
|
|
128
|
+
`);await fo(e,n)}async function vl(e){try{let t=e?.cwd||bd.cwd();return(await Cr(vd(t,e?.tsconfigPath||"tsconfig.json"),{allowCircular:!0}))?.isolatedDeclarations??!1}catch{return!1}}function bl(e,t){let r={isValid:!0,errors:[]};for(let n of pl(e))r.errors.push({line:n.line,column:n.column,message:n.message,code:n.code});for(let n of wl(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 El(e,t,r){if(e===t)return"";let n=e.split(`
|
|
129
129
|
`),i=t.split(`
|
|
130
|
-
`),s=new Map,o=new Map;for(let u=0;u<n.length;u++)s.set(n[u],(s.get(n[u])??0)+1);for(let u=0;u<i.length;u++)o.set(i[u],(o.get(i[u])??0)+1);let
|
|
131
|
-
`)}function
|
|
132
|
-
`),s=[];function o(
|
|
133
|
-
`).length;for(let
|
|
134
|
-
${
|
|
135
|
-
`}var
|
|
136
|
-
`),s=e.location.line-1;if(s>=0&&s<i.length){let o=Math.max(0,s-1),
|
|
137
|
-
`)}var
|
|
130
|
+
`),s=new Map,o=new Map;for(let u=0;u<n.length;u++)s.set(n[u],(s.get(n[u])??0)+1);for(let u=0;u<i.length;u++)o.set(i[u],(o.get(i[u])??0)+1);let a=[],c=[];for(let[u,h]of s){let l=h-(o.get(u)??0);for(let y=0;y<l;y++)a.push(u)}for(let[u,h]of o){let l=h-(s.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(`
|
|
131
|
+
`)}function Sl(e,t,r,n){let i=e.split(`
|
|
132
|
+
`),s=[];function o(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(`
|
|
133
|
+
`).length;for(let h=0;h<i.length;h++){if(i[h].trim()===""){s.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(o(C)+o(S)+o(x)+o(v)),a=0,c=l,f=0,s.push(y.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[n],mappings:s.join(";")}}function Al(e,t){return`${e}
|
|
134
|
+
${fs()}${t}
|
|
135
|
+
`}var xl=he(()=>{ml();$l();Ur();mn()});function Tl(e,t,r){let n={file:t,message:"Unknown error",code:Ar.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=Ar.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=Ar.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=Ar.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=Ar.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function Ol(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(`
|
|
136
|
+
`),s=e.location.line-1;if(s>=0&&s<i.length){let o=Math.max(0,s-1),a=Math.min(i.length-1,s+1);for(let c=o;c<=a;c++){let f=(c+1).toString().padStart(4," "),u=c===s?">":" ";if(r.push(` ${u} ${f} | ${i[c]}`),c===s&&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(`
|
|
137
|
+
`)}var Ar;var Rl=he(()=>{Ar={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 Td(e){switch(e){case"strict":return Sd;case"readonly":return Ad;case"simplified":return xd;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 kl{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...Ed);if(e.presets)for(let t of e.presets)this.rules.push(...Td(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(Od,"\\$&"),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,s=null;for(let o=0;o<this.compiled.length;o++){let{rule:a,regex:c}=this.compiled[o];if(a.condition){if(!s)s={type:e,...t};if(!a.condition(s))continue}if(c.lastIndex=0,c.test(i)){if(c.lastIndex=0,i=i.replace(c,a.replacement),c.lastIndex=0,!a.global)break}}if(this.cache.size>=Pl){let o=Math.ceil(Pl*0.1),a=0;for(let c of this.cache.keys()){if(a++>=o)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 Mi(e={rules:[]}){return new kl(e)}function Ml(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>`: ${t.map(i.trim(),r)}`)}var Ed,Sd,Ad,xd,Od,Pl=2048,b0,E0;var Dl=he(()=>{Ed=[{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}],Sd=[{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}],Ad=[{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}],xd=[{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}];Od=/[.*+?^${}()|[\]\\]/g;b0=Mi({rules:[]}),E0=Mi({rules:[],presets:["strict"]})});function xr(e){if(Rd)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 Rd;var us=he(()=>{Rd=typeof globalThis.Bun?.hash==="function"});import{existsSync as Tr,mkdirSync as Pd,readFileSync as ds,renameSync as kd,rmSync as Il,statSync as Fl,writeFileSync as Nl}from"fs";import{join as Wl,relative as Di,resolve as Md}from"path";class ps{cacheDir;manifestPath;manifest=null;configHash;constructor(e,t){this.cacheDir=Md(e.cwd,Ii),this.manifestPath=Wl(this.cacheDir,Dd),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(xr(JSON.stringify(r)))}hashString(e){return String(xr(e))}load(){try{if(!Tr(this.manifestPath))return!1;let e=ds(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==hs)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:hs,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!Tr(this.cacheDir))Pd(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{Nl(e,JSON.stringify(this.manifest,null,2)),kd(e,this.manifestPath)}finally{if(Tr(e))Il(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=Di(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=Fl(e),{mtimeMs:s,ctimeMs:o}=i;if(i.size!==n.sourceSize)return null;if(s!==n.sourceMtime||o!==n.sourceCtime){let a=ds(e,"utf-8");if(this.hashString(a)!==n.sourceHash)return null;n.sourceMtime=s,n.sourceCtime=o}return n.dtsContent}catch{return null}}update(e,t,r,n){if(!this.manifest)this.manifest={version:hs,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=Di(n,e),s,o,a;try{let c=Fl(e);s=c.mtimeMs,o=c.ctimeMs,a=c.size}catch{s=Date.now(),o=s,a=Buffer.byteLength(t)}this.manifest.entries[i]={sourcePath:i,sourceHash:this.hashString(t),sourceMtime:s,sourceCtime:o,sourceSize:a,dtsContent:r,dtsHash:this.hashString(r),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let r=Di(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(Tr(this.manifestPath))Il(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)=>Di(t,i)));for(let i of Object.keys(this.manifest.entries))if(!n.has(i))delete this.manifest.entries[i],r++;return r}}function Ll(e){let t=Wl(e,".gitignore");try{let r="";if(Tr(t))r=ds(t,"utf-8");if(!r.split(/\r?\n/).some((n)=>n.trim()===Ii||n.trim()===`${Ii}/`)){let n=r.trimEnd(),i=`${n}${n?`
|
|
138
138
|
|
|
139
139
|
`:""}# dtsx cache
|
|
140
|
-
${
|
|
141
|
-
`;
|
|
140
|
+
${Ii}/
|
|
141
|
+
`;Nl(t,i)}}catch{}}var hs=3,Ii=".dtsx-cache",Dd="manifest.json";var Gl=he(()=>{us()});function Tt(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
142
|
`;return`${n.trim()}
|
|
143
143
|
`}let r="";for(let n=0;n<e.length;n++){if(n>0)r+=`
|
|
144
144
|
`;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 o=
|
|
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
|
|
149
|
-
${
|
|
145
|
+
`}function bs(e){return e.replaceAll("*/","*\\/")}function gs(e){return jl(e).replace(/\n[ \t]*(?=\n)/g,"")}function jl(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 Ss(){Gi=!0,Qe=null}function As(){Gi=!1;let e=Qe;return Qe=null,e}function xs(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 Id(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 ms(e,t){let r=0,n=0;while((n=e.indexOf(t,n))!==-1)r++,n+=t.length;return r}function Bl(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 Fi(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&&Bl(t.charCodeAt(n)))n++;let i=t.slice(1,n),s=t.charCodeAt(n);if(s>32&&s!==62&&s!==47)return!1;if(t.endsWith("/>"))return!0;let o=t.lastIndexOf("</");if(o===-1)return!1;let a=o+2;while(a<t.length&&Bl(t.charCodeAt(a)))a++;return t.slice(o+2,a)===i&&t.charCodeAt(a)===62&&a===t.length-1}function Ni(e){let t=e.length,r=!1;for(let o=1;o<t;o++)if(e.charCodeAt(o)<=32&&e.charCodeAt(o-1)<=32){r=!0;break}if(!r)for(let o=0;o<t;o++){let a=e.charCodeAt(o);if(a===10||a===13||a===9){r=!0;break}}if(!r)return e;let n=[],i=-1,s=!1;for(let o=0;o<t;o++)if(e.charCodeAt(o)<=32){if(!s){if(i>=0)n.push(e.substring(i,o));n.push(" "),s=!0,i=-1}}else{if(s||i<0)i=o;s=!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>=Es)return"unknown";let i=e.trim();if(Fi(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(`
|
|
146
|
+
`)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let o=Fd(i);if(o!==null){if(o==="string"||!t)return"string";return o}}if(xs(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 ws(i,t,n+1);if(i.startsWith("{")&&i.endsWith("}"))return Zd(i,t,n+1);if(i.startsWith("class ")||i.startsWith("class{"))return Kd(i);if(i.startsWith("new "))return Hd(i);if(i.endsWith("as const")){let o=i.slice(0,-8).trim();if(o.startsWith("[")&&o.endsWith("]")){let a=o.slice(1,-1).trim();if(!a)return"readonly []";let c=Wi(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(o,!0,r,n+1)}if(Li(i)!==-1||i.startsWith("function")||i.startsWith("async"))return ec(i,r,n,t);if(i.startsWith("`")&&i.endsWith("`"))return Vd(i,t);if(i.startsWith("Promise."))return ql(i,t,n);if(i.startsWith("await "))return"unknown";if(i.charCodeAt(i.length-1)===110&&i.length>1&&Id(i)){if(t)return i;return"bigint"}if(i.startsWith("Symbol(")||i==="Symbol.for")return"symbol";let s=zl(i);if(s!==null)return s;if(Zl(i))return"boolean";if(Gd(i))return"number";return"unknown"}function _l(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return Nt(e,0,t)===e.length}function Fd(e){if(_l(e))return e;let t=Nd(e);if(t.length<2)return null;let r=!1,n=!0,i="";for(let s of t){let o=s.trim();if(_l(o))r=!0,i+=Wd(o);else n=!1}if(n)return Ld(i);if(r)return"string";return null}function Nd(e){let t=[],r=0,n=0,i=0;while(i<e.length){let s=e.charCodeAt(i);if(s===39||s===34||s===96){i=Nt(e,i,s);continue}if(s===40||s===91||s===123)r++;else if(s===41||s===93||s===125)r--;else if(s===43&&r===0)t.push(e.slice(n,i)),n=i+1;i++}return t.push(e.slice(n)),t}function Wd(e){return e.slice(1,-1).replace(/\\(.)/g,(t,r)=>{if(r==="n")return`
|
|
147
|
+
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function Ld(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Gd(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 Zl(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=Nt(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 Bd(e,t=!1,r=0){return Ie(e,t,!0,r)}function hr(e,t=!1,r=""){let n=Yl(r),i=[],s=!1,o=0;while(o<e.length){let c=e.charCodeAt(o);if(c===34||c===39||c===96){o=Nt(e,o,c);continue}if(c===47&&e.charCodeAt(o+1)===47){o+=2;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(c===47&&e.charCodeAt(o+1)===42){let f=e.indexOf("*/",o+2);o=f===-1?e.length:f+2;continue}if(e.startsWith("function",o)&&ys(e,o,8)||e.startsWith("class",o)&&ys(e,o,5)){let f=Ud(e,o);if(f!==-1){o=Cs(e,f);continue}}if(c===61&&e.charCodeAt(o+1)===62){let f=o+2;while(f<e.length&&e.charCodeAt(f)<=32)f++;if(e.charCodeAt(f)===123){o=Cs(e,f);continue}}if(e.startsWith("return",o)&&(o===0||!xt(e.charCodeAt(o-1)))&&!xt(e.charCodeAt(o+6))){o+=6;let f=!1;while(o<e.length&&e.charCodeAt(o)<=32){let x=e.charCodeAt(o);if(x===10||x===13)f=!0;o++}if(f||o>=e.length||e.charCodeAt(o)===59||e.charCodeAt(o)===125){s=!0;continue}let u=o,h=0,l=0,y=0;while(o<e.length){let x=e.charCodeAt(o);if(x===34||x===39||x===96){o=Nt(e,o,x);continue}if(x===47&&e.charCodeAt(o+1)===47){if(h===0&&l===0&&y===0)break;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(x===47&&e.charCodeAt(o+1)===42){let v=e.indexOf("*/",o+2);o=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=o+1;while(v<e.length&&e.charCodeAt(v)<=32)v++;if(e.startsWith("return",v)&&!xt(e.charCodeAt(v+6)))break}o++}let C=e.slice(u,o).trim(),S=gs(Bt(C,n));if(!i.includes(S))i.push(S);continue}o++}if(s&&!i.includes("undefined"))i.push("undefined");let a=i.includes("unknown")?"unknown":i.length===0?"void":i.join(" | ");return t&&!a.startsWith("Promise<")?`Promise<${a}>`:a}function Yl(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=0,i=0,s=0;for(let o=0;o<=r.length;o++){let a=r.charCodeAt(o);if(a===40||a===91||a===123)i++;else if(a===41||a===93||a===125)i--;else if(a===60)s++;else if(a===62&&r.charCodeAt(o-1)!==61&&s>0)s--;if(o!==r.length&&(a!==44||i!==0||s!==0))continue;let c=r.slice(n,o).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(Bi(u)&&h)t.set(u,h)}n=o+1}return t}function Bt(e,t){let r=e.trim();while(Jl(r))r=r.slice(1,-1).trim();if(Fi(r))return"JSX.Element";if(r.startsWith("await ")){let s=Bt(r.slice(6),t);return s.startsWith("Promise<")&&s.endsWith(">")?s.slice(8,-1):s}if(t.has(r))return t.get(r);if(r.startsWith("!"))return"boolean";if(r.startsWith("fetch("))return"Promise<Response>";let n=_d(r);if(n){let s=Bt(n.whenTrue,t),o=Bt(n.whenFalse,t);return s===o?s:`${s} | ${o}`}if(Zl(r))return"boolean";let i=0;for(let s=r.length-1;s>=0;s--){let o=r.charCodeAt(s);if(o===41||o===93||o===125)i++;else if(o===40||o===91||o===123)i--;else if(i===0&&(o===43||o===45||o===42||o===47||o===37)){let a=Bt(r.slice(0,s),t),c=Bt(r.slice(s+1),t);if(o===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,(s)=>{let o=s.slice(7);return t.get(o)??"unknown"})}function Jl(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 _d(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 ys(e,t,r){return(t===0||!xt(e.charCodeAt(t-1)))&&!xt(e.charCodeAt(t+r))}function Ud(e,t){for(let r=t;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=Nt(e,r,n)-1;continue}if(n===123)return r;if(n===59)return-1}return-1}function Cs(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=Nt(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 s=e.indexOf("*/",n+2);n=s===-1?e.length:s+2;continue}if(i===123)r++;else if(i===125)r--;n++}return n}function Nt(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=Cs(e,n+1);continue}if(n++,i===r)break}return n}function Vd(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
|
|
148
|
+
`)||e.includes("\r"))return"string";return e}function Hd(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&&(xt(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let i=e.slice(r,t);{let s=e.slice(t),o=s;if(s.startsWith("<")){let c=0,f=-1;for(let u=0;u<s.length;u++)if(s[u]==="<")c++;else if(s[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=s.slice(0,f+1);o=s.slice(f+1);let h=o.indexOf("(");if(h!==-1){let l=0,y=-1;for(let C=h;C<o.length;C++)if(o[C]==="(")l++;else if(o[C]===")"){if(l--,l===0){y=C;break}}if(y!==-1){if(o.slice(y+1).trimStart().startsWith("."))return"unknown"}}return`${i}${u}`}}let a=o.indexOf("(");if(a!==-1){let c=0,f=-1;for(let u=a;u<o.length;u++)if(o[u]==="(")c++;else if(o[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(o.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(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 Kd(e){return"{ new (...args: any[]): any }"}function ql(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 s=e.slice(n+1,i).trim(),o=Wi(s),a=[];for(let c=0;c<o.length;c++){let f=o[c].trim();if(f.startsWith("Promise.resolve(")){let u=ql(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 ws(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(r>=Es)return"unknown[]";let i=Wi(n),s=!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"){s=!0;break}}if(s){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=Wi(x),B=[];for(let W=0;W<v.length;W++)B.push(Ie(v[W].trim(),!0,!1,r+1));l.push(`readonly [${B.join(", ")}]`)}else l.push(Ie(S,!0,!1,r+1))}else if(C.startsWith("[")&&C.endsWith("]"))l.push(ws(C,!0,r+1));else l.push(Ie(C,!0,!1,r+1))}return`readonly [
|
|
149
|
+
${l.join(` |
|
|
150
150
|
`)}
|
|
151
|
-
]`}let o=
|
|
152
|
-
`:"",x=
|
|
153
|
-
${x}: ${
|
|
151
|
+
]`}let o=Gi&&!t,a=[],c=[];for(let l of i){let y=l.trim(),C=Qe;if(Qe=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(ws(y,t,r+1));else a.push(Bd(y,t,r+1));if(o)c.push(Qe);Qe=C}if(o)if(vs(e))Qe=Ni(e);else{let l=[];for(let y=0;y<i.length;y++){let C=i[y].trim();if(C.endsWith("as const"))continue;if($s(C)||C==="null"||C==="undefined")l.push(C);else if(C.startsWith("[")&&vs(C))l.push(Ni(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)Qe=`[${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(!(xs(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 Wi(e){let t=[],r=0,n=0,i=!1,s=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(!i&&(c===34||c===39||c===96))i=!0,s=c;else if(i&&c===s&&(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 o=e.substring(r).trim();if(o)t.push(o);return t}function $s(e){if(xs(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function jd(e){return e==="number"||e==="string"||e==="boolean"}function vs(e){let t=!1,r=0,n=e.length;for(let i=0;i<n;i++){let s=e.charCodeAt(i);if(t){if(s===92){i++;continue}if(s===r)t=!1;continue}if(s===34||s===39||s===96){t=!0,r=s;continue}if(s===61&&i+1<n&&e.charCodeAt(i+1)===62)return!1;if(s>=97&&s<=122){let o=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(o,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 Zd(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"{}";if(r>=Es)return"Record<string, unknown>";let i=zd(n),s=[],o=[],a=Gi&&!t,c=[];for(let[h,l]of i){let{comments:y,key:C}=Ql(h),S=y?`${y}
|
|
152
|
+
`:"",x=C,v=!1;if(C==="..."){let H=l.trim(),j=ur(H)?`typeof ${H}`:Ie(H,t,!1,r+1);if(j!=="unknown")o.push(j);if(a&&(ur(H)||H.startsWith("{")))c.push(`...${Ni(H)}`);continue}let B=Qe;Qe=null;let W,P=l.trim();if(P===C&&Bi(P))W=`typeof ${P}`;else if(ep(P)){v=!0;let H=tp(C);if(H){x=H.name;let j="";if(P.startsWith("async "))j="async ";if(P.charCodeAt(j.length)===42)j+="*";W=Hl(H.name,j+H.typeParams+P.slice(j.length))}else W=Hl(C,P)}else{if(W=Ie(l,t,!1,r+1),W==="unknown"&&ur(P))W=`typeof ${P}`;if(W.includes("=>")||W.includes("function")||W.includes("async"))W=Ul(W)}let F=Qe;Qe=B;let I=l.trim(),k=Xd(C);if(k){let H=Qd(k.kind,k.name,W);if(H){s.push(`${S}${H}`);continue}}if(!t&&jd(W)&&$s(I))s.push(`${S}/** @defaultValue ${bs(I)} */
|
|
153
|
+
${x}: ${W}`);else s.push(`${S}${x}: ${W}`);if(a){let H=jl(x);if(I.endsWith("as const"));else if($s(I))c.push(`${H}: ${I}`);else if(I.startsWith("[")&&vs(I))c.push(`${H}: ${Ni(I)}`);else if(I.startsWith("{")){if(F)c.push(`${H}: ${F}`)}else if(v)c.push(`${H}: ${gs(Ul(W))}`);else if(!I.startsWith("[")&&(I.includes("=>")||I.startsWith("function")||I.startsWith("async"))){let j=ec(I,!1,0,!0);c.push(`${H}: ${gs(j)}`)}}}if(a&&c.length>0){let h=r>0?(r-1)/2:0,l=`{ ${c.join(", ")} }`;if(l.length<=80)Qe=l;else{let y=" ".repeat((h+1)*2),C=" ".repeat(h*2);Qe=`{
|
|
154
154
|
${y}${c.join(`,
|
|
155
155
|
${y}`)}
|
|
156
|
-
${
|
|
156
|
+
${C}}`}}let f=s.length>0?`{
|
|
157
157
|
${s.join(`;
|
|
158
158
|
`)}
|
|
159
|
-
}`:"{}";if(o.length===0)return f;let u=o[0];for(let
|
|
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
|
-
`))
|
|
164
|
-
${n}`:n,n]);else if(n.startsWith("...")&&n.length>3)e.push(["...",n.slice(3).trim()])}function
|
|
165
|
-
`){let i=r,s=n;while(i<s&&(e[i]===" "||e[i]==="\t"||e[i]==="\r"))i++;while(s>i&&(e[s-1]===" "||e[s-1]==="\t"||e[s-1]==="\r"))s--;let o=e.slice(i,s);if(r=n+1,o.startsWith("///")){if(o.indexOf("<")===-1)continue;if(
|
|
159
|
+
}`:"{}";if(o.length===0)return f;let u=o[0];for(let h=1;h<o.length;h++)u=`Omit<${u}, keyof ${o[h]}> & ${o[h]}`;return s.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function Bi(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(!xt(e.charCodeAt(r)))return!1;return!0}function ur(e){let t=e.split(".");return t.length>0&&t.every(Bi)}function Yd(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 s=it(e,n,"<",">");if(s!==-1)n=s}}return-1}function zl(e){if(e.length<3||!e.endsWith(")"))return null;let t=Yd(e);if(t===-1||it(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,s=!1,o=r.indexOf("<");if(o!==-1){if(it(r,o,"<",">")!==r.length-1)return null;i=r.slice(0,o).trim(),s=!0}if(!ur(i))return null;let a=e.slice(t+1,-1).trim(),c=Li(a)!==-1||a.startsWith("function")||a.startsWith("async function"),f=ur(a),u=!c&&a.endsWith(")")&&zl(a)!==null;if(!s&&!n&&!c&&!f&&!u)return null;let h=`ReturnType<typeof ${r}>`;return n?`${h} | undefined`:h}function Ul(e){let t=e.split(`
|
|
160
|
+
`).map((f)=>Xl(f)).join(`
|
|
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(!xt(f)&&!xt(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let n=t.indexOf("(");if(n!==-1){let f=it(t,n,"(",")");if(f!==-1){let u=t.slice(n,f+1),h=_t(u);t=t.slice(0,n)+h+t.slice(f+1)}}let i=t.length,s="",o=[],a=!1,c=!1;for(let f=0;f<i;f++){let u=t.charCodeAt(f);if(u===123||u===40)o.push(u);else if(u===125||u===41)o.pop();if(u<=32){if(a=!0,u===10||u===13)c=!0;continue}if(a&&s.length>0){let h=(o.length>0?o[o.length-1]:0)===123;if(c&&h){let l=s.charCodeAt(s.length-1),y=l===59||l===44||l===123||u===125,C=s.length>=2&&s.charCodeAt(s.length-1)===47&&s.charCodeAt(s.length-2)===42;if(!y&&!C)s+="; ";else s+=" "}else s+=" "}a=!1,c=!1,s+=t[f]}return s.trim()}function xt(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function _t(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 s=!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,B=S+1<i.length?i.charCodeAt(S+1):0;if(v!==61&&v!==33&&v!==60&&v!==62&&B!==61&&B!==62){s=!0;break}}}}if(!s)return t;let o=[],a=[],c=0,f=0,u=!1,h=0;for(let C=0;C<=i.length;C++){if(C===i.length){o.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){o.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 o){let S=C.trim();if(!S){l.push(C);continue}if(S.startsWith("//"))continue;let x=Xl(S),v=C.slice(0,C.length-C.trimStart().length);l.push(v+Jd(x))}let y=l[0]||"";for(let C=1;C<l.length;C++)y+=(a[C-1]||", ")+l[C];return n?`(${y})`:y}function Xl(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 Jd(e){if(e.startsWith("..."))return e;let t=-1,r=-1,n=0,i=!1,s=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(i){if(c===92){a++;continue}if(c===s)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,s=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 o=r!==-1;if(t!==-1&&(r===-1||t<r)){let a=e.slice(0,t).trim(),c=r!==-1?e.slice(t+1,r).trim():e.slice(t+1).trim(),f=o&&!a.endsWith("?")?"?":"";return`${a}${f}: ${c}`}else if(r!==-1){let a=e.slice(0,r).trim(),c=!a.endsWith("?")?"?":"",f=e.slice(r+1).trim(),u="unknown";if(f==="true"||f==="false")u="boolean";else if(/^-?\d+(\.\d+)?$/.test(f))u="number";else if(f.startsWith("'")&&f.endsWith("'")||f.startsWith('"')&&f.endsWith('"'))u="string";else if(f.startsWith("["))u="unknown[]";else if(f.startsWith("{"))u="Record<string, unknown>";return`${a}${c}: ${u}`}return e}function qd(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 Ql(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(`
|
|
162
|
+
`),key:e.slice(r).trim()}}function zd(e){let t=[],r="",n="",i=0,s=!1,o="",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,B=S<e.length-1?e.charCodeAt(S+1):0;if(!s&&!c&&x===47&&B===47){r=r.replace(/[ \t]+$/,""),S+=2;while(S<e.length&&e.charCodeAt(S)!==10)S++;S--;continue}if(!s&&!c&&x===47&&B===42){c=!0,f=1,r+="/*",S++;continue}else if(c&&x===42&&B===47){if(f--,r+="*/",S++,f===0)c=!1;continue}else if(c&&x===47&&B===42){f++,r+="/*",S++;continue}let W=e[S];if(!s&&!c&&(x===34||x===39||x===96))s=!0,o=W,r+=W;else if(s&&W===o&&v!==92)s=!1,r+=W;else if(!s&&!c)if(x===40&&i===0&&a&&l===0){n=r.trim();let P=qd(n),F=P>0?n.slice(0,P):"",I=n.slice(P),k="";if(I.startsWith("async ")||I.startsWith("async\t")||I.startsWith(`async
|
|
163
|
+
`))I=I.slice(6).trimStart(),k="async ";if(I.startsWith("*"))I=I.slice(1).trimStart(),k+="*";n=F+I,r=k+W,a=!1,y=!0,C=!1,i=1}else if(x===123||x===91||x===40){if(i++,r+=W,C&&x===123)C=!1}else if(x===125||x===93||x===41){if(i--,r+=W,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+=W;else if(x===60&&h)l++,r+=W;else if(x===60&&a&&i===0)l++,r+=W;else if(x===62&&l>0&&v!==61)l--,r+=W;else if(x===61&&B===62&&h&&l===0)h=!1,u=!1,r+=W;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())Vl(t,r.trim());r="",n="",a=!0,u=!1,h=!1,l=0}else r+=W;else r+=W}if(n&&r.trim()){let S=r.trim();t.push([n,S])}else if(a&&r.trim())Vl(t,r.trim());return t}function Vl(e,t){let{comments:r,key:n}=Ql(t);if(Bi(n))e.push([r?`${r}
|
|
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
|
+
`){let i=r,s=n;while(i<s&&(e[i]===" "||e[i]==="\t"||e[i]==="\r"))i++;while(s>i&&(e[s-1]===" "||e[s-1]==="\t"||e[s-1]==="\r"))s--;let o=e.slice(i,s);if(r=n+1,o.startsWith("///")){if(o.indexOf("<")===-1)continue;if(rp.test(o)||ip.test(o)||np.test(o))t.push(o)}else if(o===""||o.startsWith("//"))continue;else break}return t}function op(e){if(e.includes(`
|
|
166
166
|
`))return`/**
|
|
167
167
|
* ${e}
|
|
168
168
|
*/
|
|
169
169
|
`;return`/** ${e} */
|
|
170
|
-
`}function
|
|
170
|
+
`}function ap(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,s="";for(let o=0;o<e.length;o++){let a=e[o],c=o>0?e[o-1]:"";if(!i&&(a==='"'||a==="'"||a==="`"))i=!0,s=a;else if(i&&a===s&&c!=="\\")i=!1;if(!i){if(a==="<")n++;else if(a===">")n--;else if(a==="{"&&n===0)return o}}return-1}function lp(e,t=!0){return Tt(e.leadingComments,t)+e.text}function rc(e,t=!0){let r=Tt(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:s,value:o}=e,a=!s&&o?_i(o):null;if(a)s=a;else if(!s&&o&&o.trim().endsWith("as const"))s=Ie(o,!0);else if(!s&&o&&i==="const"){let f=o.trim(),u=f.startsWith("{")||f.startsWith("[");if(u)Ss();s=Ie(o,!u)}else if(!s&&o)s=Ie(o,i==="const");if(!s)s="unknown";let c="";if(t&&o&&!e.typeAnnotation&&!o.trim().endsWith("as const")){let f=o.trim();if(i!=="const"){if((s==="string"||s==="number"||s==="boolean")&&f.length>0)c=`@defaultValue ${f}`}else if(f.startsWith("{")||f.startsWith("[")){let u=As();if(u)if(u.includes(`
|
|
171
171
|
`))c=`@defaultValue
|
|
172
172
|
* \`\`\`ts
|
|
173
173
|
${u.split(`
|
|
174
|
-
`).map((
|
|
174
|
+
`).map((h)=>` * ${h}`).join(`
|
|
175
175
|
`)}
|
|
176
|
-
* \`\`\``;else c=`@defaultValue \`${u}\``}}else if(t&&o&&e.typeAnnotation&&
|
|
176
|
+
* \`\`\``;else c=`@defaultValue \`${u}\``}}else if(t&&o&&e.typeAnnotation&&tc(e.typeAnnotation)){Ss();let f=o.trim(),u=f.endsWith("as const")?f.slice(0,-8).trim():f;Ie(u,!1);let h=As();if(h)if(h.includes(`
|
|
177
177
|
`))c=`@defaultValue
|
|
178
178
|
* \`\`\`ts
|
|
179
|
-
${
|
|
180
|
-
`).map((
|
|
179
|
+
${h.split(`
|
|
180
|
+
`).map((l)=>` * ${l}`).join(`
|
|
181
181
|
`)}
|
|
182
|
-
* \`\`\``;else c=`@defaultValue \`${
|
|
183
|
-
`))
|
|
184
|
-
* ${
|
|
182
|
+
* \`\`\``;else c=`@defaultValue \`${h}\``}if(c=bs(c),n+=`: ${s};`,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
|
+
`))h=`/**
|
|
184
|
+
* ${h.slice(4)}`;return`${h}
|
|
185
185
|
* ${c}
|
|
186
186
|
*/
|
|
187
187
|
`+n}return`/**
|
|
188
188
|
* ${f.replace(/^\/\/\s*/,"")}
|
|
189
189
|
* ${c}
|
|
190
190
|
*/
|
|
191
|
-
${n}`}if(c)return`${
|
|
192
|
-
`;i+=j
|
|
193
|
-
`));for(let
|
|
194
|
-
|
|
195
|
-
`;i+=
|
|
196
|
-
`;i+=
|
|
197
|
-
`;i+=
|
|
198
|
-
`;i+=k[b]}for(let b=0;b<L.
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
`)
|
|
202
|
-
`)
|
|
203
|
-
`)
|
|
204
|
-
`)}function
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
`))
|
|
210
|
-
`)){let
|
|
211
|
-
`).
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
`;if(h==="t")return"\t";if(h==="r")return"\r";if(h==="0")return"\x00";return h})}function ef(d){return`'${d.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Lr(d){if(d.endsWith("as const"))return null;let p=0,h=-1;for(let g=0;g<d.length;g++){let v=d.charCodeAt(g);if(v===le||v===ue||v===Fe)g=_i(d,g,v)-1;else if(v===123||v===91||v===40)p++;else if(v===125||v===93||v===41)p--;else if(p===0&&v===32&&g+4<=d.length&&d.substring(g,g+4)===" as ")h=g}if(h===-1)return null;return d.slice(h+4).trim()||null}function dr(){if(C(),a<l&&i.charCodeAt(a)===lt){a++,C();let d=a,p=0;while(a<l){if(T())continue;let h=i.charCodeAt(a);if(h===ae||h===Ae||h===$e)p++;else if(h===Se||h===Pe||h===me&&!Y())p--;else if(h===K)if(p>0)p++;else{let g=m(d,a),v=(E)=>{let O=g.length-E.length;return O>=0&&g.endsWith(E)&&(O===0||!Ve(g.charCodeAt(O-1)))};if(g.length===0||g.endsWith("|")||g.endsWith("&")||v("is")||v("extends"))p++;else break}else if(h===X){if(p===0)break;p--}else if(p===0&&h===re)break;if(p===0&&ce())break;a++}return m(d,a)}return""}function Tt(d,p,h,g){a+=8,C();let v=a<l&&i.charCodeAt(a)===xe;if(v)a++,C();let E=N();if(!E&&!g)return null;C();let O=dt();C();let R=xt();C();let S=dr(),A=S.length>0;if(!S)if(h&&v)S="AsyncGenerator<unknown, void, unknown>";else if(v)S="Generator<unknown, void, unknown>";else if(h)S="Promise<void>";else S="void";C();let P=!1;if(a<l&&i.charCodeAt(a)===K){P=!0;let M=a+1;if(z(K,X),!A&&!v)S=fr(i.slice(M,a-1),h,R)}else if(a<l&&i.charCodeAt(a)===re)a++;let _=_t(R),B=`${p?g?"export default function ":"export declare function ":"declare function "}${E||(g?"":"default")}${O}${_}: ${S};`,I=Qe(d);if(P)u.add(c.length);return{kind:"function",name:E||"default",text:B,isExported:p,isDefault:g,isAsync:h,isGenerator:v,returnType:S,generics:O||void 0,leadingComments:I,start:d,end:a}}function Ft(d,p,h){a+=p.length,C();let g=[];do{if(C(),a>=l)break;let v=i.charCodeAt(a);if(v===K||v===Ae)return ne(),g;let E=N();if(!E)return ne(),g;C();let O,R,S=!1;if(a<l&&i.charCodeAt(a)===lt){a++,C();let _=a,B=0;while(a<l){if(T()){if(B===0&&se())break;continue}let I=i.charCodeAt(a);if(I===ae||I===K||I===Ae||I===$e)B++;else if(I===Se||I===X||I===Pe||I===me&&!Y())B--;else if(B===0&&(I===re||I===ht))break;else if(B===0&&I===be&&!te())break;if(B===0&&(Z()||ie()))break;a++}O=m(_,a)}if(a<l&&i.charCodeAt(a)===be)if(o&&O&&(!s||!$p(O)))qi();else{a++,C();let _=a,B=0,I=0,M=0,U=!0;for(;;){a=_,B=0,I=0,M=0;while(a<l){if(T()){if(B===0&&I===0&&M===0&&se())break;continue}let V=i.charCodeAt(a);if(V===ae||V===K||V===Ae)B++;else if(V===Se||V===X||V===Pe)B--;else if(V===$e&&B===0){let Ze=eo(a);if(Ze!==null)M=Math.max(0,M+Ze);else if(U&&(a+1>=l||i.charCodeAt(a+1)!==be))I++}else if(V===me&&B===0&&M===0&&!Y()){if(I>0&&(a+1>=l||i.charCodeAt(a+1)!==be))I--}else if(B===0&&I===0&&M===0&&(V===re||V===ht))break;if(B===0&&I===0&&M===0&&(Z()||De()))break;a++}if(I>0&&U){U=!1;continue}break}if(R=m(_,a),R.endsWith(" as const")||R==="const"){if(S=!0,!O){let V=R.endsWith(" as const")?R.slice(0,-9).trim():R,Ze=Qi(V);O=Ze!=="unknown"?Ze:void 0}}else if(!O){let V=Gi(R)??Lr(R);if(V)O=V}}if(a<l){let _=i.charCodeAt(a);if(_===ht){a++;continue}if(_===re)a++}let A=Qe(d),P=`${h?"export ":""}declare ${p} ${E}: ${O||"unknown"};`;g.push({kind:"variable",name:E,text:P,isExported:h,typeAnnotation:O,value:R,modifiers:S?[p,"const assertion"]:[p],leadingComments:A,start:d,end:a});break}while(a<l);return g}function eo(d){if(i.charCodeAt(d)!==$e||d+1>=l)return null;let p=i.charCodeAt(d+1);if(p===me)return 1;if(p===Q)return-1;if(!gt(p))return null;let h=d+2;while(h<l){let A=i.charCodeAt(h);if(!Ve(A)&&A!==pt&&A!==58&&A!==45)break;h++}let g=i.slice(d+1,h),v=i.charCodeAt(h);if(v>32&&v!==me&&v!==Q)return null;let E=0,O=0,R=h;for(;R<l;R++){let A=i.charCodeAt(R);if(O!==0){if(A===rt)R++;else if(A===O)O=0;continue}if(A===le||A===ue||A===Fe)O=A;else if(A===K)E++;else if(A===X&&E>0)E--;else if(A===me&&E===0)break}if(R>=l)return null;let S=R-1;while(S>d&&i.charCodeAt(S)<=32)S--;if(i.charCodeAt(S)===Q)return 0;return i.indexOf(`</${g}`,R+1)===-1?null:1}function en(d,p){a+=9,C();let h=N();C();let g=dt();C();let v="";if(b("extends")){a+=7,C();let A=a,P=0;while(a<l){if(T())continue;let _=i.charCodeAt(a);if(_===$e)P++;else if(_===me&&!Y())P--;else if(_===K&&P===0)break;a++}v=m(A,a)}C();let E=a<l&&i.charCodeAt(a)===K?zi():"{}",O=zs(E),R=`${p?"export ":""}declare interface ${h}${g}${v?` extends ${v}`:""} ${O}`,S=Qe(d);return{kind:"interface",name:h,text:R,isExported:p,extends:v||void 0,generics:g||void 0,leadingComments:S,start:d,end:a}}function tn(d,p){a+=4,C();let h=N();C();let g=dt();if(C(),a<l&&i.charCodeAt(a)===be)a++;C();let v=a,E=0;while(a<l){if(T())continue;let A=i.charCodeAt(a);if(A===ae||A===K||A===Ae||A===$e)E++;else if(A===Se||A===X||A===Pe||A===me&&!Y())E--;else if(E===0&&A===re)break;if(E===0&&(Z()||ie()))break;a++}let O=m(v,a);if(a<l&&i.charCodeAt(a)===re)a++;let R=`${p?"export ":""}type ${h}${g} = ${O}`,S=Qe(d);return{kind:"type",name:h,text:R,isExported:p,generics:g||void 0,leadingComments:S,start:d,end:a}}function Ut(d,p,h){a+=4,C();let g=N();C();let v=a;if(a<l&&i.charCodeAt(a)===K)z(K,X);let E=m(d,a),O=Qe(d);return{kind:"enum",name:g,text:E,isExported:p,modifiers:h?["const"]:void 0,leadingComments:O,start:d,end:a}}function Ot(d,p,h,g=!1){a+=5,C();let v=N()||"AnonymousClass";C();let E=dt();C();let O="";if(b("extends")){a+=7,C();let _=a,B=0;while(a<l){if(T())continue;let I=i.charCodeAt(a);if(I===$e)B++;else if(I===me&&!Y())B--;else if(B===0&&(I===K||b("implements")))break;a++}O=m(_,a)}let R;if(b("implements")){a+=10,C();let _=a,B=0;while(a<l){if(T())continue;let M=i.charCodeAt(a);if(M===$e)B++;else if(M===me&&!Y())B--;else if(B===0&&M===K)break;a++}let I=m(_,a);if(I)R=I.split(",").map((M)=>M.trim())}C();let S=rn(),A=`${p?g?"export default ":"export declare ":"declare "}${h?"abstract ":""}class ${v}${E}${O?` extends ${O}`:""}${R&&R.length>0?` implements ${R.join(", ")}`:""} ${S}`,P=Qe(d);return{kind:"class",name:v,text:A,isExported:p,isDefault:g,extends:O||void 0,implements:R,generics:E||void 0,modifiers:h?["abstract"]:void 0,leadingComments:P,start:d,end:a}}function rn(){if(a>=l||i.charCodeAt(a)!==K)return"{}";a++;let d=[];while(a<l){if(C(),a>=l)break;if(i.charCodeAt(a)===X){a++;break}if(i.charCodeAt(a)===re){a++;continue}if(b("static")&&sn("static")===K){a+=6,C(),z(K,X);continue}let p=!1,h=!1,g=!1,v=!1,E=!1,O=!1,R=!1,S=!1,A=!0;while(A){C();let B=a,I=N();if(a=B,I){let M=sn(I);if(M===ae||M===$e||M===Bi||M===33||M===lt||M===be||M===re||M===X)break}if(b("private")){p=!0,a+=7;continue}if(b("protected")){h=!0,a+=9;continue}if(b("public")){a+=6;continue}if(b("static")){g=!0,a+=6;continue}if(b("abstract")){v=!0,a+=8;continue}if(b("readonly")){E=!0,a+=8;continue}if(b("override")){O=!0,a+=8;continue}if(b("accessor")){R=!0,a+=8;continue}if(b("async")){S=!0,a+=5;continue}if(b("declare")){a+=7;continue}break}if(C(),a>=l||i.charCodeAt(a)===X)break;if(i.charCodeAt(a)===Os)p=!0;let P=p?[]:d,_=" ";if(h)_+="protected ";if(g)_+="static ";if(v)_+="abstract ";if(E)_+="readonly ";if(b("constructor")){a+=11,C();let B=xt();if(C(),rf(B,P),a<l&&i.charCodeAt(a)===K)z(K,X);else if(a<l&&i.charCodeAt(a)===re)a++;let I=_t(B);P.push(` constructor${I};`)}else if(b("get"))if(a+=3,C(),a<l&&to(i.charCodeAt(a))){let B=nn();if(B.startsWith("#")){if(C(),a<l&&i.charCodeAt(a)===ae)xt();if(C(),dr(),C(),a<l&&i.charCodeAt(a)===K)z(K,X);else if(a<l&&i.charCodeAt(a)===re)a++;continue}C(),xt(),C();let I=dr()||"unknown";if(C(),a<l&&i.charCodeAt(a)===K)z(K,X);else if(a<l&&i.charCodeAt(a)===re)a++;P.push(`${_}get ${B}(): ${I};`)}else io("get",_,g,E,S,P);else if(b("set"))if(a+=3,C(),a<l&&to(i.charCodeAt(a))){let B=nn();if(B.startsWith("#")){if(C(),a<l&&i.charCodeAt(a)===ae)xt();if(C(),a<l&&i.charCodeAt(a)===K)z(K,X);else if(a<l&&i.charCodeAt(a)===re)a++;continue}C();let I=xt();if(C(),a<l&&i.charCodeAt(a)===K)z(K,X);else if(a<l&&i.charCodeAt(a)===re)a++;let M=_t(I);P.push(`${_}set ${B}${M};`)}else io("set",_,g,E,S,P);else{let B=i.charCodeAt(a)===xe;if(B)a++,C();let I=nn();if(!I){ro();continue}no(I,_,g,E,B,v,S,P)}}return`{
|
|
191
|
+
${n}`}if(c)return`${op(c)}${n}`;return r+n}function cp(e,t=!0){let r=Tt(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 s=ap(e.text);if(s!==-1)i+=` ${e.text.slice(s)}`;else i+=" {}";return r+i}function fp(e,t=!0){let r=Tt(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 o=e.text.slice(i),a=o.length;while(a>0&&(o.charCodeAt(a-1)===59||o.charCodeAt(a-1)===32||o.charCodeAt(a-1)===10||o.charCodeAt(a-1)===13))a--;if(a<o.length)o=o.slice(0,a);n+=o}else{if(n+=`type ${e.name}`,e.generics)n+=e.generics;n+=" = any"}let s=n.trimEnd();if(!s.endsWith(";")&&!s.endsWith("}"))n+=";";return r+n}function up(e,t=!0){return Tt(e.leadingComments,t)+e.text}function hp(e,t=!0){let r=Tt(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 dp(e,t=!0){let r=Tt(e.leadingComments,t);if(e.text.startsWith("declare global"))return r+e.text;if(e.source||(e.name.startsWith('"')||e.name.startsWith("'")||e.name.startsWith("`"))){let s="declare module ";s+=e.name;let o=e.text.indexOf("{");if(o!==-1)s+=` ${e.text.slice(o)}`;else s+=" {}";return r+s}let 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 pp(e){let t=Ut.get(e);if(t)return Ut.delete(e),Ut.set(e,t),t;return null}function ic(e,t){if(Ut.set(e,t),Ut.size>200){let r=0;for(let n of Ut.keys()){if(r++>=20)break;Ut.delete(n)}}}function mp(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 s=r.slice(1,i),o=e.slice(0,t).trim(),a=o.startsWith("import type ");if(o.startsWith("import "))o=o.slice(7).trim();if(o.startsWith("type "))o=o.slice(5).trim();let c=null,f=[],u=!1,h=o.indexOf("{"),l=o.lastIndexOf("}");if(h!==-1&&l!==-1){let y=o.slice(0,h).trim();if(y.endsWith(","))c=y.slice(0,-1).trim()||null;let C=o.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,B=x;while(v<B&&(C.charCodeAt(v)===32||C.charCodeAt(v)===9||C.charCodeAt(v)===10))v++;while(B>v&&(C.charCodeAt(B-1)===32||C.charCodeAt(B-1)===9||C.charCodeAt(B-1)===10))B--;if(v<B)f.push(C.slice(v,B));S=x+1}}else{let y=o.trim();if(y.startsWith("* as "))c=y.slice(5).trim()||null,u=!0;else c=y||null}return{defaultName:c,namedItems:f,source:s,isTypeOnly:a,isNamespace:u}}function gp(e){let t=pp(e);if(t)return t;let r=[],n=e.indexOf(" from ");if(n===-1)return ic(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 s=i.indexOf("{"),o=i.lastIndexOf("}");if(s!==-1&&o!==-1){let a=i.slice(0,s).trim();if(a.endsWith(",")){let f=a.slice(0,-1).trim();if(f)r.push(f)}else if(a&&!a.includes(","))r.push(a);let c=i.slice(s+1,o).split(",");for(let f=0;f<c.length;f++){let u=c[f].trim();if(!u)continue;if(u.startsWith("type "))u=u.slice(5).trim();let 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 ic(e,r),r}function nc(e,t){throw Error(t||`Unexpected value: ${e}`)}function yp(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function Cp(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 s=r;r++;while(r<n&&yp(e.charCodeAt(r)))r++;t.add(e.substring(s,r))}else r++}return t}function lc(e,t,r=!0,n=["bun"]){let i="",s=t.sourceCode;if(s){let k=0;while(k<s.length&&(s.charCodeAt(k)===32||s.charCodeAt(k)===9||s.charCodeAt(k)===10||s.charCodeAt(k)===13))k++;if(k<s.length-2&&s.charCodeAt(k)===47&&s.charCodeAt(k+1)===47&&s.charCodeAt(k+2)===47){let H=sp(s);if(H.length>0)for(let j=0;j<H.length;j++){if(i)i+=`
|
|
192
|
+
`;i+=H[j]}}}let o=[],a=[],c=[],f=[],u=[],h=[],l=[],y=[],C=[];for(let k of e){let H=k.kind;switch(H){case"import":o.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:nc(H,`Unhandled declaration kind: ${H}`)}}let S=new Set,x=[],v=[],B=[],W=new Set;for(let k of C){let H=Tt(k.leadingComments,r);if(k.text.startsWith("export default")){let j=k.text.endsWith(";")?k.text:`${k.text};`;B.push(H+j)}else{let j=k.text.trim();if(!j.endsWith(";"))j+=";";let O=j.match(wp);if(O){let me=O[1],Oe=0;for(let ie=0;ie<=me.length;ie++)if(ie===me.length||me.charCodeAt(ie)===44){let ne=Oe,ue=ie;while(ne<ue&&me.charCodeAt(ne)<=32)ne++;while(ue>ne&&me.charCodeAt(ue-1)<=32)ue--;if(ne<ue)S.add(me.slice(ne,ue));Oe=ie+1}}let Z=H+j;if(!W.has(Z))if(W.add(Z),Z.includes("export type"))x.push(Z);else v.push(Z)}}let P=new Map;if(o.length>0)for(let k of o){let H=gp(k.text);for(let j of H)P.set(j,k)}let F=[];if(o.length>0){let k=new Set,H=[];for(let Z of a)H.push(Z.text);for(let Z of c)if(H.push(Z.text),Z.typeAnnotation)H.push(Z.typeAnnotation);else if(Z.isExported&&Z.value)H.push(rc(Z,!1));for(let Z of f)H.push(Z.text);for(let Z of u)H.push(Z.text);for(let Z of h)H.push(Z.text);for(let Z of l)H.push(Z.text);for(let Z of y)H.push(Z.text);for(let Z of C)H.push(Z.text);let j=H.join(`
|
|
193
|
+
`);if(j&&P.size>0){let Z=Cp(j);for(let me of P.keys())if(Z.has(me))k.add(me)}for(let Z of S)if(P.has(Z))k.add(Z);for(let Z of o){if(Z.isSideEffect){let z=Z.text.trim(),te=z.endsWith(";")?z:`${z};`;F.push(te);continue}let me=mp(Z.text);if(!me)continue;let{defaultName:Oe,namedItems:ie,source:ne,isTypeOnly:ue,isNamespace:oe}=me,L=Oe?k.has(Oe):!1,K="",J=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(),se=X.indexOf(" as ");if(se!==-1)X=X.slice(se+4).trim();if(k.has(X)){if(J>0)K+=", ";K+=te,J++}}if(L||J>0){let z=ue?"import type ":"import ";if(L&&Oe)if(oe)z+=`* as ${Oe}`;else z+=J>0?`${Oe}, { ${K} }`:Oe;else if(J>0)z+=`{ ${K} }`;z+=` from '${ne}';`,F.push(z)}}let O=n.length;if(F.length>1){if(sc!==n)sc=n,oc=n.map((ie)=>`from '${ie}`),ac=n.map((ie)=>`from "${ie}`);let Z=oc,me=ac,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(me[ue])){ne=ue;break}Oe.set(ie,ne)}F.sort((ie,ne)=>{let ue=Oe.get(ie),oe=Oe.get(ne);return ue!==oe?ue-oe:ie.localeCompare(ne)})}}for(let k=0;k<F.length;k++){if(i)i+=`
|
|
194
|
+
`;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 H=I[k];for(let j=0;j<H.length;j++){let O=H[j],Z="",me=O.kind;switch(me){case"function":Z=lp(O,r);break;case"variable":Z=rc(O,r);break;case"interface":Z=cp(O,r);break;case"type":Z=fp(O,r);break;case"class":Z=up(O,r);break;case"enum":Z=hp(O,r);break;case"module":case"namespace":Z=dp(O,r);break;case"import":case"export":case"unknown":break;default:nc(me,`Unhandled declaration kind in processor: ${me}`)}if(Z){if(i)i+=`
|
|
196
|
+
`;i+=Z}}}for(let k=0;k<v.length;k++){if(i)i+=`
|
|
197
|
+
`;i+=v[k]}for(let k=0;k<B.length;k++){if(i)i+=`
|
|
198
|
+
`;i+=B[k]}if(!i&&(o.length>0||C.length>0))return"export {};";return i}var rp,ip,np,Ut,wp,sc=null,oc,ac;var cc=he(()=>{Os();rp=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,ip=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,np=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;Ut=new Map;wp=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,oc=[],ac=[]});function Ue(e){return e===Me||e===De||e===$e||e===xe}function bp(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(!Ct(n))return!1;t=!1}else if(!Ke(n))return!1}return e.length>0&&!t}function Vi(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 Ep(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===Y&&e.includes("[")&&e.includes("]:")}function hc(e,t,r=!0){return pc(e,t,r,!0)}function dc(e,t,r=!0){return pc(e,t,r,!1)}function pc(e,t,r,n){let i=e,s=r,o=n,a=i.length,c=[],f=new Map,u=new Map,h=new Set,l=0;function y(d){let m=u.get(d.name);if(m)m.push(d);else u.set(d.name,[d]);f.set(d.name,d)}if(l<a&&i.charCodeAt(l)===65279)l++;function C(d,m){if(d<m){let p=i.charCodeAt(d),g=i.charCodeAt(m-1);if(p!==Me&&p!==De&&p!==$e&&p!==xe&&g!==Me&&g!==De&&g!==$e&&g!==xe)return i.slice(d,m)}while(d<m&&Ue(i.charCodeAt(d)))d++;while(m>d&&Ue(i.charCodeAt(m-1)))m--;return i.slice(d,m)}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!==$e&&d!==xe&&d!==ee)return;while(l<a){let m=i.charCodeAt(l);if(m===Me||m===De||m===$e||m===xe){l++;continue}if(m===ee&&l+1<a){let p=i.charCodeAt(l+1);if(p===ee){l=x(l+2);continue}if(p===Ae){let g=i.indexOf("*/",l+2);l=g===-1?a:g+2;continue}}break}}function B(d){let m=d.length,p=0,g=m;for(let w=0;w<m;w++){let b=d.charCodeAt(w);if(p){if(b===nt){w++;continue}if(b===p)p=0;continue}if(b===le||b===fe||b===Fe){p=b;continue}if(b===ee&&w+1<m){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=m;while(g>0&&(d.charCodeAt(g-1)===Me||d.charCodeAt(g-1)===De||d.charCodeAt(g-1)===xe))g--;return g<m?d.slice(0,g):d}function W(d){l++;let m=d===le?"'":'"';while(l<a){let p=i.indexOf(m,l);if(p===-1){l=a;return}let g=0,w=p-1;while(w>=0&&i.charCodeAt(w)===nt)g++,w--;if(g%2===0){l=p+1;return}l=p+1}}function P(){l++;let d=[];while(l<a){let m=i.charCodeAt(l);if(d.length===0){if(m===nt){l+=2;continue}if(m===Fe){l++;return}if(m===vp&&l+1<a&&i.charCodeAt(l+1)===Y){l+=2,d.push(0);continue}l++;continue}if(m===le||m===fe){W(m);continue}if(m===Fe){P();continue}if(m===ee&&l+1<a){let p=i.charCodeAt(l+1);if(p===ee){l=x(l+2);continue}if(p===Ae){let g=i.indexOf("*/",l+2);l=g===-1?a:g+2;continue}if(k()){H();continue}l++;continue}if(m===Y){d[d.length-1]++,l++;continue}if(m===Q){let p=d[d.length-1];if(p===0){d.pop(),l++;continue}d[d.length-1]=p-1,l++;continue}l++}}let F=!1;function I(){F=!1;let d=i.charCodeAt(l);if(d===le||d===fe)return W(d),!0;if(d===Fe)return P(),!0;if(d===ee&&l+1<a){let m=i.charCodeAt(l+1);if(m===ee)return l=x(l+2),!0;if(m===Ae){let p=i.indexOf("*/",l+2);return F=x(l+2)<(p===-1?a:p),l=p===-1?a:p+2,!0}if(k())return H(),!0}return!1}function k(){return Hr(i,l)}function H(){l=gr(i,l)}function j(){let d=l;while(l<a&&Ke(i.charCodeAt(l)))l++;return i.slice(d,l)}function O(d){if(l+d.length>a)return!1;for(let m=0;m<d.length;m++)if(i.charCodeAt(l+m)!==d.charCodeAt(m))return!1;if(l+d.length<a&&Ke(i.charCodeAt(l+d.length)))return!1;return!0}function Z(d){let m=l+d;while(m<a){let p=i.charCodeAt(m);if(p===Me||p===De||p===$e||p===xe){m++;continue}return p!==gt&&p!==ve}return!1}function me(){if(!F)return!1;let d=l;v();let m=l>=a||Oe()||i.charCodeAt(l)===Q;return l=d,m}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!==$e&&d!==xe)return!1;let m=l;if(l++,d===xe&&l<a&&i.charCodeAt(l)===$e)l++;while(l<a){let g=i.charCodeAt(l);if(g===Me||g===De||g===xe||g===$e){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 p=l>=a||Oe()||i.charCodeAt(l)===Q;return l=m,p}function ne(d){let m=d-1;while(m>=0){let E=i.charCodeAt(m);if(E===Me||E===De||E===xe||E===$e){m--;continue}break}if(m<0)return!0;let p=i[m];if("+-*/%=<>&|^!~?:,.([{".includes(p))return!0;let g=m;while(g>0&&i.charCodeAt(g-1)!==$e)g--;let w=i.slice(g,m+1),b=w.lastIndexOf("<");if(b!==-1&&/^<[A-Za-z]/.test(w.slice(b))&&!w.slice(b).includes(">"))return!0;let T=m;while(T>=0&&/[a-z]/i.test(i[T]))T--;let R=i.slice(T+1,m+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!==$e&&d!==xe)return!1;if(ne(l))return!1;let m=l;l++;while(l<a){let b=i.charCodeAt(l);if(b===Me||b===De||b===xe||b===$e){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 p=l<a?i[l]:"",g=i.slice(l,l+2),w=p==="."||p==="?"||p===":"||p===")"||p==="]"||p==="}"||p===","||p==="+"||p==="-"||p==="*"||p==="/"||p==="%"||p==="<"||p===">"||p==="="||p==="&"||p==="|"||p==="^"||p==="`"||g==="=>"||O("as")||O("satisfies")||O("instanceof")||O("in");return l=m,!w}function oe(){let d=i.charCodeAt(l);if(d!==$e&&d!==xe)return!1;if(ne(l))return!1;let m=l;l++;while(l<a){let w=i.charCodeAt(l);if(w===Me||w===De||w===xe||w===$e){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 p=l<a?i[l]:"",g=p==="|"||p==="&"||p==="["||p==="."||p==="?"||p===":"||p===">"||p===")"||p===","||O("extends");return l=m,!g}function L(){let d=i.charCodeAt(l);if(d!==$e&&d!==xe)return!1;let m=l;if(l++,d===xe&&l<a&&i.charCodeAt(l)===$e)l++;while(l<a){let g=i.charCodeAt(l);if(g===Me||g===De||g===xe||g===$e){l++;continue}if(g===ee&&l+1<a&&i.charCodeAt(l+1)===ee){l=x(l+2);continue}break}if(l>=a)return l=m,!0;let p=i.charCodeAt(l);if(p===124||p===38||p===gt||p===Ui||p===ft)return l=m,!1;if(O("extends")||O("keyof")||O("typeof")||O("infer")||O("is")||O("as")||O("in"))return l=m,!1;return l=m,!0}let K=/[{}'"`\/]/g,J=/[()'"`\/]/g,z=/[[\]'"`\/]/g,te=/[<>'"`\/]/g;function X(d,m){let p=1;l++;let g=d===Y?K:d===ae?J:d===Se?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,W(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)p++;else if(T===m){if(m===pe&&b>0&&i.charCodeAt(b-1)===ve){g.lastIndex=b+1;continue}if(p--,p===0)return l=b+1,l}g.lastIndex=b+1}return l=a,l}function se(){return l>0&&i.charCodeAt(l-1)===ve}function Be(){return l+1<a&&i.charCodeAt(l+1)===pe}let He=/[<{};'"`\/\n\r()[\]]/g;function Re(d=!1){let m=0,p=0,g=0,w=0,b=i.charCodeAt(l)===Y;He.lastIndex=l;let T;while((T=He.exec(i))!==null){let R=T.index,E=i.charCodeAt(R);if(E===le||E===fe){l=R,W(E),He.lastIndex=l;continue}if(E===Fe){l=R,P(),He.lastIndex=l;continue}if(E===ee){if(R>0&&i.charCodeAt(R-1)===we){He.lastIndex=R+1;continue}if(l=R,I()){if(m===0&&p===0&&g===0&&w===0&&me())return;He.lastIndex=l;continue}He.lastIndex=R+1;continue}if(E===we){let A=to(R);if(A!==null)w=Math.max(0,w+A);He.lastIndex=R+1;continue}if(E===ae){p++,He.lastIndex=R+1;continue}if(E===Ee){p--,He.lastIndex=R+1;continue}if(E===Se){g++,He.lastIndex=R+1;continue}if(E===ke){g--,He.lastIndex=R+1;continue}if(E===Y){m++,He.lastIndex=R+1;continue}if(E===Q){let A=m>0;if(!A&&d&&p===0&&g===0&&w===0){l=R;return}if(A)m--;if((!A||b)&&m===0&&p===0&&g===0&&w===0){l=R+1;return}He.lastIndex=R+1;continue}if(E===re&&m===0&&p===0&&g===0&&w===0){l=R+1;return}if((E===$e||E===xe)&&m===0&&p===0&&g===0&&w===0){if(l=R,ie())return}He.lastIndex=R+1}l=a}function qc(){l++;while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;let d=i.indexOf(`
|
|
199
|
+
`,l),m=d===-1?a:d,p=i.indexOf(";",l);if(p!==-1&&p<m){let g=p-1;while(g>=l&&(i.charCodeAt(g)===Me||i.charCodeAt(g)===De))g--;let w=i.charCodeAt(l),b=i.charCodeAt(g);if(w===Y&&b===Q||w===Se&&b===ke||w===le&&b===le||w===fe&&b===fe||w===Fe&&b===Fe){l=p+1;return}}Re()}function Js(){X(Y,Q);while(l<a&&Ue(i.charCodeAt(l)))l++;if(O("from")){l+=4;while(l<a&&Ue(i.charCodeAt(l)))l++;if(l<a){let d=i.charCodeAt(l);if(d===le||d===fe)W(d)}}while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;if(l<a&&i.charCodeAt(l)===re)l++}function qs(){l++;while(l<a&&Ue(i.charCodeAt(l)))l++;if(O("as")){l+=2;while(l<a&&Ue(i.charCodeAt(l)))l++;j();while(l<a&&Ue(i.charCodeAt(l)))l++}if(O("from")){l+=4;while(l<a&&Ue(i.charCodeAt(l)))l++;if(l<a){let d=i.charCodeAt(l);if(d===le||d===fe)W(d)}}while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;if(l<a&&i.charCodeAt(l)===re)l++}function Lr(d){let m=d.indexOf("from ");if(m===-1)return;let p=m+5;while(p<d.length&&(d.charCodeAt(p)===32||d.charCodeAt(p)===9))p++;if(p>=d.length)return;let g=d.charCodeAt(p);if(g!==39&&g!==34)return;let w=d.indexOf(d[p],p+1);if(w===-1)return;return d.slice(p+1,w)}function tt(d){if(!s)return;let m=d-1;while(m>=0&&Ue(i.charCodeAt(m)))m--;if(m<0)return;let p=[],g=!1;while(m>=0){if(m>=1&&i.charCodeAt(m)===ee&&i.charCodeAt(m-1)===Ae){let T=i.lastIndexOf("/*",m-2);if(T>=0){p.push(i.slice(T,m+1)),g=!0,m=T-1;while(m>=0&&Ue(i.charCodeAt(m)))m--;continue}break}let w=m;while(w>0&&i.charCodeAt(w-1)!==$e)w--;let b=C(w,m+1);if(b.startsWith("//")){if(g)break;let T=[b];m=w-1;while(m>=0&&(i.charCodeAt(m)===$e||i.charCodeAt(m)===xe))m--;while(m>=0){let R=m;while(R>0&&i.charCodeAt(R-1)!==$e)R--;let E=C(R,m+1);if(E.startsWith("//")){T.push(E),m=R-1;while(m>=0&&(i.charCodeAt(m)===$e||i.charCodeAt(m)===xe))m--}else if(E===""){m=R-1;while(m>=0&&(i.charCodeAt(m)===$e||i.charCodeAt(m)===xe))m--}else break}T.reverse(),p.push(T.join(`
|
|
200
|
+
`));continue}break}if(p.length===0)return;return p.reverse(),p}function zc(d){let m=d,p=!1;while(l<a){let E=i.charCodeAt(l);if(E===re){l++;break}if(E===le||E===fe){W(E),p=!0;while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;if(l<a&&i.charCodeAt(l)===re)l++;break}if(E===$e&&p)break;l++}let g=C(m,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 U=g.indexOf(String.fromCharCode(M),A+1);if(U!==-1)T=g.slice(A+1,U)}}}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),U=g.indexOf(String.fromCharCode(M),A+1);if(U!==-1)T=g.slice(A+1,U)}}}let R=tt(m);return{kind:"import",name:"",text:g,isExported:!1,isTypeOnly:w,isSideEffect:b,source:T,leadingComments:R,start:m,end:l}}function Xi(){let d=l;return X(Y,Q),i.slice(d,l)}function zs(d){let m=d.indexOf("(");if(m===-1)return d;let p=d.slice(m);if(p.indexOf("=")===-1)return d;let g=!1;for(let E=0;E<p.length;E++)if(p.charCodeAt(E)===61){let A=E>0?p.charCodeAt(E-1):0,M=E+1<p.length?p.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=m;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(m,b+1),R=Vt(T);return d.slice(0,m)+R+d.slice(b+1)}function Xs(d){let m=d.indexOf("//")!==-1||d.indexOf("/*")!==-1,p=d.split(`
|
|
201
|
+
`),g=[],w=[],b=[],T=!1,R=1/0;for(let M=0;M<p.length;M++){let U=p[M];if(m){if(T){if(U.includes("*/"))T=!1;continue}let G=U.trim();if(G.length===0)continue;let N=G.charCodeAt(0);if(N===ee){let Je=G.charCodeAt(1);if(Je===ee)continue;if(Je===Ae){if(!G.includes("*/"))T=!0;continue}}if(N===Ae)continue;let D=B(U);if(D.charCodeAt(D.length-1)===re)D=D.slice(0,-1);D=zs(D);let _=D.trim();if(!_)continue;g.push(D),w.push(_);let V=0;while(V<D.length&&Ue(D.charCodeAt(V)))V++;if(_!=="{"&&_!=="}"){if(V<R)R=V}b.push(V)}else{let G=U.length;while(G>0&&(U.charCodeAt(G-1)===Me||U.charCodeAt(G-1)===De||U.charCodeAt(G-1)===xe))G--;if(G===0)continue;let N=G<U.length?U.slice(0,G):U;if(N.charCodeAt(N.length-1)===re)N=N.slice(0,-1);N=zs(N);let D=N.trim();if(!D)continue;g.push(N),w.push(D);let _=0;while(_<N.length&&Ue(N.charCodeAt(_)))_++;if(D!=="{"&&D!=="}"){if(_<R)R=_}b.push(_)}}if(g.length===0)return"{}";if(R===1/0||R<=2)return g.join(`
|
|
202
|
+
`);let E=R-2,A=Array(g.length);for(let M=0;M<g.length;M++){let U=w[M];if(U==="{"){A[M]=U;continue}let G=b[M];if(G>R)A[M]=g[M];else if(G===R&&(U.charCodeAt(0)===Q||U.charCodeAt(0)===ke||U.charCodeAt(0)===Ee))A[M]=g[M];else{let N=Math.max(0,G-E);A[M]=" ".repeat(N)+U}}return A.join(`
|
|
203
|
+
`)}function mt(){if(l>=a||i.charCodeAt(l)!==we)return"";let d=l;X(we,pe);let m=i.slice(d,l);if(m.includes(`
|
|
204
|
+
`)){let p="",g=!1;for(let w=0;w<m.length;w++){let b=m.charCodeAt(w);if(b===32||b===9||b===10||b===13){if(!g&&p.length>0)p+=" ",g=!0}else p+=m[w],g=!1}if(p.charCodeAt(1)===32)p=`<${p.slice(2)}`;if(p.charCodeAt(p.length-2)===32)p=`${p.slice(0,-2)}>`;return p}return m}function Ot(){if(l>=a||i.charCodeAt(l)!==ae)return"()";let d=l;return X(ae,Ee),i.slice(d,l)}function Gr(d){if(d.indexOf("/")===-1)return d;let m="",p=!1,g=0;for(let w=0;w<d.length;w++){let b=d.charCodeAt(w);if(p){if(m+=d[w],b===nt&&w+1<d.length){m+=d[++w];continue}if(b===g)p=!1;continue}if(b===le||b===fe||b===Fe){p=!0,g=b,m+=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,m+=" ";continue}if(T===ee){let R=d.indexOf(`
|
|
205
|
+
`,w+2);w=R===-1?d.length:R-1;continue}}m+=d[w]}return m.trim()}function Vt(d){let m=d.slice(1,-1).trim();if(!m)return"()";if(d.indexOf(`
|
|
206
|
+
`)===-1&&m.indexOf(":")!==-1&&m.indexOf("{")===-1&&m.indexOf("[")===-1&&m.indexOf("=")===-1&&m.indexOf("@")===-1&&m.indexOf("...")===-1){let E=0,A=0,M=0;for(let U=0;U<m.length;U++){let G=m.charCodeAt(U);if(G===ae||G===we||G===Y)M++;else if(G===Ee||G===pe||G===Q)M--;else if(M===0){if(G===ft)E++;else if(G===pt)A++}}if(E>=A+1){let U=!1;for(let G=0;G<Ps.length;G++){let N=Ps[G],D=m.indexOf(N);if(D!==-1){let _=D+N.length;if((D===0||!Ke(m.charCodeAt(D-1)))&&(_>=m.length||!Ke(m.charCodeAt(_)))){U=!0;break}}}if(!U)return d}}let p=[],g=0,w=0,b=!1,T=0;for(let E=0;E<=m.length;E++){if(E===m.length){p.push(Gr(m.slice(g).trim()));break}let A=m.charCodeAt(E);if(b){if(A===nt){E++;continue}if(A===T)b=!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){b=!0,T=A;continue}if(A===ae||A===Y||A===Se||A===we)w++;else if(A===Ee||A===Q||A===ke||A===pe&&!(E>0&&m.charCodeAt(E-1)===ve))w--;else if(A===pt&&w===0)p.push(Gr(m.slice(g,E).trim())),g=E+1}let R=[];for(let E of p){if(!E)continue;let A=E.trim();if(A.startsWith("//")||A.startsWith("/*"))continue;let M=E;{let U=!1,G=0,N=0,D=0;for(let _=0;_<M.length-1;_++){let V=M.charCodeAt(_);if(V===$e){D=_+1;continue}if(U){if(V===nt){_++;continue}if(V===G)U=!1;continue}if(V===le||V===fe||V===Fe){U=!0,G=V;continue}if(V===Y||V===Se||V===ae||V===we){N++;continue}if(V===Q||V===ke||V===Ee||V===pe){if(N>0)N--;continue}if(V===ee&&M.charCodeAt(_+1)===ee){if(N===0){M=M.slice(0,_).trimEnd();break}let Je=M.indexOf(`
|
|
207
|
+
`,_);if(Je===-1){M=M.slice(0,D).trimEnd();break}let qe=M.slice(0,D),jt=M.slice(Je+1);M=`${qe}${jt}`,_=D-1}}}if(!M.trim())continue;R.push(Qs(M))}return`(${R.join(", ")})`}function Xc(d){if(!d.startsWith("{")&&!d.startsWith("["))return d;let m="",p=0,g=0,w=!1,b=0;while(p<d.length){let T=d.charCodeAt(p);if(w){if(T===nt&&p+1<d.length){m+=d[p]+d[p+1],p+=2;continue}if(T===b)w=!1;m+=d[p],p++;continue}if(T===ee&&p+1<d.length){let R=d.charCodeAt(p+1);if(R===Ae){let E=p;p+=2;while(p+1<d.length&&!(d.charCodeAt(p)===Ae&&d.charCodeAt(p+1)===ee))p++;p=Math.min(p+2,d.length),m+=d.slice(E,p);continue}if(R===ee){let E=p;while(p<d.length&&d.charCodeAt(p)!==10)p++;m+=d.slice(E,p);continue}}if(T===le||T===fe||T===Fe){w=!0,b=T,m+=d[p],p++;continue}if(T===Y||T===Se||T===ae)g++;else if(T===Q||T===ke||T===Ee)g--;if(g>=1&&T===ve&&(p+1>=d.length||d.charCodeAt(p+1)!==ve&&d.charCodeAt(p+1)!==pe)){while(m.length>0&&(m[m.length-1]===" "||m[m.length-1]==="\t"||m[m.length-1]===`
|
|
208
|
+
`))m=m.slice(0,-1);p++;let R=0;while(p<d.length){let E=d.charCodeAt(p);if(E===le||E===fe||E===Fe){let A=E;p++;while(p<d.length){if(d.charCodeAt(p)===nt){p+=2;continue}if(d.charCodeAt(p)===A){p++;break}p++}continue}if(E===Y||E===Se||E===ae)R++;else if(E===Q||E===ke||E===Ee){if(R===0)break;R--}else if(E===pt&&R===0)break;p++}continue}if(g===1&&T===gt&&p+2<d.length&&d.charCodeAt(p+1)===gt&&d.charCodeAt(p+2)===gt){p+=3;continue}m+=d[p],p++}return m}function Qs(d){let m=d.trim(),p=m.startsWith("...");if(p)m=m.slice(3).trim();while(m.startsWith("@")){let D=1;while(D<m.length&&Ke(m.charCodeAt(D)))D++;if(D<m.length&&m.charCodeAt(D)===ae){let _=1;D++;while(D<m.length&&_>0){if(m.charCodeAt(D)===ae)_++;else if(m.charCodeAt(D)===Ee)_--;D++}}m=m.slice(D).trim()}let g=!0;while(g){g=!1;for(let D of Ps)if(m.startsWith(D)&&m.length>D.length&&!Ke(m.charCodeAt(D.length))){let _=m.slice(D.length).trim();if(_.charCodeAt(0)===ft||_.charCodeAt(0)===Ui&&_.length>1&&_.charCodeAt(1)===ft)break;m=_,g=!0;break}}let w=-1,b=-1,T=0,R=!1,E=0;for(let D=0;D<m.length;D++){let _=m.charCodeAt(D);if(R){if(_===nt){D++;continue}if(_===E)R=!1;continue}if(_===ee&&D+1<m.length){let V=m.charCodeAt(D+1);if(V===Ae){D+=2;while(D+1<m.length&&!(m.charCodeAt(D)===Ae&&m.charCodeAt(D+1)===ee))D++;D++;continue}if(V===ee){while(D<m.length&&m.charCodeAt(D)!==10)D++;continue}}if(_===le||_===fe||_===Fe){R=!0,E=_;continue}if(_===ae||_===Y||_===Se||_===we)T++;else if(_===Ee||_===Q||_===ke||_===pe&&!(D>0&&m.charCodeAt(D-1)===ve))T--;else if(T===0){if(_===ft&&w===-1)w=D;else if(_===ve&&b===-1&&(D===0||m.charCodeAt(D-1)!==ve)&&(D+1>=m.length||m.charCodeAt(D+1)!==ve&&m.charCodeAt(D+1)!==pe))b=D}}let A,M,U=b!==-1;if(w!==-1&&(b===-1||w<b))if(A=m.slice(0,w).trim(),b!==-1)M=m.slice(w+1,b).trim();else M=m.slice(w+1).trim();else if(b!==-1)A=m.slice(0,b).trim(),M=Qi(m.slice(b+1).trim());else A=m,M="unknown";if(A=Xc(A),(A.startsWith("{")||A.startsWith("["))&&A.includes(`
|
|
209
|
+
`)){let D=A.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(D.length<=40)A=D;else A=A.split(`
|
|
210
|
+
`).map((_)=>{let V=_.trim();if(!V)return"";if(V==="{"||V==="}"||V==="["||V==="]"||V.startsWith("}")||V.startsWith("]"))return V;return` ${V}`}).join(`
|
|
211
|
+
`)}let G=A.endsWith("?")||U;if(A.endsWith("?"))A=A.slice(0,-1).trim();let N=G&&!p?"?":"";if(p)return`...${A}: ${M}`;return`${A}${N}: ${M}`}function eo(d){let m=0;if(m<d.length&&d.charCodeAt(m)===45)m++;if(m>=d.length)return!1;let p=d.charCodeAt(m);if(p<48||p>57)return!1;while(m<d.length&&d.charCodeAt(m)>=48&&d.charCodeAt(m)<=57)m++;if(m<d.length&&d.charCodeAt(m)===46){if(m++,m>=d.length||d.charCodeAt(m)<48||d.charCodeAt(m)>57)return!1;while(m<d.length&&d.charCodeAt(m)>=48&&d.charCodeAt(m)<=57)m++}return m===d.length}function Qi(d){let m=d.trim();if(m==="true"||m==="false")return"boolean";if(eo(m))return"number";if(m.startsWith("'")&&m.endsWith("'")||m.startsWith('"')&&m.endsWith('"'))return"string";if(m.startsWith("["))return"unknown[]";if(m.startsWith("{"))return"Record<string, unknown>";return"unknown"}function en(d){let m=d.trim();if(m.endsWith("as const"))m=m.slice(0,-8).trim();if(m==="true"||m==="false")return m;if(eo(m))return m;let p=Qc(m);if(p!==null)return p;return"unknown"}function Qc(d){if(d==="")return null;if(d.charCodeAt(0)===le||d.charCodeAt(0)===fe){if(Vi(d,0,d.charCodeAt(0))===d.length)return d}let m=ef(d,"+");if(m.length>1){let p=!1,g=!0,w=[];for(let b of m){let T=b.trim(),R=T.charCodeAt(0);if((R===le||R===fe)&&Vi(T,0,R)===T.length)p=!0,w.push(tf(T));else g=!1}if(g)return rf(w.join(""));if(p)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(d)&&/\d/.test(d)&&/[+*/%\-\s]/.test(d))return"number";return null}function ef(d,m){let p=[],g=0,w="",b=0;while(b<d.length){let T=d.charCodeAt(b);if(T===le||T===fe||T===Fe){let R=Vi(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(`
|
|
212
|
+
`,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===Se||T===Y)g++;else if(T===Ee||T===ke||T===Q)g--;if(d[b]===m&&g===0){p.push(w),w="",b++;continue}w+=d[b],b++}return p.push(w),p}function tf(d){return d.slice(1,-1).replace(/\\(.)/g,(m,p)=>{if(p==="n")return`
|
|
213
|
+
`;if(p==="t")return"\t";if(p==="r")return"\r";if(p==="0")return"\x00";return p})}function rf(d){return`'${d.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Br(d){if(d.endsWith("as const"))return null;let m=0,p=-1;for(let g=0;g<d.length;g++){let w=d.charCodeAt(g);if(w===le||w===fe||w===Fe)g=Vi(d,g,w)-1;else if(w===123||w===91||w===40)m++;else if(w===125||w===93||w===41)m--;else if(m===0&&w===32&&g+4<=d.length&&d.substring(g,g+4)===" as ")p=g}if(p===-1)return null;return d.slice(p+4).trim()||null}function mr(){if(v(),l<a&&i.charCodeAt(l)===ft){l++,v();let d=l,m=0;while(l<a){if(I())continue;let p=i.charCodeAt(l);if(p===ae||p===Se||p===we)m++;else if(p===Ee||p===ke||p===pe&&!se())m--;else if(p===Y)if(m>0)m++;else{let g=C(d,l),w=(b)=>{let T=g.length-b.length;return T>=0&&g.endsWith(b)&&(T===0||!Ke(g.charCodeAt(T-1)))};if(g.length===0||g.endsWith("|")||g.endsWith("&")||w("is")||w("extends"))m++;else break}else if(p===Q){if(m===0)break;m--}else if(m===0&&p===re)break;if(m===0&&L())break;l++}return C(d,l)}return""}function Rt(d,m,p,g){l+=8,v();let w=l<a&&i.charCodeAt(l)===Ae;if(w)l++,v();let b=j();if(!b&&!g)return null;v();let T=mt();v();let R=Ot();v();let E=mr(),A=E.length>0;if(!E)if(p&&w)E="AsyncGenerator<unknown, void, unknown>";else if(w)E="Generator<unknown, void, unknown>";else if(p)E="Promise<void>";else E="void";v();let M=!1;if(l<a&&i.charCodeAt(l)===Y){M=!0;let _=l+1;if(X(Y,Q),!A&&!w)E=hr(i.slice(_,l-1),p,R)}else if(l<a&&i.charCodeAt(l)===re)l++;let U=Vt(R),G=`${m?g?"export default function ":"export declare function ":"declare function "}${b||(g?"":"default")}${T}${U}: ${E};`,N=tt(d),D={kind:"function",name:b||"default",text:G,isExported:m,isDefault:g,isAsync:p,isGenerator:w,returnType:E,generics:T||void 0,leadingComments:N,start:d,end:l};if(M)h.add(D);return D}function Wt(d,m,p){l+=m.length,v();let g=[];do{if(v(),l>=a)break;let w=i.charCodeAt(l);if(w===Y||w===Se)return Re(),g;let b=j();if(!b)return Re(),g;v();let T,R,E=!1;if(l<a&&i.charCodeAt(l)===ft){l++,v();let U=l,G=0;while(l<a){if(I()){if(G===0&&me())break;continue}let N=i.charCodeAt(l);if(N===ae||N===Y||N===Se||N===we)G++;else if(N===Ee||N===Q||N===ke||N===pe&&!se())G--;else if(G===0&&(N===re||N===pt))break;else if(G===0&&N===ve&&!Be())break;if(G===0&&(ie()||oe()))break;l++}T=C(U,l)}if(l<a&&i.charCodeAt(l)===ve)if(o&&T&&(!s||!Ep(T)))qc();else{l++,v();let U=l,G=0,N=0,D=0,_=!0;for(;;){l=U,G=0,N=0,D=0;while(l<a){if(I()){if(G===0&&N===0&&D===0&&me())break;continue}let V=i.charCodeAt(l);if(V===ae||V===Y||V===Se)G++;else if(V===Ee||V===Q||V===ke)G--;else if(V===we&&G===0){let Je=to(l);if(Je!==null)D=Math.max(0,D+Je);else if(_&&(l+1>=a||i.charCodeAt(l+1)!==ve))N++}else if(V===pe&&G===0&&D===0&&!se()){if(N>0&&(l+1>=a||i.charCodeAt(l+1)!==ve))N--}else if(G===0&&N===0&&D===0&&(V===re||V===pt))break;if(G===0&&N===0&&D===0&&(ie()||ue()))break;l++}if(N>0&&_){_=!1;continue}break}if(R=C(U,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=_i(R)??Br(R);if(V)T=V}}if(l<a){let U=i.charCodeAt(l);if(U===pt){l++;continue}if(U===re)l++}let A=tt(d),M=`${p?"export ":""}declare ${m} ${b}: ${T||"unknown"};`;g.push({kind:"variable",name:b,text:M,isExported:p,typeAnnotation:T,value:R,modifiers:E?[m,"const assertion"]:[m],leadingComments:A,start:d,end:l});break}while(l<a);return g}function to(d){if(i.charCodeAt(d)!==we||d+1>=a)return null;let m=i.charCodeAt(d+1);if(m===pe)return 1;if(m===ee)return-1;if(!Ct(m))return null;let p=d+2;while(p<a){let A=i.charCodeAt(p);if(!Ke(A)&&A!==gt&&A!==58&&A!==45)break;p++}let g=i.slice(d+1,p),w=i.charCodeAt(p);if(w>32&&w!==pe&&w!==ee)return null;let b=0,T=0,R=p;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===Y)b++;else if(A===Q&&b>0)b--;else if(A===pe&&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,m){l+=9,v();let p=j();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 U=i.charCodeAt(l);if(U===we)M++;else if(U===pe&&!se())M--;else if(U===Y&&M===0)break;l++}w=C(A,l)}v();let b=l<a&&i.charCodeAt(l)===Y?Xi():"{}",T=Xs(b),R=`${m?"export ":""}declare interface ${p}${g}${w?` extends ${w}`:""} ${T}`,E=tt(d);return{kind:"interface",name:p,text:R,isExported:m,extends:w||void 0,generics:g||void 0,leadingComments:E,start:d,end:l}}function rn(d,m){l+=4,v();let p=j();v();let g=mt();if(v(),l<a&&i.charCodeAt(l)===ve)l++;v();let w=l,b=0;while(l<a){if(I())continue;let A=i.charCodeAt(l);if(A===ae||A===Y||A===Se||A===we)b++;else if(A===Ee||A===Q||A===ke||A===pe&&!se())b--;else if(b===0&&A===re)break;if(b===0&&(ie()||oe()))break;l++}let T=C(w,l);if(l<a&&i.charCodeAt(l)===re)l++;let R=`${m?"export ":""}type ${p}${g} = ${T}`,E=tt(d);return{kind:"type",name:p,text:R,isExported:m,generics:g||void 0,leadingComments:E,start:d,end:l}}function Ht(d,m,p){l+=4,v();let g=j();v();let w=l;if(l<a&&i.charCodeAt(l)===Y)X(Y,Q);let b=C(d,l),T=tt(d);return{kind:"enum",name:g,text:b,isExported:m,modifiers:p?["const"]:void 0,leadingComments:T,start:d,end:l}}function Pt(d,m,p,g=!1){l+=5,v();let w=j()||"AnonymousClass";v();let b=mt();v();let T="";if(O("extends")){l+=7,v();let U=l,G=0;while(l<a){if(I())continue;let N=i.charCodeAt(l);if(N===we)G++;else if(N===pe&&!se())G--;else if(G===0&&(N===Y||O("implements")))break;l++}T=C(U,l)}let R;if(O("implements")){l+=10,v();let U=l,G=0;while(l<a){if(I())continue;let D=i.charCodeAt(l);if(D===we)G++;else if(D===pe&&!se())G--;else if(G===0&&D===Y)break;l++}let N=C(U,l);if(N)R=N.split(",").map((D)=>D.trim())}v();let E=nn(),A=`${m?g?"export default ":"export declare ":"declare "}${p?"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:m,isDefault:g,extends:T||void 0,implements:R,generics:b||void 0,modifiers:p?["abstract"]:void 0,leadingComments:M,start:d,end:l}}function nn(){if(l>=a||i.charCodeAt(l)!==Y)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")&&on("static")===Y){l+=6,v(),X(Y,Q);continue}let m=!1,p=!1,g=!1,w=!1,b=!1,T=!1,R=!1,E=!1,A=!0;while(A){v();let G=l,N=j();if(l=G,N){let D=on(N);if(D===ae||D===we||D===Ui||D===33||D===ft||D===ve||D===re||D===Q)break}if(O("private")){m=!0,l+=7;continue}if(O("protected")){p=!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)===Rs)m=!0;let M=m?[]:d,U=" ";if(p)U+="protected ";if(g)U+="static ";if(w)U+="abstract ";if(b)U+="readonly ";if(O("constructor")){l+=11,v();let G=Ot();if(v(),sf(G,M),l<a&&i.charCodeAt(l)===Y)X(Y,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let N=Vt(G);M.push(` constructor${N};`)}else if(O("get"))if(l+=3,v(),l<a&&ro(i.charCodeAt(l))){let G=sn();if(G.startsWith("#")){if(v(),l<a&&i.charCodeAt(l)===ae)Ot();if(v(),mr(),v(),l<a&&i.charCodeAt(l)===Y)X(Y,Q);else if(l<a&&i.charCodeAt(l)===re)l++;continue}v(),Ot(),v();let N=mr()||"unknown";if(v(),l<a&&i.charCodeAt(l)===Y)X(Y,Q);else if(l<a&&i.charCodeAt(l)===re)l++;M.push(`${U}get ${G}(): ${N};`)}else no("get",U,g,b,E,M);else if(O("set"))if(l+=3,v(),l<a&&ro(i.charCodeAt(l))){let G=sn();if(G.startsWith("#")){if(v(),l<a&&i.charCodeAt(l)===ae)Ot();if(v(),l<a&&i.charCodeAt(l)===Y)X(Y,Q);else if(l<a&&i.charCodeAt(l)===re)l++;continue}v();let N=Ot();if(v(),l<a&&i.charCodeAt(l)===Y)X(Y,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let D=Vt(N);M.push(`${U}set ${G}${D};`)}else no("set",U,g,b,E,M);else{let G=i.charCodeAt(l)===Ae;if(G)l++,v();let N=sn();if(!N){io();continue}so(N,U,g,b,G,w,E,M)}}return`{
|
|
215
214
|
${d.join(`
|
|
216
215
|
`)}
|
|
217
|
-
}`}function
|
|
218
|
-
${
|
|
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(`
|
|
219
218
|
`)}
|
|
220
|
-
}`}function
|
|
221
|
-
`,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
|
|
222
|
-
`&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function
|
|
223
|
-
`)&&s===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:o}}return null}function
|
|
224
|
-
`)&&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
|
|
225
|
-
`,s.index)+1,
|
|
226
|
-
`&&/\s|;/.test(e[
|
|
227
|
-
`)
|
|
228
|
-
`,i.index)+1;if(!r.has(s))continue;if(/\bexport\b/.test(e.slice(s,i.index)))continue;let o=i[1],
|
|
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]!==`
|
|
229
228
|
`)c++;while(c<e.length&&/\s/.test(e[c])&&e[c]!==`
|
|
230
|
-
`)c++;if(e[c]!=="{")continue;let
|
|
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===`
|
|
231
230
|
`&&u===0){f=c;break}c++}if(f===-1)f=e.length}if(e[f]===`
|
|
232
|
-
`)f++;t.push({name:
|
|
233
|
-
`&&r===0)t.add(n+1);n++}return t}function
|
|
234
|
-
`,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
|
|
235
|
-
`)o++;let
|
|
236
|
-
`){let o=n(),
|
|
237
|
-
${t.scriptSetup.content}`:t.script.content;if(r=x.script,x.options){let
|
|
238
|
-
`)}var
|
|
239
|
-
defineProps<${r}>()`,null)}function
|
|
240
|
-
`)&&n===0){let c=i+1;if(
|
|
241
|
-
`),r=null,n=
|
|
242
|
-
`)}var
|
|
243
|
-
${
|
|
244
|
-
${
|
|
245
|
-
...`:"")),q.debug("--- End preview ---")};if(s){let
|
|
246
|
-
`);if(r.failOnUnresolvedReExport)throw Error(
|
|
247
|
-
--- Generation Statistics ---`),q.info(`Files processed: ${o.filesProcessed}`),q.info(`Files generated: ${o.filesGenerated}`),
|
|
248
|
-
Errors:`);for(let
|
|
249
|
-
`)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(o);return q.debug("DTS generation complete!"),o}async function
|
|
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}
|
|
250
249
|
entrypoints: ${e.entrypoints.map((s)=>JSON.stringify(s)).join(", ")||"(none)"}
|
|
251
250
|
`+(e.exclude?.length?` exclude: ${e.exclude.map((s)=>JSON.stringify(s)).join(", ")}
|
|
252
|
-
`:"")+"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)=>
|
|
253
|
-
${n}`)}let i=e.entrypoints.filter((s)=>{if(
|
|
254
|
-
${n}`)}async function
|
|
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(`
|
|
255
254
|
`).find((o)=>i.test(o))??n.trim().split(`
|
|
256
255
|
`)[0];throw Error(`Built package at ${t} cannot be imported: ${s}
|
|
257
|
-
Fix the generated module at its source before publishing.`)}}async function
|
|
258
|
-
`),await
|
|
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};
|