@stacksjs/build 0.75.422 → 0.75.431
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/README.md +18 -1
- package/dist/dependency-layers.d.ts +6 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +104 -104
- package/dist/workspace.d.ts +10 -0
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var ge=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var
|
|
3
|
-
`||c==="\r"?c:" ":c;continue}if(s===o)break}continue}if(i===47&&n+1<t){let o=e.charCodeAt(n+1);if(o===47){n+=2;while(n<t&&e.charCodeAt(n)!==10)n++;continue}if(o===42){n+=2;while(n+1<t&&!(e.charCodeAt(n)===42&&e.charCodeAt(n+1)===47))n++;n+=2;continue}}r+=e[n++]}return r}function
|
|
2
|
+
var ge=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var Fc=import.meta.require;import{readFile as Gc,stat as pp,writeFile as jc}from"fs/promises";async function zo(e,t){if(Nr)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await jc(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function Pt(e){if(Nr)return globalThis.Bun.file(e).text();return Gc(e,"utf-8")}var Nr,gp;var Lr=ge(()=>{Nr=typeof globalThis.Bun<"u",gp=!Nr&&typeof process<"u"&&!!process.versions?.node});import{existsSync as _c,statSync as Vc}from"fs";import{dirname as Uc,extname as Kc,isAbsolute as Yo,join as zc,resolve as Zo}from"path";function Wr(e){try{return Vc(e).isFile()}catch{return!1}}function zt(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!Yo(r))return{resolved:null,isRelative:!1};let n=Uc(t),i=Zo(n,r);if(Wr(i))return{resolved:i,isRelative:!0};let o=Kc(i),s=Hc[o];if(s){let a=i.slice(0,-o.length);for(let c of s){let f=a+c;if(Wr(f))return{resolved:f,isRelative:!0}}}for(let a of Ho){let c=i+a;if(Wr(c))return{resolved:c,isRelative:!0}}if(_c(i))for(let a of Ho){let c=zc(i,`index${a}`);if(Wr(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function Jc(e){let t=e.length,r="",n=0;while(n<t){let i=e.charCodeAt(n);if(i===34||i===39||i===96){let o=i;r+=e[n++];while(n<t){let s=e.charCodeAt(n),a=e[n++];if(r+=o===96&&s!==o?s===10||s===13?a:" ":a,s===92&&n<t){let c=e[n++];r+=o===96?c===`
|
|
3
|
+
`||c==="\r"?c:" ":c;continue}if(s===o)break}continue}if(i===47&&n+1<t){let o=e.charCodeAt(n+1);if(o===47){n+=2;while(n<t&&e.charCodeAt(n)!==10)n++;continue}if(o===42){n+=2;while(n+1<t&&!(e.charCodeAt(n)===42&&e.charCodeAt(n+1)===47))n++;n+=2;continue}}r+=e[n++]}return r}function tn(e,t={}){let r=[],n=Jc(e);Jo.lastIndex=0;let i;while((i=Jo.exec(n))!==null){let o=!!i[1],s=i[3],a=i[0],c;if(a.includes("* as "))c="export-star-as";else if(a.includes("*"))c="export-star";else c="export-named";r.push({specifier:s,kind:c,isTypeOnly:o})}if(t.includeImports){qo.lastIndex=0;while((i=qo.exec(n))!==null)r.push({specifier:i[3],kind:"import",isTypeOnly:!!i[1]})}return r}async function rn(e,t={}){let r=new Set,n=new Map,i=[],o=[];for(let s of e){let a=Zo(s);if(!r.has(a))r.add(a),o.push(a)}while(o.length>0){let s=o.shift(),a;try{a=await Pt(s)}catch{continue}let c=tn(a,t);n.set(s,c);for(let f of c){if(!(f.specifier.startsWith(".")||Yo(f.specifier)))continue;let u=zt(f.specifier,s);if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),o.push(u.resolved)}else i.push({from:s,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:r,reExports:n,unresolved:i}}var Ho,Hc,Jo,qo;var nn=ge(()=>{Lr();Ho=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],Hc={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};Jo=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,qo=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";\n]+\s+from\s+)?(['"])([^'"]+)\2/g});import{relative as Nt}from"path";function qc(e){let t=[],r=[],n=0,i=0,o=[],s=!1,a=0,c=e.length,f=(u)=>{let l=e.slice(n,u).trim();if(n=u,!l)return;if(Yc(l)){r.push(l);return}t.push({text:l,comments:r}),r=[]};while(a<c){let u=e[a];if(s){if(u==="\\"){a+=2;continue}if(u==="`"){s=!1,a++;continue}if(u==="$"&&e[a+1]==="{"){o.push(i),i++,s=!1,a+=2;continue}a++;continue}if(u==="/"&&e[a+1]==="*"){let l=e.indexOf("*/",a+2);a=l===-1?c:l+2;continue}if(u==="/"&&e[a+1]==="/"){let l=e.indexOf(`
|
|
4
4
|
`,a);a=l===-1?c:l;continue}if(u==="'"||u==='"'){a++;while(a<c&&e[a]!==u&&e[a]!==`
|
|
5
5
|
`){if(e[a]==="\\")a++;a++}a++;continue}if(u==="`"){s=!0,a++;continue}if(u==="("||u==="["||u==="{"){i++,a++;continue}if(u===")"||u==="]"||u==="}"){if(i--,o.length>0&&u==="}"&&i===o[o.length-1])o.pop(),s=!0;a++;continue}if(i===0&&u===";"){f(a+1),a++;continue}if(i===0&&u===`
|
|
6
|
-
`){let l=e[a+1];if(l!==void 0&&/[\w$@/]/.test(l))f(a+1);a++;continue}a++}return f(c),t}function
|
|
7
|
-
`,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
|
|
8
|
-
`).map((f)=>f.trim()).filter((f)=>f.startsWith("///"))),!1;return!0});let o=i.text.replace(/;\s*$/,"").trim(),s=o.match(/^import\s+(type\s+)?([\s\S]+?)\s+from\s+(['"])([^'"]+)\3/);if(s){let c=
|
|
6
|
+
`){let l=e[a+1];if(l!==void 0&&/[\w$@/]/.test(l))f(a+1);a++;continue}a++}return f(c),t}function Yc(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(`
|
|
7
|
+
`,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 on(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 Zc(e){let t={named:[]},r=e.trim().replace(/^type\s+/,""),n=r.match(/\{([\s\S]*)\}/);if(n){for(let s of on(n[1]))t.named.push({imported:s.local,local:s.exported});r=r.replace(n[0],"")}let i=r.match(/\*\s*as\s+([\w$]+)/);if(i)t.namespaceName=i[1],r=r.replace(i[0],"");let o=r.replace(/,/g,"").trim();if(o&&Qo.test(o))t.defaultName=o;return t}function Qc(e,t){let r=e.replace(/^export\s+/,""),n=/^default\s+/.test(r);if(r=r.replace(/^default\s+/,""),n)r=r.replace(/^((?:declare\s+)?(?:abstract\s+)?(?:class|function\s*\*?|async\s+function\s*\*?))\s*(?=[(<{])/,(i,o)=>`${o.trimEnd()} ${t}`);if(/^(?:interface|type)\b/.test(r)||/^declare\b/.test(r))return r;return`declare ${r}`}function ef(e,t){let r={file:e,declarations:[],declared:new Set,imports:new Map,localExports:new Map,namedReExports:[],starReExports:[],namespaceReExports:[],verbatim:[],directives:[]},n=qc(t);for(let i of n){i.comments=i.comments.filter((c)=>{if(/^\/\/\/\s*</.test(c))return r.directives.push(...c.split(`
|
|
8
|
+
`).map((f)=>f.trim()).filter((f)=>f.startsWith("///"))),!1;return!0});let o=i.text.replace(/;\s*$/,"").trim(),s=o.match(/^import\s+(type\s+)?([\s\S]+?)\s+from\s+(['"])([^'"]+)\3/);if(s){let c=Zc(s[2]),f=s[4];if(c.defaultName)r.imports.set(c.defaultName,{specifier:f,imported:"default"});if(c.namespaceName)r.imports.set(c.namespaceName,{specifier:f,imported:"*"});for(let u of c.named)r.imports.set(u.local,{specifier:f,imported:u.imported});continue}if(/^import\s+['"]/.test(o)){r.verbatim.push(i);continue}if(s=o.match(/^export\s+(?:type\s+)?\*\s+as\s+([\w$]+)\s+from\s+(['"])([^'"]+)\2/),s){r.namespaceReExports.push({specifier:s[3],exported:s[1]});continue}if(s=o.match(/^export\s+(?:type\s+)?\*\s+from\s+(['"])([^'"]+)\1/),s){r.starReExports.push(s[2]);continue}if(s=o.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}\s+from\s+(['"])([^'"]+)\2/),s){for(let c of on(s[1]))r.namedReExports.push({specifier:s[3],imported:c.local,exported:c.exported});continue}if(s=o.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}$/),s){for(let c of on(s[1]))r.localExports.set(c.exported,c.local);continue}if(s=o.match(/^export\s+default\s+([\w$]+)$/),s&&Qo.test(s[1])){r.localExports.set("default",s[1]);continue}if(/^export\s+as\s+namespace\b/.test(o)||/^(?:export\s+)?declare\s+(?:global\b|module\s+['"])/.test(o)){r.verbatim.push(i);continue}let a=o.match(Xc);if(a){let c=!!a[1],f=a[4]??(c?"_default":null);if(f){if(r.declared.add(f),/^export\s/.test(o))r.localExports.set(c?"default":f,f);r.declarations.push({statement:i,name:f,emit:Qc(i.text,f)});continue}}r.declarations.push({statement:i,name:null,emit:i.text})}return r}function Xo(e,t){if(t.size===0)return e;let r="",n=0,i=e.length,o=`
|
|
9
9
|
`;while(n<i){let s=e[n];if(s==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2),c=a===-1?i:a+2;r+=e.slice(n,c),n=c;continue}if(s==="/"&&e[n+1]==="/"){let a=e.indexOf(`
|
|
10
10
|
`,n),c=a===-1?i:a;r+=e.slice(n,c),n=c;continue}if(s==="'"||s==='"'){let a=n+1;while(a<i&&e[a]!==s&&e[a]!==`
|
|
11
11
|
`){if(e[a]==="\\")a++;a++}r+=e.slice(n,a+1),n=a+1,o=s;continue}if(/[A-Z_$]/i.test(s)){let a=n+1;while(a<i&&/[\w$]/.test(e[a]))a++;let c=e.slice(n,a),f=t.get(c);if(f!==void 0&&o!=="."){let u=a;while(u<i&&(e[u]===" "||e[u]==="\t"))u++;let l=(e[u]===":"||e[u]==="?"&&e[u+1]===":")&&/[{;,(\n]/.test(o);r+=l?c:f}else r+=c;o="a",n=a;continue}if(r+=s,s===`
|
|
12
|
-
`||!/\s/.test(s))o=s;n++}return r}function
|
|
12
|
+
`||!/\s/.test(s))o=s;n++}return r}function es(e,t,r,n){let i=[],o=new Map,s=[e,...t.filter((N)=>N!==e)];for(let N of s){let z=r.get(N);if(z===void 0){i.push(`No declarations were generated for ${Nt(n.cwd,N)}; it is left out of the bundle`);continue}o.set(N,ef(N,z))}let a=(N,z)=>{if(!N.startsWith(".")&&!N.startsWith("/"))return null;let J=zt(N,z).resolved;return J&&o.has(J)?J:null},c=(N)=>N.startsWith(".")||N.startsWith("/"),f=new Set,u=(N)=>{let z=N;for(let J=1;f.has(z);J++)z=`${N}_${J}`;return f.add(z),z},l=new Map;for(let[N,z]of o){let J=new Map;for(let te of z.declared)J.set(te,u(te));l.set(N,J)}let p=new Map,C=(N,z,J)=>{let te=`${N}\x00${z}`,Z=p.get(te);if(!Z)Z=u(J),p.set(te,Z);return Z},E=new Map,y=new Map,x=new Set,S=(N,z,J)=>{let te=a(z,N.file);if(te){if(J==="*")return{kind:"namespace",file:te};let Z=D(te).get(J);if(!Z)i.push(`${Nt(n.cwd,N.file)}: '${J}' is not exported by '${z}'`);return Z??null}if(c(z))return i.push(`${Nt(n.cwd,N.file)}: '${z}' is not part of the bundle`),null;return J==="*"?{kind:"external-namespace",source:z}:{kind:"external",source:z,imported:J}},M=(N,z)=>{if(N.declared.has(z))return{kind:"local",name:l.get(N.file).get(z)};let J=N.imports.get(z);if(J)return S(N,J.specifier,J.imported);return i.push(`${Nt(n.cwd,N.file)}: cannot resolve exported name '${z}'`),null};function D(N){let z=E.get(N);if(z)return z;let J=new Map,te=o.get(N);if(!te||x.has(N))return J;x.add(N);let Z=new Set;for(let[Y,oe]of te.localExports){let Fe=M(te,oe);if(Fe)J.set(Y,Fe)}for(let Y of te.namedReExports){let oe=S(te,Y.specifier,Y.imported);if(oe)J.set(Y.exported,oe)}for(let Y of te.namespaceReExports){let oe=S(te,Y.specifier,"*");if(oe)J.set(Y.exported,oe)}for(let Y of te.starReExports){let oe=a(Y,N);if(oe){for(let[Fe,Ve]of D(oe))if(Fe!=="default"&&!J.has(Fe))J.set(Fe,Ve);for(let Fe of y.get(oe)??[])Z.add(Fe)}else if(c(Y))i.push(`${Nt(n.cwd,N)}: '${Y}' is not part of the bundle`);else Z.add(Y)}return x.delete(N),E.set(N,J),y.set(N,Z),J}let O=new Map,H=[],K=(N,z)=>{switch(N.kind){case"local":return N.name;case"external":return C(N.source,N.imported,N.imported==="default"?z:N.imported);case"external-namespace":return C(N.source,"*",z);case"namespace":return me(N.file,z)}};function me(N,z){let J=O.get(N);if(J)return J;let te=u(z);O.set(N,te);let Z=[];for(let[Y,oe]of D(N)){if(Y==="default")continue;let Fe=K(oe,Y);Z.push(Fe===Y?Y:`${Fe} as ${Y}`)}if(y.get(N)?.size)i.push(`${Nt(n.cwd,N)}: 'export * from' an external module cannot be expressed inside namespace '${te}'`);return H.push(`declare namespace ${te} {
|
|
13
13
|
export { ${Z.join(", ")} };
|
|
14
|
-
}`),te}let I=[],j=[],T=new Set;for(let[N,z]of o){for(let Z of z.directives)T.add(Z);let J=new Map;for(let[Z,Y]of l.get(N))if(Z!==Y)J.set(Z,Y);for(let[Z,Y]of z.imports){if(z.declared.has(Z))continue;let oe=S(z,Y.specifier,Y.imported);if(!oe)continue;let Fe=K(oe,Z);if(Fe!==Z)J.set(Z,Fe)}let te=[];for(let Z of z.declarations){if(n.keepComments)te.push(...Z.statement.comments);let Y=
|
|
14
|
+
}`),te}let I=[],j=[],T=new Set;for(let[N,z]of o){for(let Z of z.directives)T.add(Z);let J=new Map;for(let[Z,Y]of l.get(N))if(Z!==Y)J.set(Z,Y);for(let[Z,Y]of z.imports){if(z.declared.has(Z))continue;let oe=S(z,Y.specifier,Y.imported);if(!oe)continue;let Fe=K(oe,Z);if(Fe!==Z)J.set(Z,Fe)}let te=[];for(let Z of z.declarations){if(n.keepComments)te.push(...Z.statement.comments);let Y=Xo(Z.emit,J);if(!/[;}]$/.test(Y))Y+=";";te.push(Y)}for(let Z of z.verbatim){if(n.keepComments)j.push(...Z.comments);j.push(Xo(Z.text,J))}if(te.length>0)I.push(`// From: ${Nt(n.cwd,N)}
|
|
15
15
|
${te.join(`
|
|
16
16
|
`)}`)}let Re=D(e),V=[],pe=[];for(let[N,z]of Re){if(z.kind==="external"){pe.push(`export { ${z.imported===N?N:`${z.imported} as ${N}`} } from '${z.source}';`);continue}if(z.kind==="external-namespace"){pe.push(`export * as ${N} from '${z.source}';`);continue}let J=K(z,N==="default"?"_default":N);V.push(J===N?N:`${J} as ${N}`)}for(let N of y.get(e)??[])pe.push(`export * from '${N}';`);let ee=new Map;for(let[N,z]of p){let[J,te]=N.split("\x00"),Z=ee.get(J)??{named:[],defaults:[],namespaces:[]};if(ee.set(J,Z),te==="*")Z.namespaces.push(z);else if(te==="default")Z.defaults.push(z);else Z.named.push(te===z?z:`${te} as ${z}`)}let ie=[];for(let[N,z]of[...ee].sort(([J],[te])=>J.localeCompare(te))){for(let J of z.defaults)ie.push(`import ${J} from '${N}';`);for(let J of z.namespaces)ie.push(`import * as ${J} from '${N}';`);if(z.named.length>0)ie.push(`import { ${z.named.join(", ")} } from '${N}';`)}let ne=[];if(T.size>0)ne.push([...T].join(`
|
|
17
17
|
`));if(ne.push(`/**
|
|
@@ -24,28 +24,28 @@ ${te.join(`
|
|
|
24
24
|
`)),{content:`${ne.join(`
|
|
25
25
|
|
|
26
26
|
`)}
|
|
27
|
-
`,files:[...o.keys()],exportCount:Re.size,warnings:i}}var
|
|
27
|
+
`,files:[...o.keys()],exportCount:Re.size,warnings:i}}var Qo,Xc;var ts=ge(()=>{nn();Qo=/^[A-Z_$][\w$]*$/i;Xc=/^(?: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 dr(e){if(tf)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 tf;var sn=ge(()=>{tf=typeof globalThis.Bun?.hash==="function"});import{existsSync as mr,mkdirSync as rf,readFileSync as ln,renameSync as nf,rmSync as rs,statSync as is,writeFileSync as ns}from"fs";import{join as os,relative as Br,resolve as of}from"path";class cn{cacheDir;manifestPath;manifest=null;configHash;constructor(e){this.cacheDir=of(e.cwd,Gr),this.manifestPath=os(this.cacheDir,sf),this.configHash=this.hashConfig(e)}hashConfig(e){let t={keepComments:e.keepComments,importOrder:e.importOrder,outputStructure:e.outputStructure,isolatedDeclarations:e.isolatedDeclarations,declarationMap:e.declarationMap,indentStyle:e.indentStyle,indentSize:e.indentSize,prettier:e.prettier,typeMappings:e.typeMappings?{includeDefaults:e.typeMappings.includeDefaults,presets:e.typeMappings.presets,cacheKey:e.typeMappings.cacheKey,rules:e.typeMappings.rules.map((r)=>({pattern:typeof r.pattern==="string"?{kind:"string",value:r.pattern}:{kind:"regex",source:r.pattern.source,flags:r.pattern.flags},replacement:r.replacement,global:r.global,priority:r.priority,hasCondition:Boolean(r.condition)}))}:void 0,lineEnding:e.lineEnding,normalizeOutput:e.normalizeOutput,declarationOrder:e.declarationOrder,plugins:e.plugins?.map((r)=>({name:r.name,version:r.version,cacheKey:r.cacheKey}))};return String(dr(JSON.stringify(t)))}hashString(e){return String(dr(e))}load(){try{if(!mr(this.manifestPath))return!1;let e=ln(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==an)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:an,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!mr(this.cacheDir))rf(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{ns(e,JSON.stringify(this.manifest,null,2)),nf(e,this.manifestPath)}finally{if(mr(e))rs(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=Br(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=is(e),{mtimeMs:o,ctimeMs:s}=i;if(i.size!==n.sourceSize)return null;if(o!==n.sourceMtime||s!==n.sourceCtime){let a=ln(e,"utf-8");if(this.hashString(a)!==n.sourceHash)return null;n.sourceMtime=o,n.sourceCtime=s}return n.dtsContent}catch{return null}}update(e,t,r,n){if(!this.manifest)this.manifest={version:an,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=Br(n,e),o,s,a;try{let c=is(e);o=c.mtimeMs,s=c.ctimeMs,a=c.size}catch{o=Date.now(),s=o,a=Buffer.byteLength(t)}this.manifest.entries[i]={sourcePath:i,sourceHash:this.hashString(t),sourceMtime:o,sourceCtime:s,sourceSize:a,dtsContent:r,dtsHash:this.hashString(r),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let r=Br(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(mr(this.manifestPath))rs(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)=>Br(t,i)));for(let i of Object.keys(this.manifest.entries))if(!n.has(i))delete this.manifest.entries[i],r++;return r}}function ss(e){let t=os(e,".gitignore");try{let r="";if(mr(t))r=ln(t,"utf-8");if(!r.split(/\r?\n/).some((n)=>n.trim()===Gr||n.trim()===`${Gr}/`)){let n=r.trimEnd(),i=`${n}${n?`
|
|
28
28
|
|
|
29
29
|
`:""}# dtsx cache
|
|
30
30
|
${Gr}/
|
|
31
|
-
`;ts(t,i)}}catch{}}var on=3,Gr=".dtsx-cache",Xc="manifest.json";var ns=ge(()=>{nn()});function os(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 ss=()=>{};function Ht(e){return as[e]>=as[jr]}function tf(){if(!ef)return"";return`[${new Date().toISOString().slice(11,23)}] `}function rf(e,t){let r=tf();if(e||r)return[`${r}${e}`,...t];return t}function Jt(e,t,r){let n=rf(t,r);if(ls){ls(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 cs(e){return{debug:(...t)=>{if(Ht("debug"))Jt("debug",e,t)},info:(...t)=>{if(Ht("info"))Jt("info",e,t)},warn:(...t)=>{if(Ht("warn"))Jt("warn",e,t)},error:(...t)=>{if(Ht("error"))Jt("error",e,t)},setLevel:(t)=>{jr=t},getLevel:()=>jr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return cs(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(Ht("debug"))Jt("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Ht("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Jt("info",e,[t])}}}function ln(e){jr=e}var as,jr="info",Qc="[dtsx]",ef=!1,ls=null,q;var fs=ge(()=>{as={debug:0,info:1,warn:2,error:3,silent:4};q=cs(Qc)});import nf from"process";import{existsSync as us,statSync as hs}from"fs";import{existsSync as of,mkdirSync as Sp,readdirSync as $p,readFileSync as sf,writeFileSync as Ap}from"fs";import{homedir as qt}from"os";import{dirname as Rp,resolve as st}from"path";import vi from"process";import{existsSync as ds,statSync as ms}from"fs";import{existsSync as Rn,mkdirSync as af,readdirSync as lf,writeFileSync as cf}from"fs";import{homedir as Yt}from"os";import{dirname as ps,resolve as Ye}from"path";import Lt from"process";import{join as ff,relative as uf,resolve as gs}from"path";import ai from"process";import{existsSync as Zs,mkdirSync as Wp,readdirSync as Bp,writeFileSync as Gp}from"fs";import{homedir as cn}from"os";import{dirname as Vp,resolve as qe}from"path";import gr from"process";import{join as hf,relative as df,resolve as ys}from"path";import li from"process";import{existsSync as Xs,mkdirSync as Jp,readdirSync as qp,writeFileSync as Yp}from"fs";import{dirname as Xp,resolve as ci}from"path";import Pn from"process";import{Buffer as Ot}from"buffer";import{createCipheriv as mf,createDecipheriv as pf,randomBytes as fn}from"crypto";import{closeSync as un,createReadStream as Cs,createWriteStream as gf,existsSync as hn,fsyncSync as ws,openSync as Es,writeFileSync as yf}from"fs";import{access as Cf,constants as vs,mkdir as wf,readdir as _r,rename as bs,stat as Zt,unlink as Vr,writeFile as dn}from"fs/promises";import{join as Xt}from"path";import Ue from"process";import{pipeline as Ef}from"stream/promises";import{createGzip as Ss}from"zlib";import Qt from"process";import Et from"process";import{Buffer as yt}from"buffer";import{createCipheriv as vf,createDecipheriv as bf,randomBytes as mn}from"crypto";import{closeSync as pn,createReadStream as $s,createWriteStream as Sf,existsSync as Ur,fsyncSync as As,openSync as xs,writeFileSync as $f}from"fs";import{access as Af,constants as Ts,mkdir as xf,readdir as Kr,rename as Rs,stat as er,unlink as zr,writeFile as gn}from"fs/promises";import{isAbsolute as Tf,join as tr,resolve as Rf}from"path";import ye from"process";import{pipeline as Pf}from"stream/promises";import{createGzip as Ps}from"zlib";import rr from"process";import vt from"process";import Hr from"process";import{existsSync as Jr}from"fs";import{resolve as yn}from"path";import{existsSync as Of}from"fs";import{existsSync as kf,readdirSync as Mf}from"fs";import{extname as Cn,resolve as Os}from"path";import Df from"process";import{join as If,relative as Ff,resolve as ks}from"path";import fi from"process";import{Buffer as Ct}from"buffer";import{createCipheriv as Nf,createDecipheriv as Lf,randomBytes as wn}from"crypto";import{closeSync as En,createReadStream as Ms,createWriteStream as Wf,existsSync as qr,fsyncSync as Ds,openSync as Is,writeFileSync as Bf}from"fs";import{access as Gf,constants as Fs,mkdir as jf,readdir as Yr,rename as Ns,stat as ir,unlink as Zr,writeFile as vn}from"fs/promises";import{isAbsolute as _f,join as nr,resolve as Vf}from"path";import Ce from"process";import{pipeline as Uf}from"stream/promises";import{createGzip as Ls}from"zlib";import or from"process";import bt from"process";import Xr from"process";import{existsSync as Qr}from"fs";import{resolve as bn}from"path";import{existsSync as Kf}from"fs";class Qs{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!us(e))return!0;return hs(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=us(r)?hs(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class ea{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Jf(e,t){this[e]=Hf.bind(null,t)}class jn{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!ds(e))return!0;return ms(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=ds(r)?ms(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class _n{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Zf(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function Xf(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Qf(e){return e.getStats().size*2}function Vn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Te(t[0])&&"id"in t[0]&&t[0].id===3&&Te(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Te(t)&&Te(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Te(e)&&"arr"in e&&Array.isArray(e.arr)&&Te(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Te(t[0])&&Te(e[0])){let n=[...t];for(let i of e)if(Te(i)&&"name"in i){if(!n.find((o)=>Te(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(Te(i)&&"path"in i){if(!n.find((o)=>Te(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((o)=>hi(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Te(t)||!Te(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Te(i)&&Te(r[n]))r[n]=Vn(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Te(i[0])&&Te(r[n][0])){let o=[...i];for(let s of r[n])if(Te(s)&&"name"in s){if(!o.find((a)=>Te(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(Te(s)&&"path"in s){if(!o.find((a)=>Te(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>hi(a,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function hi(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!hi(e[r],t[r]))return!1;return!0}if(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(!hi(e[i],t[i]))return!1}return!0}return!1}function Te(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function eu(e,t){if(!Xs(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 Vn(t,n)}catch{return null}}catch{return null}}async function tu({name:e="",cwd:t,defaultConfig:r}){let n=t||Pn.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let a of i){let c=ci(n,`${s}${a}`),f=await eu(c,r);if(f!==null)return f}try{let s=ci(n,"package.json");if(Xs(s)){let a=(await import(s))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return Vn(r,a)}catch{}}}catch{}return r}function ru(e,t={}){let r=li.cwd();while(r.includes("storage"))r=ys(r,"..");let n=ys(r,e||"");if(t?.relative)return df(li.cwd(),n);return n}async function iu(){try{let e=await tu({name:"clarity",defaultConfig:ii,cwd:li.cwd(),endpoint:"",headers:{}});return{...ii,...e}}catch{return ii}}function De(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nu(){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 ra{async format(e){let t=await nu(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Qt.pid,hostname:t(),environment:Qt.env.NODE_ENV||"development",platform:Qt.platform,version:Qt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qt.env.NODE_ENV||Qt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class di{name;fileLocks=new Map;currentKeyId=null;keys=new Map;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 ra,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??Ue.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ni,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ni};return{...ni,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory: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,o=3,s=1000;while(i<o)try{try{try{await Cf(this.config.logDirectory,vs.F_OK|vs.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await wf(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:Ot.from(e);try{if(!hn(this.currentLogFile))await dn(this.currentLogFile,"",{mode:420});if(n=Es(this.currentLogFile,"a",420),yf(n,a,{flag:"a"}),ws(n),n!==void 0)un(n),n=void 0;if((await Zt(this.currentLogFile)).size===0){if(await dn(this.currentLogFile,a,{flag:"w",mode:420}),(await Zt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let l=s*2**i;await new Promise((p)=>setTimeout(p,l)),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{un(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Xt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Xt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Xt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(De())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return fn(16).toString("hex")}generateKey(){return fn(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=fn(16),n=mf("aes-256-gcm",t,r),i=Ot.concat([n.update(e,"utf8"),n.final()]),o=n.getAuthTag();return{encrypted:Ot.concat([r,i,o]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Ss(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Ot.from(Ot.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(De())return;let e=await Zt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await _r(this.config.logDirectory),o=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await Zt(r).catch(()=>null))try{if(await bs(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Vr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await dn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await Zt(r).catch(()=>null))await bs(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await _r(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await Vr(Xt(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Cs(e),n=gf(t),i=Ss();await Ef(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()})),hn(this.currentLogFile))try{let e=Es(this.currentLogFile,"r+");ws(e),un(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(!De()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await _r(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Vr(Xt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Ae.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,a=(C)=>C.replace(this.ANSI_PATTERN,"");if(!this.fancy){let C=[];if(s)C.push(t);if(o==="warning")C.push("WARN");else if(o==="error")C.push("ERROR");else if(r)C.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)C.push(n.replace(/[[\]]/g,""));return C.push(i),C.join(" ")}let c=Ue.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${Ae.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,l=a(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);if(this.fancy&&!De()){let f=ha[e],u=this.options.showTags!==!1&&this.name?Ae.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ae.gray(s),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ae.green(s),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.error(l),a){let p=a.split(`
|
|
31
|
+
`;ns(t,i)}}catch{}}var an=3,Gr=".dtsx-cache",sf="manifest.json";var as=ge(()=>{sn()});function ls(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 cs=()=>{};function Ht(e){return fs[e]>=fs[jr]}function cf(){if(!lf)return"";return`[${new Date().toISOString().slice(11,23)}] `}function ff(e,t){let r=cf();if(e||r)return[`${r}${e}`,...t];return t}function Jt(e,t,r){let n=ff(t,r);if(us){us(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 hs(e){return{debug:(...t)=>{if(Ht("debug"))Jt("debug",e,t)},info:(...t)=>{if(Ht("info"))Jt("info",e,t)},warn:(...t)=>{if(Ht("warn"))Jt("warn",e,t)},error:(...t)=>{if(Ht("error"))Jt("error",e,t)},setLevel:(t)=>{jr=t},getLevel:()=>jr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return hs(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(Ht("debug"))Jt("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Ht("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Jt("info",e,[t])}}}function fn(e){jr=e}var fs,jr="info",af="[dtsx]",lf=!1,us=null,q;var ds=ge(()=>{fs={debug:0,info:1,warn:2,error:3,silent:4};q=hs(af)});import uf from"process";import{existsSync as ms,statSync as ps}from"fs";import{existsSync as hf,mkdirSync as Fp,readdirSync as Np,readFileSync as df,writeFileSync as Lp}from"fs";import{homedir as qt}from"os";import{dirname as Gp,resolve as st}from"path";import vi from"process";import{existsSync as gs,statSync as ys}from"fs";import{existsSync as On,mkdirSync as mf,readdirSync as pf,writeFileSync as gf}from"fs";import{homedir as Yt}from"os";import{dirname as Cs,resolve as Ye}from"path";import Lt from"process";import{join as yf,relative as Cf,resolve as ws}from"path";import ai from"process";import{existsSync as ea,mkdirSync as Yp,readdirSync as Zp,writeFileSync as Xp}from"fs";import{homedir as un}from"os";import{dirname as tg,resolve as qe}from"path";import gr from"process";import{join as wf,relative as Ef,resolve as Es}from"path";import li from"process";import{existsSync as ta,mkdirSync as sg,readdirSync as ag,writeFileSync as lg}from"fs";import{dirname as fg,resolve as ci}from"path";import kn from"process";import{Buffer as Ot}from"buffer";import{createCipheriv as vf,createDecipheriv as bf,randomBytes as hn}from"crypto";import{closeSync as dn,createReadStream as vs,createWriteStream as Sf,existsSync as mn,fsyncSync as bs,openSync as Ss,writeFileSync as $f}from"fs";import{access as Af,constants as $s,mkdir as xf,readdir as _r,rename as As,stat as Zt,unlink as Vr,writeFile as pn}from"fs/promises";import{join as Xt}from"path";import Ue from"process";import{pipeline as Tf}from"stream/promises";import{createGzip as xs}from"zlib";import Qt from"process";import Et from"process";import{Buffer as yt}from"buffer";import{createCipheriv as Rf,createDecipheriv as Pf,randomBytes as gn}from"crypto";import{closeSync as yn,createReadStream as Ts,createWriteStream as Of,existsSync as Ur,fsyncSync as Rs,openSync as Ps,writeFileSync as kf}from"fs";import{access as Mf,constants as Os,mkdir as Df,readdir as Kr,rename as ks,stat as er,unlink as zr,writeFile as Cn}from"fs/promises";import{isAbsolute as If,join as tr,resolve as Ff}from"path";import ye from"process";import{pipeline as Nf}from"stream/promises";import{createGzip as Ms}from"zlib";import rr from"process";import vt from"process";import Hr from"process";import{existsSync as Jr}from"fs";import{resolve as wn}from"path";import{existsSync as Lf}from"fs";import{existsSync as Wf,readdirSync as Bf}from"fs";import{extname as En,resolve as Ds}from"path";import Gf from"process";import{join as jf,relative as _f,resolve as Is}from"path";import fi from"process";import{Buffer as Ct}from"buffer";import{createCipheriv as Vf,createDecipheriv as Uf,randomBytes as vn}from"crypto";import{closeSync as bn,createReadStream as Fs,createWriteStream as Kf,existsSync as qr,fsyncSync as Ns,openSync as Ls,writeFileSync as zf}from"fs";import{access as Hf,constants as Ws,mkdir as Jf,readdir as Yr,rename as Bs,stat as ir,unlink as Zr,writeFile as Sn}from"fs/promises";import{isAbsolute as qf,join as nr,resolve as Yf}from"path";import Ce from"process";import{pipeline as Zf}from"stream/promises";import{createGzip as Gs}from"zlib";import or from"process";import bt from"process";import Xr from"process";import{existsSync as Qr}from"fs";import{resolve as $n}from"path";import{existsSync as Xf}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),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!ms(e))return!0;return ps(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=ms(r)?ps(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class ia{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function tu(e,t){this[e]=eu.bind(null,t)}class Vn{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!gs(e))return!0;return ys(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=gs(r)?ys(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Un{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function nu(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function ou(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function su(e){return e.getStats().size*2}function Kn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Te(t[0])&&"id"in t[0]&&t[0].id===3&&Te(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Te(t)&&Te(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Te(e)&&"arr"in e&&Array.isArray(e.arr)&&Te(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Te(t[0])&&Te(e[0])){let n=[...t];for(let i of e)if(Te(i)&&"name"in i){if(!n.find((o)=>Te(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(Te(i)&&"path"in i){if(!n.find((o)=>Te(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((o)=>hi(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Te(t)||!Te(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Te(i)&&Te(r[n]))r[n]=Kn(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Te(i[0])&&Te(r[n][0])){let o=[...i];for(let s of r[n])if(Te(s)&&"name"in s){if(!o.find((a)=>Te(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(Te(s)&&"path"in s){if(!o.find((a)=>Te(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>hi(a,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function hi(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!hi(e[r],t[r]))return!1;return!0}if(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(!hi(e[i],t[i]))return!1}return!0}return!1}function Te(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function au(e,t){if(!ta(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 Kn(t,n)}catch{return null}}catch{return null}}async function lu({name:e="",cwd:t,defaultConfig:r}){let n=t||kn.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let a of i){let c=ci(n,`${s}${a}`),f=await au(c,r);if(f!==null)return f}try{let s=ci(n,"package.json");if(ta(s)){let a=(await import(s))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return Kn(r,a)}catch{}}}catch{}return r}function cu(e,t={}){let r=li.cwd();while(r.includes("storage"))r=Es(r,"..");let n=Es(r,e||"");if(t?.relative)return Ef(li.cwd(),n);return n}async function fu(){try{let e=await lu({name:"clarity",defaultConfig:ii,cwd:li.cwd(),endpoint:"",headers:{}});return{...ii,...e}}catch{return ii}}function De(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function uu(){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 oa{async format(e){let t=await uu(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Qt.pid,hostname:t(),environment:Qt.env.NODE_ENV||"development",platform:Qt.platform,version:Qt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qt.env.NODE_ENV||Qt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class di{name;fileLocks=new Map;currentKeyId=null;keys=new Map;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={...Dn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new oa,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??Ue.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ni,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ni};return{...ni,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Dn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let n,i=0,o=3,s=1000;while(i<o)try{try{try{await Af(this.config.logDirectory,$s.F_OK|$s.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await xf(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:Ot.from(e);try{if(!mn(this.currentLogFile))await pn(this.currentLogFile,"",{mode:420});if(n=Ss(this.currentLogFile,"a",420),$f(n,a,{flag:"a"}),bs(n),n!==void 0)dn(n),n=void 0;if((await Zt(this.currentLogFile)).size===0){if(await pn(this.currentLogFile,a,{flag:"w",mode:420}),(await Zt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let l=s*2**i;await new Promise((p)=>setTimeout(p,l)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{dn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Xt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Xt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Xt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(De())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return hn(16).toString("hex")}generateKey(){return hn(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=hn(16),n=vf("aes-256-gcm",t,r),i=Ot.concat([n.update(e,"utf8"),n.final()]),o=n.getAuthTag();return{encrypted:Ot.concat([r,i,o]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=xs(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Ot.from(Ot.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(De())return;let e=await Zt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await _r(this.config.logDirectory),o=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await Zt(r).catch(()=>null))try{if(await As(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Vr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.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,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await Zt(r).catch(()=>null))await As(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await _r(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await Vr(Xt(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=vs(e),n=Sf(t),i=xs();await Tf(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()})),mn(this.currentLogFile))try{let e=Ss(this.currentLogFile,"r+");bs(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(!De()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await _r(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Vr(Xt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Ae.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,a=(C)=>C.replace(this.ANSI_PATTERN,"");if(!this.fancy){let C=[];if(s)C.push(t);if(o==="warning")C.push("WARN");else if(o==="error")C.push("ERROR");else if(r)C.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)C.push(n.replace(/[[\]]/g,""));return C.push(i),C.join(" ")}let c=Ue.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${Ae.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,l=a(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);if(this.fancy&&!De()){let f=pa[e],u=this.options.showTags!==!1&&this.name?Ae.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ae.gray(s),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ae.green(s),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.error(l),a){let p=a.split(`
|
|
32
32
|
`);for(let C of p)if(C.trim()&&!C.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:Ae.gray(` ${C}`),level:e,showTimestamp:!1}))}break}}else if(!De()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}if(!this.shouldLog(e))return;let c=`${o} ${this.environment}.${e.toUpperCase()}: ${s}
|
|
33
33
|
`;if(a)c+=`${a}
|
|
34
34
|
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!De()){let r=this.options.showTags!==!1&&this.name?Ae.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:Ae.blue("\u25D0"),tag:r,message:`${Ae.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
35
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!De()){let f=this.options.showTags!==!1&&this.name?Ae.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:Ae.green("\u2713"),tag:f,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!De())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 di(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(De())throw Error("createReadStream is not supported in browser environments");if(!
|
|
35
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!De()){let f=this.options.showTags!==!1&&this.name?Ae.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:Ae.green("\u2713"),tag:f,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!De())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 di(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(De())throw Error("createReadStream is not supported in browser environments");if(!mn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return vs(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=Ot.isBuffer(e)?e:Ot.from(e,"base64"),i=n.slice(0,16),o=n.slice(-16),s=n.slice(16,-16),a=bf("aes-256-gcm",r,i);return a.setAuthTag(o),Ot.concat([a.update(s),a.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return De()}isServerMode(){return!De()}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&&!De()){let o=e.split(`
|
|
36
36
|
`),s=Math.max(...o.map((u)=>u.length))+2,a=`\u250C${"\u2500".repeat(s)}\u2510`,c=`\u2514${"\u2500".repeat(s)}\u2518`,f=o.map((u)=>{let l=" ".repeat(s-u.length-2);return`\u2502 ${u}${l} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:Ae.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Ae.cyan(a)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:Ae.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:Ae.cyan(c),showTimestamp:!1}))}else if(!De())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
37
37
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(De())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ae.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Ue.stdin.removeListener("data",r);try{if(typeof Ue.stdin.setRawMode==="function")Ue.stdin.setRawMode(!1)}catch{}Ue.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Ue.stdin.setRawMode==="function")Ue.stdin.setRawMode(!0)}catch{}Ue.stdin.resume(),Ue.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let i=/%([sdijfo%])/g,o=0;if(r=e.replace(i,(s,a)=>{if(a==="%")return"%";if(o>=t.length)return s;let c=t[o++];switch(a){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}}),o<t.length)r+=` ${t.slice(o).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!De()){let i=this.options.showTags!==!1&&this.name?Ae.gray(this.formatTag(this.name)):"",o=Ae.blue("\u25D0");console.error(`${o} ${i} ${Ae.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
38
38
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||De()||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||De())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,n)),i!==void 0)this.activeProgressBar.message=i;let o=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,o)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||De())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||De())return;Ue.stdout.write(`${"\r".padEnd(Ue.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||De()||!Ue.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=Ae.green("\u2501".repeat(n)),s=Ae.gray("\u2501".repeat(i)),a=`[${o}${s}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||r===100?Ae.green("\u2713"):Ae.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${Ae.gray(this.formatTag(this.name))}`:"",p=`\r${u}${l} ${a} ${c}${f}`,C=Ue.stdout.columns||80,E=" ".repeat(Math.max(0,C-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${E}`,Ue.stdout.write(e.lastRenderedLine),t)Ue.stdout.write(`
|
|
39
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||De()||!Ue.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(De()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await _r(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=Xt(this.config.logDirectory,n);if(e.before)try{if((await Zt(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Vr(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 ri(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((o)=>we(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(we(i)&&"path"in i){if(!n.find((o)=>we(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((o)=>mi(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!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]=ri(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 o=[...i];for(let s of r[n])if(we(s)&&"name"in s){if(!o.find((a)=>we(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(we(s)&&"path"in s){if(!o.find((a)=>we(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>mi(a,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function Un(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ri(e,t);if(Array.isArray(e))return r==="replace"?t:ri(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 o=t[i],s=n[i];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(s))if(r==="replace")n[i]=o;else n[i]=ri(s,o);else if(we(o)&&we(s))n[i]=Un(s,o,r);else n[i]=o}return n}function mi(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(!mi(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(!mi(e[i],t[i]))return!1}return!0}return!1}function we(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ei(e,t,r="replace"){if(!Zs(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 Un(t,i,r)}catch{return null}}catch{return null}}function ou(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let l=[...a,f],p=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),C=`${n}_${l.map(p).join("_")}`,E=`${n}_${l.map((y)=>y.toUpperCase()).join("_")}`;if(r)ze.info(`Checking environment variable ${C} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=o(u,l);else{let y=gr.env[C]||gr.env[E];if(y!==void 0){if(r)ze.info(`Using environment variable ${y?C:E} for config ${e}.${l.join(".")}`);if(typeof u==="number")c[f]=Number(y);else if(typeof u==="boolean")c[f]=y.toLowerCase()==="true";else if(Array.isArray(u))try{let x=JSON.parse(y);if(Array.isArray(x))c[f]=x;else c[f]=y.split(",").map((S)=>S.trim())}catch{c[f]=y.split(",").map((x)=>x.trim())}else c[f]=y}}}return c}return o(i)}async function su({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:o=!1,checkEnv:s=!0,arrayStrategy:a="replace"}){let c=s&&typeof i==="object"&&i!==null&&!Array.isArray(i)?ou(e,i,o):i,f=r||gr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)ze.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),p=[`${e}.config`,`.${e}.config`].filter(Boolean),C=t?[t,`.${t}`]:[],E=t?[`${t}.config`,`.${t}.config`]:[],y=Array.from(new Set([f,qe(f,"config"),qe(f,".config"),n?qe(f,n):void 0].filter(Boolean)));for(let x of y){if(o)ze.info(`Searching for configuration in: ${x}`);let S=[qe(f,"config"),qe(f,".config")].concat(n?[qe(f,n)]:[]).includes(x)?[...l,...p,...C,...E]:[...p,...l,...E,...C];for(let M of S)for(let D of u){let O=qe(x,`${M}${D}`),H=await ei(O,c,a);if(H!==null){if(o)ze.success(`Configuration loaded from: ${O}`);return H}}}if(e){let x=qe(cn(),".config",e),S=["config",`${e}.config`];if(t)S.push(`${t}.config`);if(o)ze.info(`Checking user config directory: ${x}`);for(let M of S)for(let D of u){let O=qe(x,`${M}${D}`),H=await ei(O,c,a);if(H!==null){if(o)ze.success(`Configuration loaded from user config directory: ${O}`);return H}}}if(e){let x=qe(cn(),".config"),S=[`.${e}.config`];if(t)S.push(`.${t}.config`);if(o)ze.info(`Checking user config directory for dotfile configs: ${x}`);for(let M of S)for(let D of u){let O=qe(x,`${M}${D}`),H=await ei(O,c,a);if(H!==null){if(o)ze.success(`Configuration loaded from user config directory dotfile: ${O}`);return H}}}if(e){let x=cn(),S=[`.${e}.config`,`.${e}`];if(t)S.push(`.${t}.config`),S.push(`.${t}`);if(o)ze.info(`Checking user home directory for dotfile configs: ${x}`);for(let M of S)for(let D of u){let O=qe(x,`${M}${D}`),H=await ei(O,c,a);if(H!==null){if(o)ze.success(`Configuration loaded from user home directory: ${O}`);return H}}}try{let x=qe(f,"package.json");if(Zs(x)){let S=await import(x),M=S[e];if(!M&&t){if(M=S[t],M&&o)ze.success(`Using alias "${t}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(o)ze.success(`Configuration loaded from package.json: ${M===S[e]?e:t}`);return Un(c,M,a)}catch(D){if(o)ze.warn("Failed to merge package.json config:",D)}}}catch(x){if(o)ze.warn("Failed to load package.json:",x)}if(o)ze.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function au(e,t={}){let r=ai.cwd();while(r.includes("storage"))r=gs(r,"..");let n=gs(r,e||"");if(t?.relative)return uf(ai.cwd(),n);return n}async function lu(){try{let e=await su({name:"clarity",alias:"logging",defaultConfig:oi,cwd:ai.cwd()});return{...oi,...e||{}}}catch{return oi}}function Le(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cu(){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 ia{async format(e){let t=await cu(),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 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={...Mn},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??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(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...si,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...si};return{...si,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Mn.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,o=3,s=1000;while(i<o)try{try{try{await Af(this.config.logDirectory,Ts.F_OK|Ts.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await xf(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:yt.from(e);try{if(!Ur(this.currentLogFile))await gn(this.currentLogFile,"",{mode:420});if(n=xs(this.currentLogFile,"a",420),$f(n,a,{flag:"a"}),As(n),n!==void 0)pn(n),n=void 0;if((await er(this.currentLogFile)).size===0){if(await gn(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<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let l=s*2**i;await new Promise((p)=>setTimeout(p,l)),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{pn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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(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(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return mn(16).toString("hex")}generateKey(){return mn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=mn(16),n=vf("aes-256-gcm",t,r),i=yt.isBuffer(e)?e:yt.from(e,"utf8"),o=n.update(i),s=n.final(),a=o.length+s.length,c=n.getAuthTag(),f=yt.allocUnsafe(16+a+16);return r.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Ps(),i=[];n.on("data",(o)=>i.push(o)),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(Le())return;if(!this.shouldWriteToFile())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 Kr(this.config.logDirectory),o=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await er(r).catch(()=>null))try{if(await Rs(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await zr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await gn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await er(r).catch(()=>null))await Rs(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await Kr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await zr(tr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=$s(e),n=Sf(t),i=Ps();await Pf(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()})),Ur(this.currentLogFile))try{let e=xs(this.currentLogFile,"r+");As(e),pn(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 Kr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await zr(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.shouldStyleConsole()?ae.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:o,showTimestamp:s=!0}=e,a=(C)=>C.replace(this.ANSI_PATTERN,"");if(!this.fancy){let C=[];if(s)C.push(t);if(o==="warning")C.push("WARN");else if(o==="error")C.push("ERROR");else if(r)C.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)C.push(n.replace(/[[\]]/g,""));return C.push(i),C.join(" ")}let c=ye.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${ae.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,l=a(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=ae.underline(ae.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>ae.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>ae.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>ae.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>ae.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>ae.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(Tf(t)||t.startsWith("./")||t.startsWith("../"))t=Rf(t);else return null;return Ur(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":da[e],p=this.options.showTags!==!1&&this.name?ae.gray(this.formatTag(this.name)):"",C;switch(e){case"debug":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:ae.gray(c),level:e}),console.error(C);break;case"info":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.warn(C);break;case"success":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:ae.green(c),level:e}),console.error(C);break;case"warning":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.warn(C);break;case"error":if(C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.error(C),a){let E=a.split(`
|
|
39
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||De()||!Ue.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(De()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await _r(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=Xt(this.config.logDirectory,n);if(e.before)try{if((await Zt(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Vr(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 ri(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((o)=>we(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(we(i)&&"path"in i){if(!n.find((o)=>we(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((o)=>mi(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!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]=ri(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 o=[...i];for(let s of r[n])if(we(s)&&"name"in s){if(!o.find((a)=>we(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(we(s)&&"path"in s){if(!o.find((a)=>we(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>mi(a,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function zn(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ri(e,t);if(Array.isArray(e))return r==="replace"?t:ri(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 o=t[i],s=n[i];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(s))if(r==="replace")n[i]=o;else n[i]=ri(s,o);else if(we(o)&&we(s))n[i]=zn(s,o,r);else n[i]=o}return n}function mi(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(!mi(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(!mi(e[i],t[i]))return!1}return!0}return!1}function we(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ei(e,t,r="replace"){if(!ea(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 zn(t,i,r)}catch{return null}}catch{return null}}function hu(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let l=[...a,f],p=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),C=`${n}_${l.map(p).join("_")}`,E=`${n}_${l.map((y)=>y.toUpperCase()).join("_")}`;if(r)ze.info(`Checking environment variable ${C} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=o(u,l);else{let y=gr.env[C]||gr.env[E];if(y!==void 0){if(r)ze.info(`Using environment variable ${y?C:E} for config ${e}.${l.join(".")}`);if(typeof u==="number")c[f]=Number(y);else if(typeof u==="boolean")c[f]=y.toLowerCase()==="true";else if(Array.isArray(u))try{let x=JSON.parse(y);if(Array.isArray(x))c[f]=x;else c[f]=y.split(",").map((S)=>S.trim())}catch{c[f]=y.split(",").map((x)=>x.trim())}else c[f]=y}}}return c}return o(i)}async function du({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:o=!1,checkEnv:s=!0,arrayStrategy:a="replace"}){let c=s&&typeof i==="object"&&i!==null&&!Array.isArray(i)?hu(e,i,o):i,f=r||gr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)ze.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),p=[`${e}.config`,`.${e}.config`].filter(Boolean),C=t?[t,`.${t}`]:[],E=t?[`${t}.config`,`.${t}.config`]:[],y=Array.from(new Set([f,qe(f,"config"),qe(f,".config"),n?qe(f,n):void 0].filter(Boolean)));for(let x of y){if(o)ze.info(`Searching for configuration in: ${x}`);let S=[qe(f,"config"),qe(f,".config")].concat(n?[qe(f,n)]:[]).includes(x)?[...l,...p,...C,...E]:[...p,...l,...E,...C];for(let M of S)for(let D of u){let O=qe(x,`${M}${D}`),H=await ei(O,c,a);if(H!==null){if(o)ze.success(`Configuration loaded from: ${O}`);return H}}}if(e){let x=qe(un(),".config",e),S=["config",`${e}.config`];if(t)S.push(`${t}.config`);if(o)ze.info(`Checking user config directory: ${x}`);for(let M of S)for(let D of u){let O=qe(x,`${M}${D}`),H=await ei(O,c,a);if(H!==null){if(o)ze.success(`Configuration loaded from user config directory: ${O}`);return H}}}if(e){let x=qe(un(),".config"),S=[`.${e}.config`];if(t)S.push(`.${t}.config`);if(o)ze.info(`Checking user config directory for dotfile configs: ${x}`);for(let M of S)for(let D of u){let O=qe(x,`${M}${D}`),H=await ei(O,c,a);if(H!==null){if(o)ze.success(`Configuration loaded from user config directory dotfile: ${O}`);return H}}}if(e){let x=un(),S=[`.${e}.config`,`.${e}`];if(t)S.push(`.${t}.config`),S.push(`.${t}`);if(o)ze.info(`Checking user home directory for dotfile configs: ${x}`);for(let M of S)for(let D of u){let O=qe(x,`${M}${D}`),H=await ei(O,c,a);if(H!==null){if(o)ze.success(`Configuration loaded from user home directory: ${O}`);return H}}}try{let x=qe(f,"package.json");if(ea(x)){let S=await import(x),M=S[e];if(!M&&t){if(M=S[t],M&&o)ze.success(`Using alias "${t}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(o)ze.success(`Configuration loaded from package.json: ${M===S[e]?e:t}`);return zn(c,M,a)}catch(D){if(o)ze.warn("Failed to merge package.json config:",D)}}}catch(x){if(o)ze.warn("Failed to load package.json:",x)}if(o)ze.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function mu(e,t={}){let r=ai.cwd();while(r.includes("storage"))r=ws(r,"..");let n=ws(r,e||"");if(t?.relative)return Cf(ai.cwd(),n);return n}async function pu(){try{let e=await du({name:"clarity",alias:"logging",defaultConfig:oi,cwd:ai.cwd()});return{...oi,...e||{}}}catch{return oi}}function Le(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function gu(){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 sa{async format(e){let t=await gu(),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 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={...In},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new sa,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(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...si,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...si};return{...si,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:In.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,o=3,s=1000;while(i<o)try{try{try{await Mf(this.config.logDirectory,Os.F_OK|Os.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Df(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:yt.from(e);try{if(!Ur(this.currentLogFile))await Cn(this.currentLogFile,"",{mode:420});if(n=Ps(this.currentLogFile,"a",420),kf(n,a,{flag:"a"}),Rs(n),n!==void 0)yn(n),n=void 0;if((await er(this.currentLogFile)).size===0){if(await Cn(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<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let l=s*2**i;await new Promise((p)=>setTimeout(p,l)),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{yn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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(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(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return gn(16).toString("hex")}generateKey(){return gn(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=gn(16),n=Rf("aes-256-gcm",t,r),i=yt.isBuffer(e)?e:yt.from(e,"utf8"),o=n.update(i),s=n.final(),a=o.length+s.length,c=n.getAuthTag(),f=yt.allocUnsafe(16+a+16);return r.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Ms(),i=[];n.on("data",(o)=>i.push(o)),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(Le())return;if(!this.shouldWriteToFile())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 Kr(this.config.logDirectory),o=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await er(r).catch(()=>null))try{if(await ks(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await zr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Cn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await er(r).catch(()=>null))await ks(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await Kr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await zr(tr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Ts(e),n=Of(t),i=Ms();await Nf(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()})),Ur(this.currentLogFile))try{let e=Ps(this.currentLogFile,"r+");Rs(e),yn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Le()&&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(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.shouldStyleConsole()?ae.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:o,showTimestamp:s=!0}=e,a=(C)=>C.replace(this.ANSI_PATTERN,"");if(!this.fancy){let C=[];if(s)C.push(t);if(o==="warning")C.push("WARN");else if(o==="error")C.push("ERROR");else if(r)C.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)C.push(n.replace(/[[\]]/g,""));return C.push(i),C.join(" ")}let c=ye.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${ae.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,l=a(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=ae.underline(ae.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>ae.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>ae.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>ae.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>ae.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>ae.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(If(t)||t.startsWith("./")||t.startsWith("../"))t=Ff(t);else return null;return Ur(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":ga[e],p=this.options.showTags!==!1&&this.name?ae.gray(this.formatTag(this.name)):"",C;switch(e){case"debug":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:ae.gray(c),level:e}),console.error(C);break;case"info":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.warn(C);break;case"success":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:ae.green(c),level:e}),console.error(C);break;case"warning":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.warn(C);break;case"error":if(C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.error(C),a){let E=a.split(`
|
|
40
40
|
`);for(let y of E)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:ae.gray(` ${y}`),level:e,showTimestamp:!1}))}break}}else if(!Le()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}if(!this.shouldLog(e))return;let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
41
41
|
`;if(a)u+=`${a}
|
|
42
42
|
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,o)=>{},finish:(i)=>{},interrupt:(i,o)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Le()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!Le()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,o="info")=>{if(!Le()&&ye.stdout.isTTY)ye.stdout.write(`
|
|
43
43
|
`);if(this[o==="warning"?"warn":o](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?ae.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":ae.blue("\u25D0"),tag:r,message:`${ae.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
44
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ae.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":ae.green("\u2713"),tag:f,message:`${o}${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(!Ur(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return
|
|
44
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ae.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":ae.green("\u2713"),tag:f,message:`${o}${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(!Ur(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ts(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=yt.isBuffer(e)?e:yt.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),a=Pf("aes-256-gcm",r,i);a.setAuthTag(o);let c=a.update(s),f=a.final(),u=c.length+f.length,l=yt.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.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:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=i.split(`
|
|
45
45
|
`),c=Math.max(...a.map((p)=>p.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=a.map((p)=>this.formatConsoleMessage({timestamp:r,message:ae.cyan(p),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:ae.cyan(f),showTimestamp:!1})),l.forEach((p)=>console.error(p)),console.error(this.formatConsoleMessage({timestamp:r,message:ae.cyan(u),showTimestamp:!1}))}else if(!Le())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
|
|
46
46
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(Le())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ae.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();ye.stdin.removeListener("data",r);try{if(typeof ye.stdin.setRawMode==="function")ye.stdin.setRawMode(!1)}catch{}ye.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof ye.stdin.setRawMode==="function")ye.stdin.setRawMode(!0)}catch{}ye.stdin.resume(),ye.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,a=0;if(r=e.replace(s,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?ae.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${ae.blue("\u25D0")} `;console.error(`${a}${s} ${ae.cyan(n)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
47
47
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ye.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=ae.green("\u2501".repeat(n)),s=ae.gray("\u2501".repeat(i)),a=`[${o}${s}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?ae.green("\u2713"):ae.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${ae.gray(this.formatTag(this.name))}`:"",p=`\r${u}${l} ${a} ${c}${f}`,C=ye.stdout.columns||80,E=" ".repeat(Math.max(0,C-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${E}`,ye.stdout.write(e.lastRenderedLine),t)ye.stdout.write(`
|
|
48
|
-
`)}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 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=tr(this.config.logDirectory,n);if(e.before)try{if((await er(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await 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)}}}async function
|
|
48
|
+
`)}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 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=tr(this.config.logDirectory,n);if(e.before)try{if((await er(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await 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)}}}async function aa(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(s=c instanceof Error?c:Error(String(c)),a===r||!i(s))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function la(e){return e instanceof rt}function yu(e){return e instanceof gi}function Cu(e){if(la(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 bi{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:a=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:i,useBackwardCompatibility:o,customParsers:s,verbose:a,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return wr.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],a=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${a.join("_")}`,f=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,r,n);else{let u=Hr.env[c]||(f?Hr.env[f]:void 0);if(u!==void 0){if(n.verbose){let l=Hr.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof o,c,n.customParsers,n.configName)}catch(l){if(l instanceof yi)throw l;throw kt.envVar(c,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw kt.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Hr.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],a=`${r}_${s.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,r,n);else n.push({key:a,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
49
49
|
|
|
50
50
|
`;for(let n of e)r+=`${n.key}
|
|
51
51
|
`,r+=` Type: ${n.type}
|
|
@@ -57,25 +57,25 @@ ${Gr}/
|
|
|
57
57
|
`;r+=`| Variable | Type | Description | Example |
|
|
58
58
|
`,r+=`|----------|------|-------------|----------|
|
|
59
59
|
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
60
|
-
`;return r}}function hu(e,t){let r=fa("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function sa(e,t,r={}){return aa(e,t,r,new WeakMap)}function aa(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let a=s(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return la(e,t,i,n);if(!at(t)||!at(e))return t;return gu(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 du(e,t);case"smart":return mu(e,t,n);default:return t}return t}function du(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>On(i,n)))r.push(n);return r}function mu(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(at(t[0])&&at(e[0]))return pu(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 pu(e,t,r){let n=[...t];for(let i of e){if(!at(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in i){if(n.find((c)=>at(c)&&(a in c)&&c[a]===i[a])){s=!0;break}}if(!s)n.push(i)}return n}function gu(e,t,r,n){let i=t;if(at(i)&&n.has(i))return n.get(i);let o={...e};if(at(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let a=i[s],c=o[s];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(at(a)&&at(c))o[s]=aa(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))o[s]=la(c,a,r.arrayMergeMode||"smart",n);else o[s]=a}return o}function Kn(e,t,r="replace"){return sa(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function On(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(!On(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(!On(e[i],t[i]))return!1}return!0}return!1}function at(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Si{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1}=r;if(i){let f=sr.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Jr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,C=Object.keys(u).length>0;if(!p&&!C)throw new yr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new yr(e,Error("Configuration must export a valid object"),"unknown");let E={config:Kn(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)sr.setWithFileCheck("file",E,e,o);return E}catch(f){throw f instanceof Error?kt.configLoad(e,f):kt.configLoad(e,Error(String(f)))}};if(s)return wr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let o of n)for(let s of this.extensions)i.push(yn(t,`${o}${s}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return na(async()=>Jr(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Jr(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let a=yn(e,`${o}${s}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=yn(e,s);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Jr(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class zn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],p);else return this.validateWithJSONSchema(e,t,p)}catch(C){return u.push({path:"",message:`Validation failed: ${C}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await wr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Of(t))throw new Cr(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 Cr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(s)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${s}`,expected:a.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let a=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let a of t.required)if(!(a in s)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in s){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],c,f,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:pa},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Hn{fileLoader=new Si;envProcessor=new bi;validator=new zn;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(s,!0,r)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||o)await this.validateConfiguration(a.config,i,o,s.name);if(r?.enabled&&a)this.cacheResult(s.name||"",a,r,s);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)ht.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.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:o,configDir:s,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=o||Lt.cwd(),p=[],C=await this.loadLocalConfiguration(n,i,l,s,a,f,u,c,r);if(C)return p.push(...this.getLocalSearchPaths(n,i,l,s)),this.finalizeResult(C,p,c,n,u);let E=await this.loadHomeConfiguration(n,i,a,f,u,c);if(E)return p.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(E,p,c,n,u);let y=await this.loadPackageJsonConfiguration(n,i,l,a,f,u,c);if(y)return p.push(Ye(l,"package.json")),this.finalizeResult(y,p,c,n,u);if(p.push(...this.getAllSearchPaths(n,i,l,s)),t)throw kt.configNotFound(n,p,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,a,c){let f=a?pr(e,i,s):i,u=this.getLocalDirectories(r,n);for(let l of u){if(s)ht.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),C=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(C){if(s)ht.success(`Configuration loaded from: ${C.source.path}`);return C}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?pr(e,r,i):r,a=[Ye(Yt(),".config",e),Ye(Yt(),".config"),Yt()];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,s,{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,o,s){let a=s?pr(e,n,o):n;try{let c=Ye(r,"package.json");if(!Rn(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)ht.success(`Configuration loaded from package.json: ${l}`);return{config:Kn(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)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:pr(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw kt.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return sr.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);sr.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,Ye(e,"config"),Ye(e,".config"),t?Ye(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(Ye(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ye(Yt(),".config",e),Ye(Yt(),".config"),Yt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Ws(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 yu(e){return St.loadConfig({...e,__strictErrorHandling:!0})}async function ca(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 St.loadConfig(e);else n=await St.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)ht.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let s=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await St.applyEnvironmentVariables(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function Cu(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await St.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"&&Ws(r)))return(await St.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await St.loadConfig({...e,cwd:e.cwd||Lt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Ws(t)))return(await St.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function wu(e,t,r="replace"){let n=new Si;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function pr(e,t,r=!1){let n=new bi,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let l=[...a,f],p=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((y)=>y.toUpperCase()).join("")}`,`${i}_${l.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],C,E;for(let y of p)if(C=Lt.env[y],C!==void 0){E=y;break}if(C!==void 0&&E)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(C.toLowerCase());else if(typeof u==="number"){let y=Number(C);if(!Number.isNaN(y))c[f]=y}else if(Array.isArray(u))try{c[f]=JSON.parse(C)}catch{c[f]=C.split(",").map((y)=>y.trim())}else c[f]=C;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,l)}return c}return o(t)}function Eu(e){let t=Ye(Lt.cwd(),e.configDir),r=Ye(Lt.cwd(),e.generatedDir),n=Ye(r,"config-types.ts");if(!Rn(ps(n)))af(ps(n),{recursive:!0,mode:511});let i=Rn(t)?lf(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${qu}
|
|
60
|
+
`;return r}}function wu(e,t){let r=da("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function ca(e,t,r={}){return fa(e,t,r,new WeakMap)}function fa(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let a=s(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return ua(e,t,i,n);if(!at(t)||!at(e))return t;return Su(e,t,r,n)}function ua(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Eu(e,t);case"smart":return vu(e,t,n);default:return t}return t}function Eu(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Mn(i,n)))r.push(n);return r}function vu(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(at(t[0])&&at(e[0]))return bu(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 bu(e,t,r){let n=[...t];for(let i of e){if(!at(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in i){if(n.find((c)=>at(c)&&(a in c)&&c[a]===i[a])){s=!0;break}}if(!s)n.push(i)}return n}function Su(e,t,r,n){let i=t;if(at(i)&&n.has(i))return n.get(i);let o={...e};if(at(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let a=i[s],c=o[s];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(at(a)&&at(c))o[s]=fa(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))o[s]=ua(c,a,r.arrayMergeMode||"smart",n);else o[s]=a}return o}function Hn(e,t,r="replace"){return ca(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Mn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Mn(e[r],t[r]))return!1;return!0}if(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(!Mn(e[i],t[i]))return!1}return!0}return!1}function at(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Si{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1}=r;if(i){let f=sr.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Jr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,C=Object.keys(u).length>0;if(!p&&!C)throw new yr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new yr(e,Error("Configuration must export a valid object"),"unknown");let E={config:Hn(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)sr.setWithFileCheck("file",E,e,o);return E}catch(f){throw f instanceof Error?kt.configLoad(e,f):kt.configLoad(e,Error(String(f)))}};if(s)return wr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let o of n)for(let s of this.extensions)i.push(wn(t,`${o}${s}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return aa(async()=>Jr(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Jr(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let a=wn(e,`${o}${s}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=wn(e,s);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Jr(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class Jn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],p);else return this.validateWithJSONSchema(e,t,p)}catch(C){return u.push({path:"",message:`Validation failed: ${C}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await wr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Lf(t))throw new Cr(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 Cr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(s)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${s}`,expected:a.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let a=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let a of t.required)if(!(a in s)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in s){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],c,f,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Ca},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class qn{fileLoader=new Si;envProcessor=new bi;validator=new Jn;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(s,!0,r)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||o)await this.validateConfiguration(a.config,i,o,s.name);if(r?.enabled&&a)this.cacheResult(s.name||"",a,r,s);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)ht.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.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:o,configDir:s,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=o||Lt.cwd(),p=[],C=await this.loadLocalConfiguration(n,i,l,s,a,f,u,c,r);if(C)return p.push(...this.getLocalSearchPaths(n,i,l,s)),this.finalizeResult(C,p,c,n,u);let E=await this.loadHomeConfiguration(n,i,a,f,u,c);if(E)return p.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(E,p,c,n,u);let y=await this.loadPackageJsonConfiguration(n,i,l,a,f,u,c);if(y)return p.push(Ye(l,"package.json")),this.finalizeResult(y,p,c,n,u);if(p.push(...this.getAllSearchPaths(n,i,l,s)),t)throw kt.configNotFound(n,p,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,a,c){let f=a?pr(e,i,s):i,u=this.getLocalDirectories(r,n);for(let l of u){if(s)ht.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),C=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(C){if(s)ht.success(`Configuration loaded from: ${C.source.path}`);return C}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?pr(e,r,i):r,a=[Ye(Yt(),".config",e),Ye(Yt(),".config"),Yt()];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,s,{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,o,s){let a=s?pr(e,n,o):n;try{let c=Ye(r,"package.json");if(!On(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)ht.success(`Configuration loaded from package.json: ${l}`);return{config:Hn(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)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:pr(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw kt.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return sr.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);sr.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,Ye(e,"config"),Ye(e,".config"),t?Ye(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(Ye(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ye(Yt(),".config",e),Ye(Yt(),".config"),Yt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function js(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 $u(e){return St.loadConfig({...e,__strictErrorHandling:!0})}async function ha(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 St.loadConfig(e);else n=await St.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)ht.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let s=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await St.applyEnvironmentVariables(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function Au(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await St.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"&&js(r)))return(await St.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await St.loadConfig({...e,cwd:e.cwd||Lt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&js(t)))return(await St.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function xu(e,t,r="replace"){let n=new Si;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function pr(e,t,r=!1){let n=new bi,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let l=[...a,f],p=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((y)=>y.toUpperCase()).join("")}`,`${i}_${l.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],C,E;for(let y of p)if(C=Lt.env[y],C!==void 0){E=y;break}if(C!==void 0&&E)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(C.toLowerCase());else if(typeof u==="number"){let y=Number(C);if(!Number.isNaN(y))c[f]=y}else if(Array.isArray(u))try{c[f]=JSON.parse(C)}catch{c[f]=C.split(",").map((y)=>y.trim())}else c[f]=C;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,l)}return c}return o(t)}function Tu(e){let t=Ye(Lt.cwd(),e.configDir),r=Ye(Lt.cwd(),e.generatedDir),n=Ye(r,"config-types.ts");if(!On(Cs(n)))mf(Cs(n),{recursive:!0,mode:511});let i=On(t)?pf(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${rh}
|
|
61
61
|
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
62
|
-
`;
|
|
63
|
-
${i.map((c)=>{let f=
|
|
62
|
+
`;gf(n,o,{mode:438})}function Ru(e){let t=null,r=null,n=()=>{if(!r)r=ha(e).then((o)=>(t=o,o),(o)=>{let s="defaultConfig"in e?e.defaultConfig:{};if(t=s,"verbose"in e&&e.verbose)ht.warn("Config loading failed, using defaults:",[o instanceof Error?o:Error(String(o))]);return s});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(o,s){if(t)return t[s];let a=i[s];return n(),a},has(o,s){return s in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(o,s){return Object.getOwnPropertyDescriptor(t||i,s)},set(o,s,a){if(!t)t={...i};return t[s]=a,!0}})}function Pu(e){let t=Ds(Gf.cwd(),e?.configDir||"./config");function r(){if(!Wf(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),o=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Bf(t).filter((c)=>i.has(En(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),a=new Map;for(let{base:c,file:f}of s){let u=En(f).toLowerCase(),l=a.get(c);if(!l){a.set(c,f);continue}let p=En(l).toLowerCase();if(o.indexOf(u)<o.indexOf(p))a.set(c,f)}return Array.from(a.entries()).map(([c,f])=>({base:c,file:f})).sort((c,f)=>c.base.localeCompare(f.base))}function n(){let i=r(),o=i.map((c)=>c.base),s=o.length?o.map((c)=>`'${c}'`).join(" | "):"string",a=i.length?`{
|
|
63
|
+
${i.map((c)=>{let f=Ds(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
|
|
64
64
|
`)}
|
|
65
65
|
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
66
66
|
export type ConfigByName = ${a}
|
|
67
67
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
68
68
|
export type ConfigOf = Config
|
|
69
|
-
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function Zu(e,t={}){let r=fi.cwd();while(r.includes("storage"))r=ks(r,"..");let n=ks(r,e||"");if(t?.relative)return Ff(fi.cwd(),n);return n}function Be(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Qu(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bt<"u"){let e=bt.type;if(e==="renderer"||e==="worker")return!1;return!!(bt.versions&&(bt.versions.node||bt.versions.bun))}return!1}class wa{async format(e){let t=await Qu(),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 $i{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Ci},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new wa,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??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(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Tn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Tn};return{...Tn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ci.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!Be()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,o=3,s=1000;while(i<o)try{try{try{await Gf(this.config.logDirectory,Fs.F_OK|Fs.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await jf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ct.from(e);try{if(!qr(this.currentLogFile))await vn(this.currentLogFile,"",{mode:420});if(n=Is(this.currentLogFile,"a",420),Bf(n,a,{flag:"a"}),Ds(n),n!==void 0)En(n),n=void 0;if((await ir(this.currentLogFile)).size===0){if(await vn(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<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let l=s*2**i;await new Promise((p)=>setTimeout(p,l)),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{En(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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(Be())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return wn(16).toString("hex")}generateKey(){return wn(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=wn(16),n=Nf("aes-256-gcm",t,r),i=Ct.isBuffer(e)?e:Ct.from(e,"utf8"),o=n.update(i),s=n.final(),a=o.length+s.length,c=n.getAuthTag(),f=Ct.allocUnsafe(16+a+16);return r.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Ls(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Ct.from(Ct.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Be())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 Yr(this.config.logDirectory),o=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await ir(r).catch(()=>null))try{if(await Ns(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Zr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await vn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await ir(r).catch(()=>null))await Ns(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await Yr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await Zr(nr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Ms(e),n=Wf(t),i=Ls();await Uf(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=Is(this.currentLogFile,"r+");Ds(e),En(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(!Be()&&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 Zr(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()?fe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Be())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:o,showTimestamp:s=!0}=e,a=(C)=>C.replace(this.ANSI_PATTERN,"");if(!this.fancy){let C=[];if(s)C.push(t);if(o==="warning")C.push("WARN");else if(o==="error")C.push("ERROR");else if(r)C.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)C.push(n.replace(/[[\]]/g,""));return C.push(i),C.join(" ")}let c=Ce.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${fe.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,l=a(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=fe.underline(fe.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>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(Be())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(_f(t)||t.startsWith("./")||t.startsWith("../"))t=Vf(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),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":nh[e],p=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"",C;switch(e){case"debug":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:fe.gray(c),level:e}),console.error(C);break;case"info":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.warn(C);break;case"success":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:fe.green(c),level:e}),console.error(C);break;case"warning":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.warn(C);break;case"error":if(C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.error(C),a){let E=a.split(`
|
|
69
|
+
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function nh(e,t={}){let r=fi.cwd();while(r.includes("storage"))r=Is(r,"..");let n=Is(r,e||"");if(t?.relative)return _f(fi.cwd(),n);return n}function Be(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function sh(){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 ba{async format(e){let t=await sh(),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 $i{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Ci},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ba,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??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(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Pn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Pn};return{...Pn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ci.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!Be()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,o=3,s=1000;while(i<o)try{try{try{await Hf(this.config.logDirectory,Ws.F_OK|Ws.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Jf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ct.from(e);try{if(!qr(this.currentLogFile))await Sn(this.currentLogFile,"",{mode:420});if(n=Ls(this.currentLogFile,"a",420),zf(n,a,{flag:"a"}),Ns(n),n!==void 0)bn(n),n=void 0;if((await ir(this.currentLogFile)).size===0){if(await Sn(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<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let l=s*2**i;await new Promise((p)=>setTimeout(p,l)),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{bn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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(Be())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return vn(16).toString("hex")}generateKey(){return vn(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=vn(16),n=Vf("aes-256-gcm",t,r),i=Ct.isBuffer(e)?e:Ct.from(e,"utf8"),o=n.update(i),s=n.final(),a=o.length+s.length,c=n.getAuthTag(),f=Ct.allocUnsafe(16+a+16);return r.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Gs(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Ct.from(Ct.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Be())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 Yr(this.config.logDirectory),o=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await ir(r).catch(()=>null))try{if(await Bs(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Zr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Sn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await ir(r).catch(()=>null))await Bs(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await Yr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await Zr(nr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Fs(e),n=Kf(t),i=Gs();await Zf(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=Ls(this.currentLogFile,"r+");Ns(e),bn(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(!Be()&&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 Zr(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()?fe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Be())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:o,showTimestamp:s=!0}=e,a=(C)=>C.replace(this.ANSI_PATTERN,"");if(!this.fancy){let C=[];if(s)C.push(t);if(o==="warning")C.push("WARN");else if(o==="error")C.push("ERROR");else if(r)C.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)C.push(n.replace(/[[\]]/g,""));return C.push(i),C.join(" ")}let c=Ce.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${fe.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,l=a(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=fe.underline(fe.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>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(Be())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(qf(t)||t.startsWith("./")||t.startsWith("../"))t=Yf(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),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":uh[e],p=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"",C;switch(e){case"debug":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:fe.gray(c),level:e}),console.error(C);break;case"info":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.warn(C);break;case"success":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:fe.green(c),level:e}),console.error(C);break;case"warning":C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.warn(C);break;case"error":if(C=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:c,level:e}),console.error(C),a){let E=a.split(`
|
|
70
70
|
`);for(let y of E)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:fe.gray(` ${y}`),level:e,showTimestamp:!1}))}break}}else if(!Be()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
71
71
|
`;if(a)u+=`${a}
|
|
72
72
|
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,o)=>{},finish:(i)=>{},interrupt:(i,o)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Be()&&Ce.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!Be()&&Ce.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,o="info")=>{if(!Be()&&Ce.stdout.isTTY)Ce.stdout.write(`
|
|
73
73
|
`);if(this[o==="warning"?"warn":o](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Be()&&Ce.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":fe.blue("\u25D0"),tag:r,message:`${fe.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
74
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":fe.green("\u2713"),tag:f,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Be())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new $i(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Be())throw Error("createReadStream is not supported in browser environments");if(!qr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return
|
|
74
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":fe.green("\u2713"),tag:f,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Be())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new $i(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Be())throw Error("createReadStream is not supported in browser environments");if(!qr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Fs(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Ct.isBuffer(e)?e:Ct.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),a=Uf("aes-256-gcm",r,i);a.setAuthTag(o);let c=a.update(s),f=a.final(),u=c.length+f.length,l=Ct.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.toString("utf8")}catch(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 Be()}isServerMode(){return!Be()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=i.split(`
|
|
75
75
|
`),c=Math.max(...a.map((p)=>p.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=a.map((p)=>this.formatConsoleMessage({timestamp:r,message:fe.cyan(p),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:fe.cyan(f),showTimestamp:!1})),l.forEach((p)=>console.error(p)),console.error(this.formatConsoleMessage({timestamp:r,message:fe.cyan(u),showTimestamp:!1}))}else if(!Be())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
|
|
76
76
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(Be())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${fe.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Ce.stdin.removeListener("data",r);try{if(typeof Ce.stdin.setRawMode==="function")Ce.stdin.setRawMode(!1)}catch{}Ce.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Ce.stdin.setRawMode==="function")Ce.stdin.setRawMode(!0)}catch{}Ce.stdin.resume(),Ce.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,a=0;if(r=e.replace(s,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${fe.blue("\u25D0")} `;console.error(`${a}${s} ${fe.cyan(n)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
77
77
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!Ce.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=fe.green("\u2501".repeat(n)),s=fe.gray("\u2501".repeat(i)),a=`[${o}${s}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?fe.green("\u2713"):fe.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${fe.gray(this.formatTag(this.name))}`:"",p=`\r${u}${l} ${a} ${c}${f}`,C=Ce.stdout.columns||80,E=" ".repeat(Math.max(0,C-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${E}`,Ce.stdout.write(e.lastRenderedLine),t)Ce.stdout.write(`
|
|
78
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Be()||!Ce.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(Be()){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=nr(this.config.logDirectory,n);if(e.before)try{if((await ir(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await 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)}}}async function
|
|
78
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Be()||!Ce.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(Be()){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=nr(this.config.logDirectory,n);if(e.before)try{if((await ir(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await 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)}}}async function hh(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(s=c instanceof Error?c:Error(String(c)),a===r||!i(s))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class Zn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:a=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:i,useBackwardCompatibility:o,customParsers:s,verbose:a,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return _n.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],a=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${a.join("_")}`,f=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,r,n);else{let u=Xr.env[c]||(f?Xr.env[f]:void 0);if(u!==void 0){if(n.verbose){let l=Xr.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof o,c,n.customParsers,n.configName)}catch(l){if(l instanceof Yn)throw l;throw ar.envVar(c,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw ar.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Xr.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],a=`${r}_${s.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,r,n);else n.push({key:a,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
79
79
|
|
|
80
80
|
`;for(let n of e)r+=`${n.key}
|
|
81
81
|
`,r+=` Type: ${n.type}
|
|
@@ -87,140 +87,140 @@ export type ConfigOf = Config
|
|
|
87
87
|
`;r+=`| Variable | Type | Description | Example |
|
|
88
88
|
`,r+=`|----------|------|-------------|----------|
|
|
89
89
|
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
90
|
-
`;return r}}function sh(e,t,r={}){return Ra(e,t,r,new WeakMap)}function Ra(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let a=s(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Pa(e,t,i,n);if(!lt(t)||!lt(e))return t;return fh(e,t,r,n)}function Pa(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 ah(e,t);case"smart":return lh(e,t,n);default:return t}return t}function ah(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Bn(i,n)))r.push(n);return r}function lh(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(lt(t[0])&<(e[0]))return ch(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 ch(e,t,r){let n=[...t];for(let i of e){if(!lt(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in i){if(n.find((c)=>lt(c)&&(a in c)&&c[a]===i[a])){s=!0;break}}if(!s)n.push(i)}return n}function fh(e,t,r,n){let i=t;if(lt(i)&&n.has(i))return n.get(i);let o={...e};if(lt(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let a=i[s],c=o[s];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(lt(a)&<(c))o[s]=Ra(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))o[s]=Pa(c,a,r.arrayMergeMode||"smart",n);else o[s]=a}return o}function Oa(e,t,r="replace"){return sh(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Bn(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(!Bn(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(!Bn(e[i],t[i]))return!1}return!0}return!1}function lt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ka{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1}=r;if(i){let f=ui.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Qr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,C=Object.keys(u).length>0;if(!p&&!C)throw new wi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new wi(e,Error("Configuration must export a valid object"),"unknown");let E={config:Oa(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)ui.setWithFileCheck("file",E,e,o);return E}catch(f){throw f instanceof Error?ar.configLoad(e,f):ar.configLoad(e,Error(String(f)))}};if(s)return Gn.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let o of n)for(let s of this.extensions)i.push(bn(t,`${o}${s}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let o of n){if(!o)continue;if(r.push(o,`.${o}.config`,`${o}.config`,`.${o}`),e)r.push(`${e}.${o}.config`,`.${e}.${o}.config`)}let i=new Set;return r.filter((o)=>{if(!o||i.has(o))return!1;return i.add(o),!0})}checkFileAccess(e){return oh(async()=>Qr(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Qr(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let a=bn(e,`${o}${s}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=bn(e,s);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Qr(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class Ma{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],p);else return this.validateWithJSONSchema(e,t,p)}catch(C){return u.push({path:"",message:`Validation failed: ${C}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await Gn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Kf(t))throw new Ei(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 Ei(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(s)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${s}`,expected:a.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let a=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let a of t.required)if(!(a in s)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in s){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],c,f,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:uh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function hh(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 Da{fileLoader=new ka;envProcessor=new qn;validator=new Ma;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(s,!0,r)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||o)await this.validateConfiguration(a.config,i,o,s.name);if(r?.enabled&&a)this.cacheResult(s.name||"",a,r,s);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)wt.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw wt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:o,configDir:s,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=o||vi.cwd(),p=[],C=await this.loadLocalConfiguration(n,i,l,s,a,f,u,c,r);if(C)return p.push(...this.getLocalSearchPaths(n,i,l,s)),this.finalizeResult(C,p,c,n,u);let E=await this.loadHomeConfiguration(n,i,a,f,u,c);if(E)return p.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(E,p,c,n,u);let y=await this.loadPackageJsonConfiguration(n,i,l,a,f,u,c);if(y)return p.push(st(l,"package.json")),this.finalizeResult(y,p,c,n,u);if(p.push(...this.getAllSearchPaths(n,i,l,s)),t)throw ar.configNotFound(n,p,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${hh(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,a,c){let f=a?ti(e,i,s):i,u=this.getLocalDirectories(r,n);for(let l of u){if(s)wt.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),C=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(C){if(s)wt.success(`Configuration loaded from: ${C.source.path}`);return C}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?ti(e,r,i):r,a=[st(qt(),".config",e),st(qt(),".config"),qt()];for(let c of a){if(i)wt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:n,verbose:i});if(u){if(i)wt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let a=s?ti(e,n,o):n;try{let c=st(r,"package.json");if(!of(c))return null;let f={};try{f=JSON.parse(sf(c,"utf8"))}catch(p){if(o)wt.warn("Failed to parse package.json:",[p instanceof Error?p:Error(String(p))]);return null}let u=f[e],l=e;if(!u&&t){let p=Array.isArray(t)?t:[t];for(let C of p){if(!C)continue;if(f[C]){u=f[C],l=C;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)wt.success(`Configuration loaded from package.json: ${l}`);return{config:Oa(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)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:ti(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw ar.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ui.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);ui.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,st(e,"config"),st(e,".config"),t?st(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(st(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[st(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 ti(e,t,r=!1){let n=new qn,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let l=[...a,f],p=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((y)=>y.toUpperCase()).join("")}`,`${i}_${l.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],C,E;for(let y of p)if(C=vi.env[y],C!==void 0){E=y;break}if(C!==void 0&&E)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(C.toLowerCase());else if(typeof u==="number"){let y=Number(C);if(!Number.isNaN(y))c[f]=y}else if(Array.isArray(u))try{c[f]=JSON.parse(C)}catch{c[f]=C.split(",").map((y)=>y.trim())}else c[f]=C;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,l)}return c}return o(t)}var ui,Gn,zf,Hf=(e)=>e,qf=(e,t)=>{for(var r in t)zf(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Jf.bind(t,r)})},Yf=(e,t)=>()=>(e&&(t=e(e=0)),t),ta,fa,sr,wr,ua,Su,$u,Bs,ii,kn,Ke,Ae,Au,Gs,xu,js,Tu,Ru,Sn,Pu,_s,Vs,$n,Ou,ku,Mu,Du,ni,ha,Iu,ze,Fu,Nu,Us,oi,Mn,We,ae,Lu,Ks,Wu,zs,Bu,Gu,An,ju,Hs,Js,_u,xn,Vu,Uu,Ku,zu,Hu,si,da,Ju,qu="0.15.6",rt,gi,yr,Dn,In,yi,Fn,Nn,Cr,Ln,Wn,kt,ma,pa,ht,St,ga,ya,Yu,Xu,Ca,Ci,Vg,Ea,fe,Ug,eh,Kg,th,zg,Hg,qs,Jg,rh,ih,qg,Ys,Yg,Zg,Xg,Qg,ey,Tn,nh,ty,dt,va,wi,ba,Sa,Jn,$a,Aa,Ei,xa,Ta,ar,uh,wt,ry,iy,ny,dh,Ia;var Fa=ge(()=>{ui=new Qs,Gn=new ea,zf=Object.defineProperty;ta={};qf(ta,{withErrorRecovery:()=>na,tryLoadConfig:()=>wu,loadConfigWithResult:()=>yu,loadConfig:()=>ca,isRetryableError:()=>uu,isConfigNotFoundError:()=>fu,isBunfigError:()=>oa,globalPerformanceMonitor:()=>wr,globalCache:()=>sr,getEnvOrDefault:()=>hu,generateConfigTypes:()=>Eu,defaultGeneratedDir:()=>ya,defaultConfigDir:()=>ga,deepMergeWithArrayStrategy:()=>Kn,deepMerge:()=>sa,createLibraryConfig:()=>vu,config:()=>Cu,bunfigPlugin:()=>bu,applyEnvVarsToConfig:()=>pr,TypeGenerationError:()=>Nn,SchemaValidationError:()=>Cr,PluginError:()=>Wn,PerformanceMonitor:()=>_n,FileSystemError:()=>Fn,ErrorFactory:()=>kt,EnvVarError:()=>yi,EnvProcessor:()=>bi,ConfigValidator:()=>zn,ConfigValidationError:()=>Dn,ConfigNotFoundError:()=>gi,ConfigMergeError:()=>In,ConfigLoader:()=>Hn,ConfigLoadError:()=>yr,ConfigFileLoader:()=>Si,ConfigCache:()=>jn,CacheUtils:()=>ua,BunfigError:()=>rt,BrowserConfigError:()=>Ln,ArrayMergeStrategies:()=>ma});Yu=Yf(async()=>{fa=import.meta.require,sr=new jn,wr=new _n,ua={createKey:Zf,isEquivalent:Xf,estimateMemoryUsage:Qf},Su=ci(Pn.cwd(),"config"),$u=ci(Pn.cwd(),"src/generated"),Bs=li.env.CLARITY_LOG_DIR||hf(ru(),"logs"),ii={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Bs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},kn=await iu(),Ke={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"},Ae=Ke,Au=Ke.red,Gs=Ke.green,xu=Ke.yellow,js=Ke.blue,Tu=Ke.magenta,Ru=Ke.cyan,Sn=Ke.white,Pu=Ke.gray,_s=Ke.bgRed,Vs=Ke.bgYellow,$n=Ke.bold,Ou=Ke.dim,ku=Ke.italic,Mu=Ke.underline,Du=Ke.reset,ni={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ha={debug:"\uD83D\uDD0D",info:js("\u2139"),success:Gs("\u2713"),warning:Vs(Sn($n(" WARN "))),error:_s(Sn($n(" ERROR ")))},Iu=new di("stacks"),ze=new di("bunfig",{showTags:!0}),Fu=qe(gr.cwd(),"config"),Nu=qe(gr.cwd(),"src/generated"),Us=ai.env.CLARITY_LOG_DIR||ff(au(),"logs"),oi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Us,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Mn=await lu(),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"},ae=We,Lu=We.red,Ks=We.green,Wu=We.yellow,zs=We.blue,Bu=We.magenta,Gu=We.cyan,An=We.white,ju=We.gray,Hs=We.bgRed,Js=We.bgYellow,_u=We.bgGray,xn=We.bold,Vu=We.dim,Uu=We.italic,Ku=We.underline,zu=We.strikethrough,Hu=We.reset,si={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},da={debug:"\uD83D\uDD0D",info:zs("\u2139"),success:Ks("\u2713"),warning:Js(An(xn(" WARN "))),error:Hs(An(xn(" ERROR ")))},Ju=new pi("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}`}},gi=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})}},yr=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}},Dn=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})}},In=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}},yi=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})}},Fn=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}},Nn=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}},Cr=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})}},Ln=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})}},Wn=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}},kt={configNotFound(e,t,r){return new gi(e,t,r)},configLoad(e,t,r){return new yr(e,t,r)},configValidation(e,t,r){return new Dn(e,t,r)},configMerge(e,t,r,n){return new In(e,t,r,n)},envVar(e,t,r,n){return new yi(e,t,r,n)},fileSystem(e,t,r){return new Fn(e,t,r)},typeGeneration(e,t,r){return new Nn(e,t,r)},schemaValidation(e,t,r){return new Cr(e,t,r)},browserConfig(e,t,r,n){return new Ln(e,t,r,n)},plugin(e,t,r){return new Wn(e,t,r)}},ma={replace:"replace",concat:"concat",smart:"smart"},pa=/^https?:\/\//,ht=new pi("bunfig",{showTags:!0}),St=new Hn,ga=Ye(Lt.cwd(),"config"),ya=Ye(Lt.cwd(),"src/generated")});Xu=fi.env.CLARITY_LOG_DIR||If(Zu(),"logs"),Ca={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Xu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ci={...Ca},Vg=(async()=>{try{let{loadConfig:e}=await Yu().then(()=>ta),t=await e({name:"clarity",alias:"logging",defaultConfig:Ca,cwd:fi.cwd()});if(t)Object.assign(Ci,t)}catch{}return Ci})();Ea={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=Ea,{red:Ug,green:eh,yellow:Kg,blue:th,magenta:zg,cyan:Hg,white:qs,gray:Jg,bgRed:rh,bgYellow:ih,bgGray:qg,bold:Ys,dim:Yg,italic:Zg,underline:Xg,strikethrough:Qg,reset:ey}=Ea,Tn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nh={debug:"\uD83D\uDD0D",info:th("\u2139"),success:eh("\u2713"),warning:ih(qs(Ys(" WARN "))),error:rh(qs(Ys(" ERROR ")))};ty=new $i("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}`}};va=class va 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((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};wi=class wi 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}};ba=class ba 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})}};Sa=class Sa 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}};Jn=class Jn 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})}};$a=class $a 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}};Aa=class Aa 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}};Ei=class Ei 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})}};xa=class xa 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})}};Ta=class Ta 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}};ar={configNotFound(e,t,r){return new va(e,t,r)},configLoad(e,t,r){return new wi(e,t,r)},configValidation(e,t,r){return new ba(e,t,r)},configMerge(e,t,r,n){return new Sa(e,t,r,n)},envVar(e,t,r,n){return new Jn(e,t,r,n)},fileSystem(e,t,r){return new $a(e,t,r)},typeGeneration(e,t,r){return new Aa(e,t,r)},schemaValidation(e,t,r){return new Ei(e,t,r)},browserConfig(e,t,r,n){return new xa(e,t,r,n)},plugin(e,t,r){return new Ta(e,t,r)}};uh=/^https?:\/\//;wt=new $i("bunfig",{showTags:!0});ry=new Da;iy=st(vi.cwd(),"config"),ny=st(vi.cwd(),"src/generated"),dh={cwd:nf.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},Ia=dh});function Na(e,t,r){let n={file:t,message:"Unknown error",code:Er.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=Er.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=Er.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=Er.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=Er.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function La(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(`
|
|
90
|
+
`;return r}}function dh(e,t,r={}){return ka(e,t,r,new WeakMap)}function ka(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let a=s(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Ma(e,t,i,n);if(!lt(t)||!lt(e))return t;return yh(e,t,r,n)}function Ma(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 mh(e,t);case"smart":return ph(e,t,n);default:return t}return t}function mh(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>jn(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 gh(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 gh(e,t,r){let n=[...t];for(let i of e){if(!lt(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in i){if(n.find((c)=>lt(c)&&(a in c)&&c[a]===i[a])){s=!0;break}}if(!s)n.push(i)}return n}function yh(e,t,r,n){let i=t;if(lt(i)&&n.has(i))return n.get(i);let o={...e};if(lt(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let a=i[s],c=o[s];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(lt(a)&<(c))o[s]=ka(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))o[s]=Ma(c,a,r.arrayMergeMode||"smart",n);else o[s]=a}return o}function Da(e,t,r="replace"){return dh(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function jn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!jn(e[r],t[r]))return!1;return!0}if(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(!jn(e[i],t[i]))return!1}return!0}return!1}function lt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ia{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1}=r;if(i){let f=ui.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Qr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,C=Object.keys(u).length>0;if(!p&&!C)throw new wi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new wi(e,Error("Configuration must export a valid object"),"unknown");let E={config:Da(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)ui.setWithFileCheck("file",E,e,o);return E}catch(f){throw f instanceof Error?ar.configLoad(e,f):ar.configLoad(e,Error(String(f)))}};if(s)return _n.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let o of n)for(let s of this.extensions)i.push($n(t,`${o}${s}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let o of n){if(!o)continue;if(r.push(o,`.${o}.config`,`${o}.config`,`.${o}`),e)r.push(`${e}.${o}.config`,`.${e}.${o}.config`)}let i=new Set;return r.filter((o)=>{if(!o||i.has(o))return!1;return i.add(o),!0})}checkFileAccess(e){return hh(async()=>Qr(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Qr(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let a=$n(e,`${o}${s}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=$n(e,s);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Qr(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class Fa{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],p);else return this.validateWithJSONSchema(e,t,p)}catch(C){return u.push({path:"",message:`Validation failed: ${C}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await _n.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Xf(t))throw new Ei(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 Ei(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(s)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${s}`,expected:a.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let a=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let a of t.required)if(!(a in s)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in s){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],c,f,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Ch},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function wh(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Na{fileLoader=new Ia;envProcessor=new Zn;validator=new Fa;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(s,!0,r)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||o)await this.validateConfiguration(a.config,i,o,s.name);if(r?.enabled&&a)this.cacheResult(s.name||"",a,r,s);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)wt.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw wt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:o,configDir:s,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=o||vi.cwd(),p=[],C=await this.loadLocalConfiguration(n,i,l,s,a,f,u,c,r);if(C)return p.push(...this.getLocalSearchPaths(n,i,l,s)),this.finalizeResult(C,p,c,n,u);let E=await this.loadHomeConfiguration(n,i,a,f,u,c);if(E)return p.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(E,p,c,n,u);let y=await this.loadPackageJsonConfiguration(n,i,l,a,f,u,c);if(y)return p.push(st(l,"package.json")),this.finalizeResult(y,p,c,n,u);if(p.push(...this.getAllSearchPaths(n,i,l,s)),t)throw ar.configNotFound(n,p,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${wh(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,a,c){let f=a?ti(e,i,s):i,u=this.getLocalDirectories(r,n);for(let l of u){if(s)wt.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),C=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(C){if(s)wt.success(`Configuration loaded from: ${C.source.path}`);return C}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?ti(e,r,i):r,a=[st(qt(),".config",e),st(qt(),".config"),qt()];for(let c of a){if(i)wt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:n,verbose:i});if(u){if(i)wt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let a=s?ti(e,n,o):n;try{let c=st(r,"package.json");if(!hf(c))return null;let f={};try{f=JSON.parse(df(c,"utf8"))}catch(p){if(o)wt.warn("Failed to parse package.json:",[p instanceof Error?p:Error(String(p))]);return null}let u=f[e],l=e;if(!u&&t){let p=Array.isArray(t)?t:[t];for(let C of p){if(!C)continue;if(f[C]){u=f[C],l=C;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)wt.success(`Configuration loaded from package.json: ${l}`);return{config:Da(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)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:ti(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw ar.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ui.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);ui.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,st(e,"config"),st(e,".config"),t?st(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(st(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[st(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 ti(e,t,r=!1){let n=new Zn,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let l=[...a,f],p=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((y)=>y.toUpperCase()).join("")}`,`${i}_${l.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],C,E;for(let y of p)if(C=vi.env[y],C!==void 0){E=y;break}if(C!==void 0&&E)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(C.toLowerCase());else if(typeof u==="number"){let y=Number(C);if(!Number.isNaN(y))c[f]=y}else if(Array.isArray(u))try{c[f]=JSON.parse(C)}catch{c[f]=C.split(",").map((y)=>y.trim())}else c[f]=C;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,l)}return c}return o(t)}var ui,_n,Qf,eu=(e)=>e,ru=(e,t)=>{for(var r in t)Qf(e,r,{get:t[r],enumerable:!0,configurable:!0,set:tu.bind(t,r)})},iu=(e,t)=>()=>(e&&(t=e(e=0)),t),na,da,sr,wr,ma,Ou,ku,_s,ii,Dn,Ke,Ae,Mu,Vs,Du,Us,Iu,Fu,An,Nu,Ks,zs,xn,Lu,Wu,Bu,Gu,ni,pa,ju,ze,_u,Vu,Hs,oi,In,We,ae,Uu,Js,Ku,qs,zu,Hu,Tn,Ju,Ys,Zs,qu,Rn,Yu,Zu,Xu,Qu,eh,si,ga,th,rh="0.15.6",rt,gi,yr,Fn,Nn,yi,Ln,Wn,Cr,Bn,Gn,kt,ya,Ca,ht,St,wa,Ea,ih,oh,va,Ci,ty,Sa,fe,ry,ah,iy,lh,ny,oy,Xs,sy,ch,fh,ay,Qs,ly,cy,fy,uy,hy,Pn,uh,dy,dt,$a,wi,Aa,xa,Yn,Ta,Ra,Ei,Pa,Oa,ar,Ch,wt,my,py,gy,Eh,La;var Wa=ge(()=>{ui=new ra,_n=new ia,Qf=Object.defineProperty;na={};ru(na,{withErrorRecovery:()=>aa,tryLoadConfig:()=>xu,loadConfigWithResult:()=>$u,loadConfig:()=>ha,isRetryableError:()=>Cu,isConfigNotFoundError:()=>yu,isBunfigError:()=>la,globalPerformanceMonitor:()=>wr,globalCache:()=>sr,getEnvOrDefault:()=>wu,generateConfigTypes:()=>Tu,defaultGeneratedDir:()=>Ea,defaultConfigDir:()=>wa,deepMergeWithArrayStrategy:()=>Hn,deepMerge:()=>ca,createLibraryConfig:()=>Ru,config:()=>Au,bunfigPlugin:()=>Pu,applyEnvVarsToConfig:()=>pr,TypeGenerationError:()=>Wn,SchemaValidationError:()=>Cr,PluginError:()=>Gn,PerformanceMonitor:()=>Un,FileSystemError:()=>Ln,ErrorFactory:()=>kt,EnvVarError:()=>yi,EnvProcessor:()=>bi,ConfigValidator:()=>Jn,ConfigValidationError:()=>Fn,ConfigNotFoundError:()=>gi,ConfigMergeError:()=>Nn,ConfigLoader:()=>qn,ConfigLoadError:()=>yr,ConfigFileLoader:()=>Si,ConfigCache:()=>Vn,CacheUtils:()=>ma,BunfigError:()=>rt,BrowserConfigError:()=>Bn,ArrayMergeStrategies:()=>ya});ih=iu(async()=>{da=import.meta.require,sr=new Vn,wr=new Un,ma={createKey:nu,isEquivalent:ou,estimateMemoryUsage:su},Ou=ci(kn.cwd(),"config"),ku=ci(kn.cwd(),"src/generated"),_s=li.env.CLARITY_LOG_DIR||wf(cu(),"logs"),ii={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_s,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Dn=await fu(),Ke={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"},Ae=Ke,Mu=Ke.red,Vs=Ke.green,Du=Ke.yellow,Us=Ke.blue,Iu=Ke.magenta,Fu=Ke.cyan,An=Ke.white,Nu=Ke.gray,Ks=Ke.bgRed,zs=Ke.bgYellow,xn=Ke.bold,Lu=Ke.dim,Wu=Ke.italic,Bu=Ke.underline,Gu=Ke.reset,ni={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},pa={debug:"\uD83D\uDD0D",info:Us("\u2139"),success:Vs("\u2713"),warning:zs(An(xn(" WARN "))),error:Ks(An(xn(" ERROR ")))},ju=new di("stacks"),ze=new di("bunfig",{showTags:!0}),_u=qe(gr.cwd(),"config"),Vu=qe(gr.cwd(),"src/generated"),Hs=ai.env.CLARITY_LOG_DIR||yf(mu(),"logs"),oi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Hs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},In=await pu(),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"},ae=We,Uu=We.red,Js=We.green,Ku=We.yellow,qs=We.blue,zu=We.magenta,Hu=We.cyan,Tn=We.white,Ju=We.gray,Ys=We.bgRed,Zs=We.bgYellow,qu=We.bgGray,Rn=We.bold,Yu=We.dim,Zu=We.italic,Xu=We.underline,Qu=We.strikethrough,eh=We.reset,si={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ga={debug:"\uD83D\uDD0D",info:qs("\u2139"),success:Js("\u2713"),warning:Zs(Tn(Rn(" WARN "))),error:Ys(Tn(Rn(" ERROR ")))},th=new pi("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}`}},gi=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})}},yr=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}},Fn=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})}},Nn=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}},yi=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})}},Ln=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}},Wn=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}},Cr=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})}},Bn=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})}},Gn=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}},kt={configNotFound(e,t,r){return new gi(e,t,r)},configLoad(e,t,r){return new yr(e,t,r)},configValidation(e,t,r){return new Fn(e,t,r)},configMerge(e,t,r,n){return new Nn(e,t,r,n)},envVar(e,t,r,n){return new yi(e,t,r,n)},fileSystem(e,t,r){return new Ln(e,t,r)},typeGeneration(e,t,r){return new Wn(e,t,r)},schemaValidation(e,t,r){return new Cr(e,t,r)},browserConfig(e,t,r,n){return new Bn(e,t,r,n)},plugin(e,t,r){return new Gn(e,t,r)}},ya={replace:"replace",concat:"concat",smart:"smart"},Ca=/^https?:\/\//,ht=new pi("bunfig",{showTags:!0}),St=new qn,wa=Ye(Lt.cwd(),"config"),Ea=Ye(Lt.cwd(),"src/generated")});oh=fi.env.CLARITY_LOG_DIR||jf(nh(),"logs"),va={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:oh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ci={...va},ty=(async()=>{try{let{loadConfig:e}=await ih().then(()=>na),t=await e({name:"clarity",alias:"logging",defaultConfig:va,cwd:fi.cwd()});if(t)Object.assign(Ci,t)}catch{}return Ci})();Sa={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=Sa,{red:ry,green:ah,yellow:iy,blue:lh,magenta:ny,cyan:oy,white:Xs,gray:sy,bgRed:ch,bgYellow:fh,bgGray:ay,bold:Qs,dim:ly,italic:cy,underline:fy,strikethrough:uy,reset:hy}=Sa,Pn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},uh={debug:"\uD83D\uDD0D",info:lh("\u2139"),success:ah("\u2713"),warning:fh(Xs(Qs(" WARN "))),error:ch(Xs(Qs(" ERROR ")))};dy=new $i("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}`}};$a=class $a 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((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};wi=class wi 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}};Aa=class Aa 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})}};xa=class xa 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}};Yn=class Yn 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})}};Ta=class Ta 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}};Ra=class Ra 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}};Ei=class Ei 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})}};Pa=class Pa 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})}};Oa=class Oa 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}};ar={configNotFound(e,t,r){return new $a(e,t,r)},configLoad(e,t,r){return new wi(e,t,r)},configValidation(e,t,r){return new Aa(e,t,r)},configMerge(e,t,r,n){return new xa(e,t,r,n)},envVar(e,t,r,n){return new Yn(e,t,r,n)},fileSystem(e,t,r){return new Ta(e,t,r)},typeGeneration(e,t,r){return new Ra(e,t,r)},schemaValidation(e,t,r){return new Ei(e,t,r)},browserConfig(e,t,r,n){return new Pa(e,t,r,n)},plugin(e,t,r){return new Oa(e,t,r)}};Ch=/^https?:\/\//;wt=new $i("bunfig",{showTags:!0});my=new Na;py=st(vi.cwd(),"config"),gy=st(vi.cwd(),"src/generated"),Eh={cwd:uf.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},La=Eh});function Ba(e,t,r){let n={file:t,message:"Unknown error",code:Er.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=Er.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=Er.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=Er.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=Er.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function Ga(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(`
|
|
91
91
|
`),o=e.location.line-1;if(o>=0&&o<i.length){let s=Math.max(0,o-1),a=Math.min(i.length-1,o+1);for(let c=s;c<=a;c++){let f=(c+1).toString().padStart(4," "),u=c===o?">":" ";if(r.push(` ${u} ${f} | ${i[c]}`),c===o&&e.location.column>0){let l=" ".repeat(10+e.location.column-1);r.push(` ${l}^`)}}}}if(e.suggestion)r.push(""),r.push(` Suggestion: ${e.suggestion}`);return r.join(`
|
|
92
|
-
`)}var Er;var
|
|
93
|
-
`,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
|
|
94
|
-
`&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function _e(e,t,r,n){let i=0,o=t;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){o=it(e,o);continue}if(s==="`"){o=ct(e,o);continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=pt(e,o);continue}if(s===r)i++;else if(s===n){if(i--,i===0)return o}o++}return-1}function
|
|
95
|
-
`)&&o===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:s}}return null}function
|
|
96
|
-
`)&&r===0){if(n.trim()!=="")t.push(n.trim());n="",i++;continue}n+=o,i++}if(n.trim()!=="")t.push(n.trim());return t}function
|
|
97
|
-
`,o.index)+1,a=e.slice(s,o.index),c=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(a);if(!c)continue;let f=o.index+o[0].length;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]==="<"){let p=
|
|
92
|
+
`)}var Er;var ja=ge(()=>{Er={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 Va(e){return e.endsWith(".vue")}function vh(e){let t={script:null,scriptSetup:null},r=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,n;while((n=r.exec(e))!==null){let i=n[1]||"",o=/lang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??"js",s={content:n[2]??"",attrs:i,setup:/\bsetup\b/.test(i),lang:o};if(s.setup)t.scriptSetup=s;else t.script=s}return t}function it(e,t){let r=e[t];t++;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n===r)return t+1;t++}return t}function ct(e,t){t++;let r=0;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n==="`"&&r===0)return t+1;if(n==="$"&&e[t+1]==="{"){r++,t+=2;continue}if(n==="}"){if(r>0)r--;t++;continue}t++}return t}function pt(e,t){if(e[t+1]==="/"){let r=e.indexOf(`
|
|
93
|
+
`,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 Qn(e,t){let r=e[t];if(r==='"'||r==="'")return it(e,t);if(r==="`")return ct(e,t);if(r==="/"&&(e[t+1]==="/"||e[t+1]==="*"))return pt(e,t);return t}function eo(e){let t=e.split(""),r=0;while(r<e.length){let n=Qn(e,r);if(n>r){for(let i=r;i<n;i++)if(t[i]!==`
|
|
94
|
+
`&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function _e(e,t,r,n){let i=0,o=t;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){o=it(e,o);continue}if(s==="`"){o=ct(e,o);continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=pt(e,o);continue}if(s===r)i++;else if(s===n){if(i--,i===0)return o}o++}return-1}function to(e,t){let r=0,n=t;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=it(e,n);continue}if(i==="`"){n=ct(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=pt(e,n);continue}if(i==="="&&e[n+1]===">"){n+=2;continue}if(i==="<")r++;else if(i===">"){if(r--,r===0)return n}n++}return-1}function lr(e,t=","){let r=[],n=0,i="",o=0;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){let a=it(e,o);i+=e.slice(o,a),o=a;continue}if(s==="`"){let a=ct(e,o);i+=e.slice(o,a),o=a;continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=pt(e,o);continue}if(s==="{"||s==="["||s==="("||s==="<")n++;else if(s==="}"||s==="]"||s===")"||s===">")n--;if(s===t&&n===0){r.push(i),i="",o++;continue}i+=s,o++}if(i.trim()!=="")r.push(i);return r}function Sr(e){let t=e.trim();if(!t.startsWith("{"))return[];let r=_e(t,0,"{","}");if(r===-1)return[];let n=t.slice(1,r),i=[];for(let o of lr(n)){let s=-1,a=0;for(let u=0;u<o.length;u++){let l=o[u];if(l==='"'||l==="'"){u=it(o,u)-1;continue}if(l==="`"){u=ct(o,u)-1;continue}if(l==="{"||l==="["||l==="("||l==="<")a++;else if(l==="}"||l==="]"||l===")"||l===">")a--;else if(l===":"&&a===0){s=u;break}}if(s!==-1){i.push({key:vr(o.slice(0,s).trim()),value:o.slice(s+1).trim(),isMethod:!1});continue}let c=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(o.trim());if(c){i.push({key:vr(c[1]),value:o.trim(),isMethod:!0});continue}let f=o.trim();if(f)i.push({key:vr(f),value:"",isMethod:!1})}return i}function vr(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function br(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function $r(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n;while((n=r.exec(e))!==null){let i=n.index+n[0].length;while(i<e.length&&/\s/.test(e[i]))i++;let o=null;if(e[i]==="<"){let c=to(e,i);if(c===-1)return null;o=e.slice(i+1,c).trim(),i=c+1;while(i<e.length&&/\s/.test(e[i]))i++}if(e[i]!=="(")continue;let s=_e(e,i,"(",")");if(s===-1)return null;let a=lr(e.slice(i+1,s));return{generic:o,arg:a.length>0?a[0].trim():null}}return null}function bh(e,t){let r=Ua(e,t);if(!r)return null;return r.kind==="interface"?e.slice(r.bodyStart,r.end):e.slice(r.bodyStart,r.end).trim()}function Ua(e,t){let r=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(r){let i=r.index+r[0].length-1,o=_e(e,i,"{","}");if(o!==-1)return{kind:"interface",start:r.index,end:o+1,bodyStart:i}}let n=new RegExp(`\\btype\\s+${t}\\b[^=]*=`,"m").exec(e);if(n){let i=n.index+n[0].length,o=0,s=i;while(i<e.length){let a=e[i];if(a==='"'||a==="'"){i=it(e,i);continue}if(a==="`"){i=ct(e,i);continue}if(a==="{"||a==="["||a==="("||a==="<")o++;else if(a==="}"||a==="]"||a===")"||a===">")o--;else if((a===";"||a===`
|
|
95
|
+
`)&&o===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:s}}return null}function Sh(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let r=e.indexOf("<",t),n=to(e,r);if(n===-1)return null;if(e.slice(n+1).trim()!=="")return null;return e.slice(r+1,n).trim()}function Xn(e){let t=e.trim(),r=Sh(t);if(r!==null)return{type:r,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let n=_e(t,0,"[","]");if(n!==-1){let i=lr(t.slice(1,n)).map((o)=>Xn(o).type).filter((o)=>o!=="unknown");return{type:i.length>0?[...new Set(i)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let n=Sr(t),i=n.find((c)=>c.key==="type"),o=n.find((c)=>c.key==="required"),s=i?Xn(i.value).type:"unknown",a=!(o&&o.value.trim()==="true");return{type:s,optional:a}}if(_a[t])return{type:_a[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function Ri(e){let t=e.trim();if(t.startsWith("{")){let r=Sr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>{if(n.isMethod||n.value==="")return`${br(n.key)}?: unknown`;let i=Xn(n.value);return`${br(n.key)}${i.optional?"?":""}: ${i.type}`}).join(", ")} }`}if(t.startsWith("[")){let r=_e(t,0,"[","]");if(r===-1)return null;let n=lr(t.slice(1,r)).map((i)=>vr(i.trim())).filter((i)=>i!=="");if(n.length===0)return"{}";return`{ ${n.map((i)=>`${br(i)}?: unknown`).join(", ")} }`}return null}function $h(e){let t=e.trim();if(!t.startsWith("["))return null;let r=_e(t,0,"[","]");if(r===-1)return null;let n=lr(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(vr(i))).join(", ")}]`}function Ah(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=Sr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>`${JSON.stringify(n.key)}: (...args: any[]) => void`).join(", ")} }`}function Ka(e){return $h(e)??Ah(e)}function xh(e){let t=[],r=0,n="",i=0;while(i<e.length){let o=e[i];if(o==='"'||o==="'"){let s=it(e,i);n+=e.slice(i,s),i=s;continue}if(o==="`"){let s=ct(e,i);n+=e.slice(i,s),i=s;continue}if(o==="/"&&(e[i+1]==="/"||e[i+1]==="*")){let s=pt(e,i);n+=e.slice(i,s),i=s;continue}if(o==="="&&e[i+1]===">"){n+="=>",i+=2;continue}if(o==="{"||o==="["||o==="("||o==="<")r++;else if(o==="}"||o==="]"||o===")"||o===">")r--;if((o===";"||o===","||o===`
|
|
96
|
+
`)&&r===0){if(n.trim()!=="")t.push(n.trim());n="",i++;continue}n+=o,i++}if(n.trim()!=="")t.push(n.trim());return t}function Th(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=_e(t,0,"{","}");if(r===-1||t.slice(r+1).trim()!=="")return null;let n=xh(t.slice(1,r));if(n.length===0)return"{}";let i=[];for(let o of n){let s=/^\(\s*\w+\s*:\s*/.exec(o);if(!s)return null;let a=s[0].length,c=o[a];if(c!=="'"&&c!=='"'&&c!=="`")return null;let f=it(o,a),u=o.slice(a+1,f-1),l=_e(o,o.indexOf("(",0),"(",")");if(l===-1)return null;let p=o.slice(a,l),C=lr(p).slice(1),E=o.slice(l+1).trim();if(E.startsWith(":"))E=E.slice(1).trim();if(E==="")E="void";i.push(`${JSON.stringify(u)}: (${C.map((y)=>y.trim()).join(", ")}) => ${E}`)}return`{ ${i.join(", ")} }`}function ro(e){let t=e;for(let r of["defineProps","defineEmits","defineExpose","defineSlots","defineOptions"])t=Rh(t,r);return t}function Rh(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n=[],i=e,o;while((o=r.exec(e))!==null){let s=e.lastIndexOf(`
|
|
97
|
+
`,o.index)+1,a=e.slice(s,o.index),c=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(a);if(!c)continue;let f=o.index+o[0].length;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]==="<"){let p=to(e,f);if(p===-1)continue;f=p+1;while(f<e.length&&/\s/.test(e[f]))f++}if(e[f]!=="(")continue;let u=_e(e,f,"(",")");if(u===-1)continue;if(c[1]){let p=s+a.length-c[1].length,C=e.indexOf("(",p);if(C!==-1){let E=_e(e,C,"(",")");if(E!==-1)u=E}}let l=u+1;while(l<e.length&&e[l]!==`
|
|
98
98
|
`&&/\s|;/.test(e[l]))l++;if(e[l]===`
|
|
99
|
-
`)l++;n.push([s,l])}for(let s=n.length-1;s>=0;s--)i=i.slice(0,n[s][0])+i.slice(n[s][1]);return i}function
|
|
99
|
+
`)l++;n.push([s,l])}for(let s=n.length-1;s>=0;s--)i=i.slice(0,n[s][0])+i.slice(n[s][1]);return i}function io(e){let t=Ph(e);if(t!==-1){let r=/^export\s+default\b/.exec(e.slice(t))?.[0];if(!r)return{options:null,script:e,passthrough:!1};let n=t+r.length;while(n<e.length&&/\s/.test(e[n]))n++;let i=-1,o=-1,s=-1;if(e[n]==="{")i=n,o=_e(e,n,"{","}"),s=o;else if(e.startsWith("defineComponent",n)){let f=e.indexOf("(",n);if(f!==-1){let u=f+1;while(u<e.length&&/\s/.test(e[u]))u++;if(e[u]==="{")i=u,o=_e(e,u,"{","}"),s=_e(e,f,"(",")")}}if(i===-1||o===-1||s===-1)return{options:null,script:e,passthrough:!0};let a=s+1;if(e[a]===";")a++;let c=(e.slice(0,t)+e.slice(a)).trim();return{options:e.slice(i,o+1),script:c,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function Ph(e){let t=0,r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=it(e,r);continue}if(n==="`"){r=ct(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=pt(e,r);continue}if(n==="{"||n==="["||n==="(")t++;else if(n==="}"||n==="]"||n===")")t=Math.max(0,t-1);else if(t===0&&e.startsWith("export",r)){let i=r===0?"":e[r-1],o=e[r+6]??"";if(!/[\w$]/.test(i)&&!/[\w$]/.test(o)){if(/^export\s+default\b/.exec(e.slice(r)))return r}}r++}return-1}function Ai(e,t){let r=Sr(e).find((n)=>n.key===t);return r&&r.value!==""?r.value:null}function xi(e,t){let r=kh(e),n=e;for(let i=r.length-1;i>=0;i--){let o=r[i],s=n.slice(0,o.start)+n.slice(o.end);if(Oh(s,o.name))continue;if(new RegExp(`\\btypeof\\s+${o.name}\\b`).test(t))continue;n=s}return n}function Oh(e,t){let r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=it(e,r);continue}if(n==="`"){r=ct(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=pt(e,r);continue}if(/[A-Za-z_$]/.test(n)){let i=r+1;while(i<e.length&&/[\w$]/.test(e[i]))i++;if(e.slice(r,i)===t)return!0;r=i;continue}r++}return!1}function kh(e){let t=[],r=Mh(e),n=/^[ \t]*(const|let|var|(?:async[ \t]+)?function)[ \t]+([A-Za-z_$][\w$]*)[ \t]*(?::[^=\n]+)?=?/gm,i;while((i=n.exec(e))!==null){let o=e.lastIndexOf(`
|
|
100
100
|
`,i.index)+1;if(!r.has(o))continue;if(/\bexport\b/.test(e.slice(o,i.index)))continue;let s=i[1],a=i[2],c=i.index+i[0].length,f=-1;if(s.endsWith("function")){let u=e.indexOf("(",c);if(u===-1)continue;let l=_e(e,u,"(",")");if(l===-1)continue;c=l+1;while(c<e.length&&/\s/.test(e[c]))c++;if(e[c]===":")while(c<e.length&&e[c]!=="{"&&e[c]!==`
|
|
101
101
|
`)c++;while(c<e.length&&/\s/.test(e[c])&&e[c]!==`
|
|
102
102
|
`)c++;if(e[c]!=="{")continue;let p=_e(e,c,"{","}");if(p===-1)continue;f=p+1}else{let u=0;while(c<e.length){let l=e[c];if(l==='"'||l==="'"){c=it(e,c);continue}if(l==="`"){c=ct(e,c);continue}if(l==="/"&&(e[c+1]==="/"||e[c+1]==="*")){c=pt(e,c);continue}if(l==="{"||l==="["||l==="(")u++;else if(l==="}"||l==="]"||l===")")u--;else if(l===";"&&u===0){f=c+1;break}else if(l===`
|
|
103
103
|
`&&u===0){f=c;break}c++}if(f===-1)f=e.length}if(e[f]===`
|
|
104
|
-
`)f++;t.push({name:a,start:i.index,end:f})}return t}function
|
|
104
|
+
`)f++;t.push({name:a,start:i.index,end:f})}return t}function Mh(e){let t=new Set([0]),r=0,n=0;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=it(e,n);continue}if(i==="`"){n=ct(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=pt(e,n);continue}if(i==="{"||i==="["||i==="(")r++;else if(i==="}"||i==="]"||i===")")r=Math.max(0,r-1);if(i===`
|
|
105
105
|
`&&r===0)t.add(n+1);n++}return t}function Ti(e,t,r){let n=e.indexOf(r);if(n===-1)return e;let i=e.lastIndexOf(`
|
|
106
|
-
`,n)+1;if(/\bexport\b/.test(e.slice(i,n)))return e;let o=e.slice(0,n)+e.slice(n+r.length);if(new RegExp(`\\b${t}\\b`).test(o))return e;return o}function
|
|
106
|
+
`,n)+1;if(/\bexport\b/.test(e.slice(i,n)))return e;let o=e.slice(0,n)+e.slice(n+r.length);if(new RegExp(`\\b${t}\\b`).test(o))return e;return o}function no(e){let t="",r=0,n=()=>{for(let o=t.length-1;o>=0;o--)if(!/\s/.test(t[o]))return t[o];return""},i=(o)=>{for(let s=o;s<e.length;s++)if(!/\s/.test(e[s]))return e[s];return""};while(r<e.length){let o=e[r];if(o==='"'||o==="'"){let s=it(e,r);t+=e.slice(r,s),r=s;continue}if(o==="`"){let s=ct(e,r);t+=e.slice(r,s),r=s;continue}if(o==="/"&&e[r+1]==="*"){let s=pt(e,r);t+=e.slice(r,s).replace(/\s*\n\s*/g," "),r=s;continue}if(o==="/"&&e[r+1]==="/"){let s=r+2;while(s<e.length&&e[s]!==`
|
|
107
107
|
`)s++;let a=e.slice(r+2,s).trim();if(a!==""&&!a.includes("*/"))t+=`/* ${a} */`;r=s;continue}if(o===`
|
|
108
|
-
`){let s=n(),a=i(r+1);if(s===""||a===""){r++;continue}let c=
|
|
109
|
-
${t.scriptSetup.content}`:t.script.content;if(r=x.script,x.options){let S=Ai(x.options,"props");if(S)n=Ri(S);let M=Ai(x.options,"emits");if(M)i=
|
|
110
|
-
`)}var
|
|
111
|
-
defineProps<${r}>()`,null)}function
|
|
112
|
-
`)&&n===0){let c=i+1;if(!
|
|
113
|
-
`),r=null,n=
|
|
114
|
-
`)}var
|
|
108
|
+
`){let s=n(),a=i(r+1);if(s===""||a===""){r++;continue}let c=Dh(t);if(!c&&("{;,(<:=[".includes(s)||"}),]>;|&".includes(a))){if(!t.endsWith(" ")&&!t.endsWith(";"))t+=" "}else if(c){if(!t.endsWith(" "))t+=" "}else{if(t.endsWith(" "))t=t.slice(0,-1);t+="; "}r++;while(r<e.length&&(e[r]===" "||e[r]==="\t"))r++;continue}t+=o,r++}return t}function Dh(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 Pi(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=$r(n,"defineProps");if(!i)continue;if(i.generic){let o=i.generic;if(o.startsWith("{"))return{type:o};if(/^[A-Za-z_$][\w$]*$/.test(o)){for(let s of r){let a=Ua(s,o);if(!a)continue;let c=bh(s,o);if(c===null)continue;return{type:c,inlinedLocal:{name:o,declText:s.slice(a.start,a.end)}}}return{type:o}}return{type:o}}if(i.arg){let o=Ri(i.arg);if(o!==null)return{type:o}}}return null}function oo(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=$r(n,"defineEmits");if(!i)continue;if(i.generic)return Th(i.generic)??i.generic;if(i.arg){let o=Ka(i.arg);if(o!==null)return o}}return null}function so(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=$r(n,"defineExpose");if(!i||!i.arg||!i.arg.startsWith("{"))continue;let o=Sr(i.arg);if(o.length===0)return null;return`{ ${o.map((s)=>{if(s.value===""&&/^[A-Za-z_$][\w$]*$/.test(s.key))return`${br(s.key)}: typeof ${s.key}`;let a=s.isMethod||/=>|^\s*function\b/.test(s.value);return`${br(s.key)}: ${a?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function za(e){let t=vh(e),r="",n=null,i=null;if(t.script){let x=io(t.script.content);if(x.passthrough)return t.scriptSetup?`${t.script.content}
|
|
109
|
+
${t.scriptSetup.content}`:t.script.content;if(r=x.script,x.options){let S=Ai(x.options,"props");if(S)n=Ri(S);let M=Ai(x.options,"emits");if(M)i=Ka(M)}}let o=t.scriptSetup?.content??null,s=o!==null?ro(o):null,a=Pi(o,o!==null?null:r),c=a?.type??n??"{}",f=oo(o,null)??i,u=so(o,null),l=a?.inlinedLocal;if(l){if(r=Ti(r,l.name,l.declText),s!==null)s=Ti(s,l.name,l.declText)}let p=[c,u??"{}"];if(f)p.push("{}","{}","{}","{}","{}",f);let C=no(`DefineComponent<${p.join(", ")}>`),E=[],y=xi(r,C);if(y.trim()!=="")E.push(y);if(s&&s.trim()!==""){let x=xi(s,C);if(x.trim()!=="")E.push(x)}return E.push("import type { DefineComponent } from 'vue'"),E.push(`type __DtsxComponentType = ${C}`),E.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),E.push("export default __dtsx_component__"),E.join(`
|
|
110
|
+
`)}var _a;var ao=ge(()=>{_a={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 Ja(e){return e.endsWith(".stx")}function Ih(e){let t=[],r=/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi,n;while((n=r.exec(e))!==null){let i=n[1]??"",o=/\blang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??(/\b(?:type\s*=\s*["'](?:text\/)?typescript["']|typescript)\b/i.test(i)?"ts":"js"),s=/\bserver\b/i.test(i)?"server":/\bclient\b/i.test(i)?"client":"universal";t.push({content:n[2]??"",kind:"script",attrs:i,context:s,lang:o,start:n.index})}return t}function Fh(e){let t=[],r=/^[ \t]*@ts[ \t]*(?:\r?\n|$)/gm,n;while((n=r.exec(e))!==null){let i=r.lastIndex,o=/^[ \t]*@endts[ \t]*(?:\r?\n|$)/gm;o.lastIndex=i;let s=o.exec(e),a=s?.index??e.length;if(t.push({content:e.slice(i,a),kind:"ts",attrs:"",context:"universal",lang:"ts",start:n.index}),!s)break;r.lastIndex=o.lastIndex}return t}function Nh(e){return[...Ih(e),...Fh(e)].sort((t,r)=>t.start-r.start)}function Lh(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 Wh(e){let t=/(?:\$?props)\s+as\s+/g,r;while((r=t.exec(e))!==null){let n=t.lastIndex;while(n<e.length&&/\s/.test(e[n]))n++;if(e[n]==="{"){let s=_e(e,n,"{","}");if(s!==-1)return e.slice(n,s+1).trim();continue}let i=/^[A-Za-z_$][\w$]*/.exec(e.slice(n))?.[0];if(!i)continue;let o=n+i.length;while(o<e.length&&/\s/.test(e[o]))o++;if(e[o]==="<"){let s=_e(e,o,"<",">");if(s!==-1)o=s+1}return e.slice(n,o).trim()}return null}function Bh(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function Gh(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 jh(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function _h(e){let t=eo(e),r=new Map,n=/\$props(?:\.([A-Za-z_$][\w$]*)|\[\s*(['"])([^'"\n]+)\2\s*\])/g,i;while((i=n.exec(e))!==null){if(t.slice(i.index,i.index+6)!=="$props")continue;let o=i[1]??i[3],s=Gh(e.slice(n.lastIndex));r.set(o,jh(r.get(o),s))}if(r.size===0)return null;return{type:`{ ${[...r].map(([o,s])=>`${/^[A-Za-z_$][\w$]*$/.test(o)?o:JSON.stringify(o)}?: ${s}`).join(", ")} }`}}function Vh(e){let t=Pi(e,null);if(t)return t;let r=Wh(e)??Bh(e);if(!r)return _h(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 Pi(`${e}
|
|
111
|
+
defineProps<${r}>()`,null)}function Uh(e){return ro(e)}function Ha(e){let t=eo(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 Kh(e){let t=[],r=0,n=0,i=0;while(i<e.length){let s=e[i],a=Qn(e,i);if(a>i){i=a;continue}if(s==="{"||s==="["||s==="(")n++;else if(s==="}"||s==="]"||s===")")n=Math.max(0,n-1);if((s===";"||s===`
|
|
112
|
+
`)&&n===0){let c=i+1;if(!Ha(e.slice(r,c)))t.push([r,c]);r=c}i++}if(r<e.length&&!Ha(e.slice(r)))t.push([r,e.length]);let o=e;for(let s=t.length-1;s>=0;s--)o=o.slice(0,t[s][0])+o.slice(t[s][1]);return o}function qa(e){let t=Nh(e).filter(Lh).map((y)=>y.content).join(`
|
|
113
|
+
`),r=null,n=io(t);if(n.passthrough)return t;if(t=n.script,n.options){let y=Ai(n.options,"props");if(y)r=Ri(y)}let i=t,o=Uh(t),s=Vh(i),a=s?.type??r??"{}",c=oo(i,null),f=so(i,null),u=$r(i,"defineSlots")?.generic??null,l=s?.inlinedLocal;if(l)o=Ti(o,l.name,l.declText);let p=`DefineComponent<${a}>`,C=[];if(c)C.push(`readonly __stxEmits?: ${c}`);if(u)C.push(`readonly __stxSlots?: ${u}`);if(f)C.push(`readonly __stxExposed?: ${f}`);if(C.length>0)p+=` & { ${C.join(", ")} }`;p=no(p),o=Kh(xi(o,p));let E=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${p}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(o.trim()!=="")E.push(o);return E.join(`
|
|
114
|
+
`)}var Ya=ge(()=>{ao()});function At(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}
|
|
115
115
|
`;return`${n.trim()}
|
|
116
116
|
`}let r="";for(let n=0;n<e.length;n++){if(n>0)r+=`
|
|
117
117
|
`;r+=e[n].trim()}return`${r}
|
|
118
|
-
`}function
|
|
119
|
-
`)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let s=
|
|
120
|
-
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function
|
|
121
|
-
`)||e.includes("\r"))return"string";return e}function
|
|
118
|
+
`}function go(e){return e.replaceAll("*/","*\\/")}function co(e){return il(e).replace(/\n[ \t]*(?=\n)/g,"")}function il(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 Co(){Ii=!0,Ze=null}function wo(){Ii=!1;let e=Ze;return Ze=null,e}function Eo(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 zh(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 lo(e,t){let r=0,n=0;while((n=e.indexOf(t,n))!==-1)r++,n+=t.length;return r}function Za(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 Oi(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&&Za(t.charCodeAt(n)))n++;let i=t.slice(1,n),o=t.charCodeAt(n);if(o>32&&o!==62&&o!==47)return!1;if(t.endsWith("/>"))return!0;let s=t.lastIndexOf("</");if(s===-1)return!1;let a=s+2;while(a<t.length&&Za(t.charCodeAt(a)))a++;return t.slice(s+2,a)===i&&t.charCodeAt(a)===62&&a===t.length-1}function ki(e){let t=e.length,r=!1;for(let s=1;s<t;s++)if(e.charCodeAt(s)<=32&&e.charCodeAt(s-1)<=32){r=!0;break}if(!r)for(let s=0;s<t;s++){let a=e.charCodeAt(s);if(a===10||a===13||a===9){r=!0;break}}if(!r)return e;let n=[],i=-1,o=!1;for(let s=0;s<t;s++)if(e.charCodeAt(s)<=32){if(!o){if(i>=0)n.push(e.substring(i,s));n.push(" "),o=!0,i=-1}}else{if(o||i<0)i=s;o=!1}if(i>=0)n.push(e.substring(i));return n.join("")}function Ne(e,t=!1,r=!1,n=0){if(!e||typeof e!=="string")return"unknown";if(n>=yo)return"unknown";let i=e.trim();if(Oi(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(`
|
|
119
|
+
`)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let s=Hh(i);if(s!==null){if(s==="string"||!t)return"string";return s}}if(Eo(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 ho(i,t,n+1);if(i.startsWith("{")&&i.endsWith("}"))return od(i,t,n+1);if(i.startsWith("class ")||i.startsWith("class{"))return id(i);if(i.startsWith("new "))return rd(i);if(i.endsWith("as const")){let s=i.slice(0,-8).trim();if(s.startsWith("[")&&s.endsWith("]")){let a=s.slice(1,-1).trim();if(!a)return"readonly []";let c=Mi(a),f=[];for(let u=0;u<c.length;u++)f.push(Ne(c[u].trim(),!0,!1,n+1));return`readonly [${f.join(", ")}]`}return Ne(s,!0,r,n+1)}if(Di(i)!==-1||i.startsWith("function")||i.startsWith("async"))return ul(i,r,n,t);if(i.startsWith("`")&&i.endsWith("`"))return td(i,t);if(i.startsWith("Promise."))return al(i,t,n);if(i.startsWith("await "))return"unknown";if(i.charCodeAt(i.length-1)===110&&i.length>1&&zh(i)){if(t)return i;return"bigint"}if(i.startsWith("Symbol(")||i==="Symbol.for")return"symbol";let o=ll(i);if(o!==null)return o;if(nl(i))return"boolean";if(Zh(i))return"number";return"unknown"}function Xa(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return Mt(e,0,t)===e.length}function Hh(e){if(Xa(e))return e;let t=Jh(e);if(t.length<2)return null;let r=!1,n=!0,i="";for(let o of t){let s=o.trim();if(Xa(s))r=!0,i+=qh(s);else n=!1}if(n)return Yh(i);if(r)return"string";return null}function Jh(e){let t=[],r=0,n=0,i=0;while(i<e.length){let o=e.charCodeAt(i);if(o===39||o===34||o===96){i=Mt(e,i,o);continue}if(o===40||o===91||o===123)r++;else if(o===41||o===93||o===125)r--;else if(o===43&&r===0)t.push(e.slice(n,i)),n=i+1;i++}return t.push(e.slice(n)),t}function qh(e){return e.slice(1,-1).replace(/\\(.)/g,(t,r)=>{if(r==="n")return`
|
|
120
|
+
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function Yh(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Zh(e){if(e==="")return!1;let t=!1,r=!1;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);if(i>=48&&i<=57){t=!0;continue}if(i===43||i===45||i===42||i===47||i===37){r=!0;continue}if(i===46||i===40||i===41||i<=32)continue;return!1}return t&&r}function nl(e){let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=Mt(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 Xh(e,t=!1,r=0){return Ne(e,t,!0,r)}function fr(e,t=!1,r=""){let n=ol(r),i=[],o=!1,s=0;while(s<e.length){let c=e.charCodeAt(s);if(c===34||c===39||c===96){s=Mt(e,s,c);continue}if(c===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10&&e.charCodeAt(s)!==13)s++;continue}if(c===47&&e.charCodeAt(s+1)===42){let f=e.indexOf("*/",s+2);s=f===-1?e.length:f+2;continue}if(e.startsWith("function",s)&&fo(e,s,8)||e.startsWith("class",s)&&fo(e,s,5)){let f=ed(e,s);if(f!==-1){s=uo(e,f);continue}}if(c===61&&e.charCodeAt(s+1)===62){let f=s+2;while(f<e.length&&e.charCodeAt(f)<=32)f++;if(e.charCodeAt(f)===123){s=uo(e,f);continue}}if(e.startsWith("return",s)&&(s===0||!$t(e.charCodeAt(s-1)))&&!$t(e.charCodeAt(s+6))){s+=6;let f=!1;while(s<e.length&&e.charCodeAt(s)<=32){let x=e.charCodeAt(s);if(x===10||x===13)f=!0;s++}if(f||s>=e.length||e.charCodeAt(s)===59||e.charCodeAt(s)===125){o=!0;continue}let u=s,l=0,p=0,C=0;while(s<e.length){let x=e.charCodeAt(s);if(x===34||x===39||x===96){s=Mt(e,s,x);continue}if(x===47&&e.charCodeAt(s+1)===47){if(l===0&&p===0&&C===0)break;while(s<e.length&&e.charCodeAt(s)!==10&&e.charCodeAt(s)!==13)s++;continue}if(x===47&&e.charCodeAt(s+1)===42){let S=e.indexOf("*/",s+2);s=S===-1?e.length:S+2;continue}if(x===40)l++;else if(x===41)l--;else if(x===91)p++;else if(x===93)p--;else if(x===123)C++;else if(x===125){if(C===0&&l===0&&p===0)break;C--}else if(x===59&&l===0&&p===0&&C===0)break;else if((x===10||x===13)&&l===0&&p===0&&C===0){let S=s+1;while(S<e.length&&e.charCodeAt(S)<=32)S++;if(e.startsWith("return",S)&&!$t(e.charCodeAt(S+6)))break}s++}let E=e.slice(u,s).trim(),y=co(Wt(E,n));if(!i.includes(y))i.push(y);continue}s++}if(o&&!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 ol(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=0,i=0,o=0;for(let s=0;s<=r.length;s++){let a=r.charCodeAt(s);if(a===40||a===91||a===123)i++;else if(a===41||a===93||a===125)i--;else if(a===60)o++;else if(a===62&&r.charCodeAt(s-1)!==61&&o>0)o--;if(s!==r.length&&(a!==44||i!==0||o!==0))continue;let c=r.slice(n,s).trim(),f=c.indexOf(":");if(f!==-1){let u=c.slice(0,f).trim().replace(/^\.\.\./,"").replace(/\?$/,""),l=c.slice(f+1).trim(),p=l.indexOf("=");if(p!==-1)l=l.slice(0,p).trim();if(Fi(u)&&l)t.set(u,l)}n=s+1}return t}function Wt(e,t){let r=e.trim();while(sl(r))r=r.slice(1,-1).trim();if(Oi(r))return"JSX.Element";if(r.startsWith("await ")){let o=Wt(r.slice(6),t);return o.startsWith("Promise<")&&o.endsWith(">")?o.slice(8,-1):o}if(t.has(r))return t.get(r);if(r.startsWith("!"))return"boolean";if(r.startsWith("fetch("))return"Promise<Response>";let n=Qh(r);if(n){let o=Wt(n.whenTrue,t),s=Wt(n.whenFalse,t);return o===s?o:`${o} | ${s}`}if(nl(r))return"boolean";let i=0;for(let o=r.length-1;o>=0;o--){let s=r.charCodeAt(o);if(s===41||s===93||s===125)i++;else if(s===40||s===91||s===123)i--;else if(i===0&&(s===43||s===45||s===42||s===47||s===37)){let a=Wt(r.slice(0,o),t),c=Wt(r.slice(o+1),t);if(s===43&&(a==="string"||c==="string"))return"string";if(a==="number"&&c==="number")return"number";break}}return Ne(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(o)=>{let s=o.slice(7);return t.get(s)??"unknown"})}function sl(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 Qh(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 fo(e,t,r){return(t===0||!$t(e.charCodeAt(t-1)))&&!$t(e.charCodeAt(t+r))}function ed(e,t){for(let r=t;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=Mt(e,r,n)-1;continue}if(n===123)return r;if(n===59)return-1}return-1}function uo(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=Mt(e,n,i);continue}if(i===47&&e.charCodeAt(n+1)===47){n+=2;while(n<e.length&&e.charCodeAt(n)!==10&&e.charCodeAt(n)!==13)n++;continue}if(i===47&&e.charCodeAt(n+1)===42){let o=e.indexOf("*/",n+2);n=o===-1?e.length:o+2;continue}if(i===123)r++;else if(i===125)r--;n++}return n}function Mt(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=uo(e,n+1);continue}if(n++,i===r)break}return n}function td(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
|
|
121
|
+
`)||e.includes("\r"))return"string";return e}function rd(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&&($t(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let i=e.slice(r,t);{let o=e.slice(t),s=o;if(o.startsWith("<")){let c=0,f=-1;for(let u=0;u<o.length;u++)if(o[u]==="<")c++;else if(o[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=o.slice(0,f+1);s=o.slice(f+1);let l=s.indexOf("(");if(l!==-1){let p=0,C=-1;for(let E=l;E<s.length;E++)if(s[E]==="(")p++;else if(s[E]===")"){if(p--,p===0){C=E;break}}if(C!==-1){if(s.slice(C+1).trimStart().startsWith("."))return"unknown"}}return`${i}${u}`}}let a=s.indexOf("(");if(a!==-1){let c=0,f=-1;for(let u=a;u<s.length;u++)if(s[u]==="(")c++;else if(s[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(s.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(i){case"Date":return"Date";case"Map":return"Map<any, any>";case"Set":return"Set<any>";case"WeakMap":return"WeakMap<any, any>";case"WeakSet":return"WeakSet<any>";case"RegExp":return"RegExp";case"Error":return"Error";case"Array":return"any[]";case"Object":return"object";case"Function":return"Function";case"Promise":return"Promise<any>";default:return i}}return"unknown"}function id(e){return"{ new (...args: any[]): any }"}function al(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<${Ne(i,t,!1,r+1)}>`}return"Promise<unknown>"}if(e.startsWith("Promise.reject("))return"Promise<never>";if(e.startsWith("Promise.all(")){let n=e.indexOf("[",12),i=e.lastIndexOf("]");if(n!==-1&&i>n){let o=e.slice(n+1,i).trim(),s=Mi(o),a=[];for(let c=0;c<s.length;c++){let f=s[c].trim();if(f.startsWith("Promise.resolve(")){let u=al(f,t,r+1),l=u.indexOf("<"),p=u.lastIndexOf(">");a.push(l!==-1&&p>l?u.slice(l+1,p):"unknown")}else a.push(Ne(f,t,!1,r+1))}return`Promise<[${a.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function ho(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(r>=yo)return"unknown[]";let i=Mi(n),o=!1;for(let p=0;p<i.length;p++){let C=i[p],E=C.length;while(E>0&&C.charCodeAt(E-1)<=32)E--;if(E>=8&&C.slice(E-8,E)==="as const"){o=!0;break}}if(o){let p=[];for(let C=0;C<i.length;C++){let E=i[C].trim();if(E.endsWith("as const")){let y=E.slice(0,-8).trim();if(y.startsWith("[")&&y.endsWith("]")){let x=y.slice(1,-1).trim(),S=Mi(x),M=[];for(let D=0;D<S.length;D++)M.push(Ne(S[D].trim(),!0,!1,r+1));p.push(`readonly [${M.join(", ")}]`)}else p.push(Ne(y,!0,!1,r+1))}else if(E.startsWith("[")&&E.endsWith("]"))p.push(ho(E,!0,r+1));else p.push(Ne(E,!0,!1,r+1))}return`readonly [
|
|
122
122
|
${p.join(` |
|
|
123
123
|
`)}
|
|
124
|
-
]`}let s=Ii&&!t,a=[],c=[];for(let p of i){let C=p.trim(),E=Ze;if(Ze=null,C.startsWith("...")){let y=C.slice(3).trim(),x=Ne(y,!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(cr(y))a.push(`(typeof ${y})[number]`);else a.push("unknown")}else if(C.startsWith("[")&&C.endsWith("]"))a.push(
|
|
125
|
-
`:"",x=E,S=!1;if(E==="..."){let I=p.trim(),j=cr(I)?`typeof ${I}`:Ne(I,t,!1,r+1);if(j!=="unknown")s.push(j);if(a&&(cr(I)||I.startsWith("{")))c.push(`...${ki(I)}`);continue}let M=Ze;Ze=null;let D,O=p.trim();if(O===E&&Fi(O))D=`typeof ${O}`;else if(
|
|
126
|
-
${x}: ${D}`);else o.push(`${y}${x}: ${D}`);if(a){let I=
|
|
124
|
+
]`}let s=Ii&&!t,a=[],c=[];for(let p of i){let C=p.trim(),E=Ze;if(Ze=null,C.startsWith("...")){let y=C.slice(3).trim(),x=Ne(y,!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(cr(y))a.push(`(typeof ${y})[number]`);else a.push("unknown")}else if(C.startsWith("[")&&C.endsWith("]"))a.push(ho(C,t,r+1));else a.push(Xh(C,t,r+1));if(s)c.push(Ze);Ze=E}if(s)if(po(e))Ze=ki(e);else{let p=[];for(let C=0;C<i.length;C++){let E=i[C].trim();if(E.endsWith("as const"))continue;if(mo(E)||E==="null"||E==="undefined")p.push(E);else if(E.startsWith("[")&&po(E))p.push(ki(E));else if(E.startsWith("{")){if(c[C])p.push(c[C])}else{let y=Ne(E,!1,!1,0);if(y!=="unknown")p.push(y)}}if(p.length>0)Ze=`[${p.join(", ")}]`}if(t)return`readonly [${a.join(", ")}]`;let f=new Set,u=[],l=!0;for(let p of a){if(!f.has(p))f.add(p),u.push(p);if(l){if(!(Eo(p)||p==="true"||p==="false"||p.charCodeAt(0)===34&&p.charCodeAt(p.length-1)===34||p.charCodeAt(0)===39&&p.charCodeAt(p.length-1)===39))l=!1}}if(l&&a.length<=10)return`readonly [${a.join(", ")}]`;if(u.length===1)return`${u[0]}[]`;return`(${u.join(" | ")})[]`}function Mi(e){let t=[],r=0,n=0,i=!1,o=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(!i&&(c===34||c===39||c===96))i=!0,o=c;else if(i&&c===o&&(a===0||e.charCodeAt(a-1)!==92))i=!1;if(!i){if(c===91||c===123||c===40)n++;else if(c===93||c===125||c===41)n--;else if(c===44&&n===0){let f=e.substring(r,a).trim();if(f)t.push(f);r=a+1;continue}}}let s=e.substring(r).trim();if(s)t.push(s);return t}function mo(e){if(Eo(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function nd(e){return e==="number"||e==="string"||e==="boolean"}function po(e){let t=!1,r=0,n=e.length;for(let i=0;i<n;i++){let o=e.charCodeAt(i);if(t){if(o===92){i++;continue}if(o===r)t=!1;continue}if(o===34||o===39||o===96){t=!0,r=o;continue}if(o===61&&i+1<n&&e.charCodeAt(i+1)===62)return!1;if(o>=97&&o<=122){let s=i;while(i<n&&(e.charCodeAt(i)>=97&&e.charCodeAt(i)<=122||e.charCodeAt(i)>=65&&e.charCodeAt(i)<=90||e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57||e.charCodeAt(i)===95||e.charCodeAt(i)===36))i++;let a=e.slice(s,i);if(a==="new"||a==="async"||a==="await"||a==="function"||a==="yield"||a==="console"||a==="process")return!1;let c=i;while(c<n&&e.charCodeAt(c)<=32)c++;if(c<n&&e.charCodeAt(c)===40)return!1;i--}}return!0}function od(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"{}";if(r>=yo)return"Record<string, unknown>";let i=cd(n),o=[],s=[],a=Ii&&!t,c=[];for(let[l,p]of i){let{comments:C,key:E}=fl(l),y=C?`${C}
|
|
125
|
+
`:"",x=E,S=!1;if(E==="..."){let I=p.trim(),j=cr(I)?`typeof ${I}`:Ne(I,t,!1,r+1);if(j!=="unknown")s.push(j);if(a&&(cr(I)||I.startsWith("{")))c.push(`...${ki(I)}`);continue}let M=Ze;Ze=null;let D,O=p.trim();if(O===E&&Fi(O))D=`typeof ${O}`;else if(hd(O)){S=!0;let I=dd(E);if(I){x=I.name;let j="";if(O.startsWith("async "))j="async ";if(O.charCodeAt(j.length)===42)j+="*";D=tl(I.name,j+I.typeParams+O.slice(j.length))}else D=tl(E,O)}else{if(D=Ne(p,t,!1,r+1),D==="unknown"&&cr(O))D=`typeof ${O}`;if(D.includes("=>")||D.includes("function")||D.includes("async"))D=Qa(D)}let H=Ze;Ze=M;let K=p.trim(),me=fd(E);if(me){let I=ud(me.kind,me.name,D);if(I){o.push(`${y}${I}`);continue}}if(!t&&nd(D)&&mo(K))o.push(`${y}/** @defaultValue ${go(K)} */
|
|
126
|
+
${x}: ${D}`);else o.push(`${y}${x}: ${D}`);if(a){let I=il(x);if(K.endsWith("as const"));else if(mo(K))c.push(`${I}: ${K}`);else if(K.startsWith("[")&&po(K))c.push(`${I}: ${ki(K)}`);else if(K.startsWith("{")){if(H)c.push(`${I}: ${H}`)}else if(S)c.push(`${I}: ${co(Qa(D))}`);else if(!K.startsWith("[")&&(K.includes("=>")||K.startsWith("function")||K.startsWith("async"))){let j=ul(K,!1,0,!0);c.push(`${I}: ${co(j)}`)}}}if(a&&c.length>0){let l=r>0?(r-1)/2:0,p=`{ ${c.join(", ")} }`;if(p.length<=80)Ze=p;else{let C=" ".repeat((l+1)*2),E=" ".repeat(l*2);Ze=`{
|
|
127
127
|
${C}${c.join(`,
|
|
128
128
|
${C}`)}
|
|
129
129
|
${E}}`}}let f=o.length>0?`{
|
|
130
130
|
${o.join(`;
|
|
131
131
|
`)}
|
|
132
|
-
}`:"{}";if(s.length===0)return f;let u=s[0];for(let l=1;l<s.length;l++)u=`Omit<${u}, keyof ${s[l]}> & ${s[l]}`;return o.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function Fi(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(!$t(e.charCodeAt(r)))return!1;return!0}function cr(e){let t=e.split(".");return t.length>0&&t.every(Fi)}function
|
|
133
|
-
`).map((f)=>
|
|
134
|
-
`),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(!$t(f)&&!$t(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let n=t.indexOf("(");if(n!==-1){let f=nt(t,n,"(",")");if(f!==-1){let u=t.slice(n,f+1),l=Bt(u);t=t.slice(0,n)+l+t.slice(f+1)}}let i=t.length,o="",s=[],a=!1,c=!1;for(let f=0;f<i;f++){let u=t.charCodeAt(f);if(u===123||u===40)s.push(u);else if(u===125||u===41)s.pop();if(u<=32){if(a=!0,u===10||u===13)c=!0;continue}if(a&&o.length>0){let l=(s.length>0?s[s.length-1]:0)===123;if(c&&l){let p=o.charCodeAt(o.length-1),C=p===59||p===44||p===123||u===125,E=o.length>=2&&o.charCodeAt(o.length-1)===47&&o.charCodeAt(o.length-2)===42;if(!C&&!E)o+="; ";else o+=" "}else o+=" "}a=!1,c=!1,o+=t[f]}return o.trim()}function $t(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Bt(e){let t=e.trim(),r,n=!1;if(t.startsWith("(")&&t.endsWith(")"))r=t.slice(1,-1),n=!0;else r=t;let i=r.trim();if(!i)return n?"()":"";let o=!1;{let E=0;for(let y=0;y<i.length;y++){let x=i.charCodeAt(y);if(x===40||x===60||x===91||x===123)E++;else if(x===41||x===93||x===125||x===62&&i.charCodeAt(y-1)!==61)E--;else if(E===0&&x===61){let S=y>0?i.charCodeAt(y-1):0,M=y+1<i.length?i.charCodeAt(y+1):0;if(S!==61&&S!==33&&S!==60&&S!==62&&M!==61&&M!==62){o=!0;break}}}}if(!o)return t;let s=[],a=[],c=0,f=0,u=!1,l=0;for(let E=0;E<=i.length;E++){if(E===i.length){s.push(i.slice(c));break}let y=i.charCodeAt(E);if(u){if(y===92){E++;continue}if(y===l)u=!1;continue}if(y===47&&E+1<i.length){let x=i.charCodeAt(E+1);if(x===42){E+=2;while(E+1<i.length&&!(i.charCodeAt(E)===42&&i.charCodeAt(E+1)===47))E++;E++;continue}if(x===47){while(E<i.length&&i.charCodeAt(E)!==10)E++;continue}}if(y===39||y===34||y===96){u=!0,l=y;continue}if(y===40||y===60||y===91||y===123)f++;else if(y===41||y===93||y===125||y===62&&i.charCodeAt(E-1)!==61)f--;else if(y===44&&f===0){s.push(i.slice(c,E));let x=",",S=E+1;while(S<i.length&&i.charCodeAt(S)<=32)x+=i[S],S++;a.push(x),c=S}}let p=[];for(let E of s){let y=E.trim();if(!y){p.push(E);continue}if(y.startsWith("//"))continue;let x=
|
|
135
|
-
`),key:e.slice(r).trim()}}function
|
|
136
|
-
`))K=K.slice(6).trimStart(),me="async ";if(K.startsWith("*"))K=K.slice(1).trimStart(),me+="*";n=H+K,r=me+D,a=!1,C=!0,E=!1,i=1}else if(x===123||x===91||x===40){if(i++,r+=D,E&&x===123)E=!1}else if(x===125||x===93||x===41){if(i--,r+=D,x===41&&i===0&&!a&&!C)u=!0;if(C){if(x===41&&i===0&&!E)E=!0;else if(x===125&&i===0)C=!1,E=!1}}else if(x===58&&i===0&&a&&p===0)n=r.trim(),r="",a=!1;else if(x===58&&i===0&&u)l=!0,r+=D;else if(x===60&&l)p++,r+=D;else if(x===60&&a&&i===0)p++,r+=D;else if(x===62&&p>0&&S!==61)p--,r+=D;else if(x===61&&M===62&&l&&p===0)l=!1,u=!1,r+=D;else if(x===44&&i===0&&p===0&&!E){if(n&&r.trim()){let O=r.trim();t.push([n,O])}else if(a&&r.trim())
|
|
137
|
-
${n}`:n,n]);else if(n.startsWith("...")&&n.length>3)e.push(["...",n.slice(3).trim()])}function id(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 nd(e,t,r){let n=r.trim();if(n.charCodeAt(0)!==40)return null;let i=nt(n,0,"(",")");if(i===-1)return null;let o=n.slice(1,i).trim(),s=n.slice(i+1).trimStart();if(!s.startsWith("=>"))return null;let a=s.slice(2).trim();if(e==="get")return`get ${t}(): ${a||"unknown"}`;return`set ${t}(${o})`}function od(e){let t=e;if(t.startsWith("async ")||t.startsWith("async\t"))t=t.slice(5).trimStart();if(t.startsWith("*"))t=t.slice(1).trimStart();if(!t.startsWith("("))return!1;let r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);if(i===40)r++;else if(i===41){if(r--,r===0){let o=t.slice(n+1).trimStart();if(o.startsWith("{"))return!0;if(o.startsWith(":")){let s=wo(o,1);if(s?.kind==="arrow")return!1;if(s?.kind==="body")return!0}return!1}}}return!1}function sd(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let r=0,n=-1;for(let o=t.length-1;o>=0;o--){let s=t.charCodeAt(o);if(s===62){if(o>0&&t.charCodeAt(o-1)===61)continue;r++}else if(s===60){if(r--,r===0){n=o;break}}}if(n===-1)return null;let i=t.slice(0,n).trimEnd();if(!i)return null;return{name:i,typeParams:t.slice(n)}}function Xa(e,t){let r=t.trimStart(),n=!1,i=!1;if(r.startsWith("async ")||r.startsWith("async\t"))n=!0,r=r.slice(5).trimStart();if(r.startsWith("*"))i=!0,r=r.slice(1).trimStart();let o="";if(r.charCodeAt(0)===60){let p=0,C=-1;for(let E=0;E<r.length;E++)if(r.charCodeAt(E)===60)p++;else if(r.charCodeAt(E)===62&&!(E>0&&r.charCodeAt(E-1)===61)){if(p--,p===0){C=E;break}}if(C!==-1)o=r.slice(0,C+1),r=r.slice(C+1).trimStart()}let s=r.indexOf("("),a=nt(r,s,"(",")");if(s===-1||a===-1)return"() => unknown";let c=r.slice(s,a+1),f="unknown",u=r.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let p=u.slice(1),C=wo(p,0);if(C)f=p.slice(0,C.index).trim();else f=p.trim()}if(f==="unknown"&&!i&&u.charCodeAt(0)===123){let p=nt(u,0,"{","}");if(p!==-1){let C=fr(u.slice(1,p),n,c);if(C!=="unknown"&&C!=="Promise<unknown>")f=n&&C.startsWith("Promise<")?C.slice(8,-1):C;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 l=Bt(c);return`${o}${l} => ${f}`}function wo(e,t){let r=0,n=0,i=0,o=0,s=!1,a=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(s){if(f===92)c++;else if(f===a)s=!1;continue}if(f===34||f===39||f===96){s=!0,a=f;continue}if(f===40)r++;else if(f===41&&r>0)r--;else if(f===91)n++;else if(f===93&&n>0)n--;else if(f===60)i++;else if(f===62&&i>0&&e.charCodeAt(c-1)!==61)i--;else if(f===125&&o>0)o--;else if(f===123){let u=r>0||n>0||i>0||o>0,l=e.slice(t,c).trimEnd(),p=l.charCodeAt(l.length-1),C=l.length===0||p===38||p===124||p===40||p===44||p===58||p===61||p===91;if(u||C)o++;else return{index:c,kind:"body"}}else if(f===61&&c+1<e.length&&e.charCodeAt(c+1)===62&&r===0&&n===0&&i===0&&o===0)return{index:c,kind:"arrow"}}return null}function nt(e,t,r,n){let i=0;for(let o=t;o<e.length;o++)if(e[o]===r)i++;else if(e[o]===n){if(n===">"&&o>0&&e[o-1]==="=")continue;if(i--,i===0)return o}return-1}function Di(e){let t=0,r=0,n=!1,i="";for(let o=0;o<e.length-1;o++){let s=e[o],a=e[o+1],c=o>0?e[o-1]:"";if(!n&&(s==='"'||s==="'"||s==="`"))n=!0,i=s;else if(n&&s===i&&c!=="\\")n=!1;if(!n){if(s==="<"){let f=nt(e,o,"<",">");if(f!==-1){o=f;continue}}if(s==="(")t++;else if(s===")")t--;else if(s==="[")r++;else if(s==="]")r--;if(s==="="&&a===">"&&t===0&&r===0)return o}}return-1}function ll(e,t=!1,r=0,n=!0){let i=e.trim();if(i.length>200&&so(i,"=>")>2&&so(i,"<")>5&&!i.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(i.startsWith("async ")&&i.includes("=>")){let s=i.slice(5).trim(),a=Di(s);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=s.substring(0,a).trim(),f=s.substring(a+2).trim(),u=Qa(c),{params:l,returnType:p}=u;if(l=Bt(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let C=p;if(C);else if(f.startsWith("{"))C=fr(f.slice(1,f.endsWith("}")?-1:void 0),!0,l);else C=Ne(f,n,!1,r+1);let E=`${l} => ${p||C.startsWith("Promise<")?C:`Promise<${C}>`}`;return t?`(${E})`:E}if(i.includes("=>")){let s="",a=i;if(i.startsWith("<")){let x=nt(i,0,"<",">");if(x!==-1)s=i.substring(0,x+1),a=i.substring(x+1).trim()}let c=Di(a);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,c).trim(),u=a.substring(c+2).trim(),l=Qa(f),{params:p,returnType:C}=l;if(p=Bt(p),p==="()"||p==="")p="()";else if(!p.startsWith("("))p=`(${p})`;let E="unknown";if(C)E=C;else if(u.startsWith("{"))E=fr(u.slice(1,u.endsWith("}")?-1:void 0),!1,p);else if(Oi(u)||il(u)&&Oi(u.slice(1,-1).trim()))E="JSX.Element";else if(u.includes("=>")){let x=u.trimStart(),S=x.indexOf("("),M=S!==-1?nt(x,S,"(",")"):-1,D=M!==-1?x.indexOf("=>",M):-1;if(S===0&&M!==-1&&D!==-1){let O=x.substring(S+1,M).trim(),H=Bt(O);if(s.includes("T")&&H.includes("T"))E=`(${H}) => T`;else E=`(${H}) => any`}else E="any"}else if(t)E="unknown";else E=Wt(u,rl(p));let y=`${s}${p} => ${E}`;return t?`(${y})`:y}if(i.startsWith("function")){let s=8,a=i.length;while(s<a&&i.charCodeAt(s)<=32)s++;let c=!1;if(s<a&&i.charCodeAt(s)===42){c=!0,s++;while(s<a&&i.charCodeAt(s)<=32)s++}let f="";if(s<a&&i.charCodeAt(s)===60){let p=s,C=1;s++;while(s<a&&C>0){let E=i.charCodeAt(s);if(E===60)C++;else if(E===62&&i.charCodeAt(s-1)!==61)C--;s++}f=i.substring(p,s);while(s<a&&i.charCodeAt(s)<=32)s++}let u=i.indexOf("(",s);if(u!==-1){let p=1,C=u+1;while(C<a&&p>0){let D=i.charCodeAt(C);if(D===40)p++;else if(D===41)p--;C++}let E=i.substring(u+1,C-1).trim(),y=E?Bt(`(${E})`):"()";if(c){let D=i.substring(C).trim(),O=D.indexOf("Generator<");if(O!==-1){let K=O+10,me=D.indexOf(">",K);if(me!==-1){let I=D.substring(K,me),j=`${f}${y} => Generator<${I}>`;return t?`(${j})`:j}}let H=`${f}${y} => Generator<any, any, any>`;return t?`(${H})`:H}let x="unknown",S=i.substring(C).trimStart();if(S.charCodeAt(0)===58){let D=S.slice(1),O=wo(D,0),H=(O?D.slice(0,O.index):D).trim();if(H)x=H}let M=`${f}${y} => ${x}`;return t?`(${M})`:M}let l="(...args: any[]) => unknown";return t?`(${l})`:l}if(i.includes("=>")&&i.includes("(")&&i.includes(")")){if(i.length>100||so(i,"=>")>2){let s="";if(i.charCodeAt(0)===60){let l=nt(i,0,"<",">");if(l!==-1)s=i.substring(0,l+1)}let a=i.indexOf("("),c=a!==-1?nt(i,a,"(",")"):-1,f=a!==-1&&c!==-1?i.substring(a,c+1):"(...args: any[])";f=Bt(f);let u=`${s}${f} => any`;return t?`(${u})`:u}return t?`(${i})`:i}let o="() => unknown";return t?`(${o})`:o}function Qa(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=nt(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 cl(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 Ni(e){let t=-1,r=0;for(let i=0;i<e.length;i++){let o=e.charCodeAt(i);if(o===34||o===39||o===96){i=Mt(e,i,o)-1;continue}if(o===47&&e.charCodeAt(i+1)===47){while(i<e.length&&e.charCodeAt(i)!==10)i++;continue}if(o===47&&e.charCodeAt(i+1)===42){let s=e.indexOf("*/",i+2);i=s===-1?e.length:s+1;continue}if(o===47){let s=i-1;while(s>=0&&e.charCodeAt(s)<=32)s--;if(s<0||"([{:;,=!?&|+*-~>".includes(e[s])){let a=!1;for(i++;i<e.length;i++){let c=e.charCodeAt(i);if(c===92)i++;else if(c===91)a=!0;else if(c===93)a=!1;else if(c===47&&!a)break}continue}}if(o===40||o===91||o===123)r++;else if(o===41||o===93||o===125)r--;else if(r===0&&e.startsWith("satisfies",i)&&lo(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 po=20,Ii=!1,Ze=null;var Eo=()=>{};function Ge(e){return e===Oe||e===ke||e===de||e===Se}function Gt(e){return e>=65&&e<=90||e>=97&&e<=122||e===ld||e===hl||e>127}function Qe(e){return Gt(e)||e>=48&&e<=57}function cd(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(!Gt(n))return!1;t=!1}else if(!Qe(n))return!1}return e.length>0&&!t}function Bi(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===Xe){n+=2;continue}if(n++,i===r)break}return n}function fd(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===U&&e.includes("[")&&e.includes("]:")}function dl(e,t,r=!0){return pl(e,t,r,!0)}function ml(e,t,r=!0){return pl(e,t,r,!1)}function pl(e,t,r,n){let i=e,o=r,s=n,a=i.length,c=[],f=new Map,u=new Set,l=0;if(l<a&&i.charCodeAt(l)===65279)l++;function p(m,h){if(m<h){let d=i.charCodeAt(m),g=i.charCodeAt(h-1);if(d!==Oe&&d!==ke&&d!==de&&d!==Se&&g!==Oe&&g!==ke&&g!==de&&g!==Se)return i.slice(m,h)}while(m<h&&Ge(i.charCodeAt(m)))m++;while(h>m&&Ge(i.charCodeAt(h-1)))h--;return i.slice(m,h)}let C=/[\r\n]/g;function E(m){return C.lastIndex=m,C.exec(i)?.index??a}function y(){if(l>=a)return;let m=i.charCodeAt(l);if(m!==Oe&&m!==ke&&m!==de&&m!==Se&&m!==X)return;while(l<a){let h=i.charCodeAt(l);if(h===Oe||h===ke||h===de||h===Se){l++;continue}if(h===X&&l+1<a){let d=i.charCodeAt(l+1);if(d===X){l=E(l+2);continue}if(d===be){let g=i.indexOf("*/",l+2);l=g===-1?a:g+2;continue}}break}}function x(m){let h=m.length,d=0,g=h;for(let w=0;w<h;w++){let v=m.charCodeAt(w);if(d){if(v===Xe){w++;continue}if(v===d)d=0;continue}if(v===le||v===he||v===Ie){d=v;continue}if(v===X&&w+1<h){let R=m.charCodeAt(w+1);if(R===X){g=w;while(g>0&&(m.charCodeAt(g-1)===Oe||m.charCodeAt(g-1)===ke))g--;return m.slice(0,g)}if(R===be){let P=m.indexOf("*/",w+2);if(P!==-1){m=`${m.slice(0,w)} ${m.slice(P+2)}`,w--;continue}}}}g=h;while(g>0&&(m.charCodeAt(g-1)===Oe||m.charCodeAt(g-1)===ke||m.charCodeAt(g-1)===Se))g--;return g<h?m.slice(0,g):m}function S(m){l++;let h=m===le?"'":'"';while(l<a){let d=i.indexOf(h,l);if(d===-1){l=a;return}let g=0,w=d-1;while(w>=0&&i.charCodeAt(w)===Xe)g++,w--;if(g%2===0){l=d+1;return}l=d+1}}function M(){l++;let m=[];while(l<a){let h=i.charCodeAt(l);if(m.length===0){if(h===Xe){l+=2;continue}if(h===Ie){l++;return}if(h===hl&&l+1<a&&i.charCodeAt(l+1)===U){l+=2,m.push(0);continue}l++;continue}if(h===le||h===he){S(h);continue}if(h===Ie){M();continue}if(h===X&&l+1<a){let d=i.charCodeAt(l+1);if(d===X){l=E(l+2);continue}if(d===be){let g=i.indexOf("*/",l+2);l=g===-1?a:g+2;continue}if(me()){I();continue}l++;continue}if(h===U){m[m.length-1]++,l++;continue}if(h===Q){let d=m[m.length-1];if(d===0){m.pop(),l++;continue}m[m.length-1]=d-1,l++;continue}l++}}let D=!1;function O(){D=!1;let m=i.charCodeAt(l);if(m===le||m===he)return S(m),!0;if(m===Ie)return M(),!0;if(m===X&&l+1<a){let h=i.charCodeAt(l+1);if(h===X)return l=E(l+2),!0;if(h===be){let d=i.indexOf("*/",l+2);return D=E(l+2)<(d===-1?a:d),l=d===-1?a:d+2,!0}if(me())return I(),!0}return!1}function H(m){let h=m;for(;;){while(h>=0&&(i.charCodeAt(h)===Oe||i.charCodeAt(h)===ke||i.charCodeAt(h)===de||i.charCodeAt(h)===Se))h--;if(h<0)return-1;if(i.charCodeAt(h)===X&&h>0&&i.charCodeAt(h-1)===be){let w=i.lastIndexOf("/*",h-2);if(w===-1)return-1;h=w-1;continue}let d=i.lastIndexOf(`
|
|
138
|
-
`,h)+1,g=K(d,h);if(g!==-1){h=g-1;continue}return h}}function K(m,h){let d=0;for(let g=m;g<=h;g++){let w=i.charCodeAt(g);if(d){if(w===Xe){g++;continue}if(w===d)d=0;continue}if(w===le||w===he||w===Ie){d=w;continue}if(w===X&&g+1<=h&&i.charCodeAt(g+1)===X)return g}return-1}function me(){let m=H(l-1);if(m<0)return!0;let h=i.charCodeAt(m);if(h===$e||h===se||h===Ee||h===33||h===38||h===124||h===Li||h===ft||h===ut||h===re||h===U||h===Q||h===94||h===126||h===43||h===45||h===be||h===37||h===ve||h===ue)return!0;if(Qe(h)){let d=m;while(d>=0&&Qe(i.charCodeAt(d)))d--;let g=i.slice(d+1,m+1);if(g==="return"||g==="typeof"||g==="void"||g==="delete"||g==="throw"||g==="new"||g==="in"||g==="of"||g==="case"||g==="instanceof"||g==="yield"||g==="await")return!0}return!1}function I(){l++;let m=!1;while(l<a){let h=i.charCodeAt(l);if(h===Xe){l+=2;continue}if(m){if(h===Pe)m=!1;l++;continue}if(h===Ee){m=!0,l++;continue}if(h===X){l++;break}if(h===de||h===Se)break;l++}while(l<a&&Qe(i.charCodeAt(l)))l++}function j(){let m=l;while(l<a&&Qe(i.charCodeAt(l)))l++;return i.slice(m,l)}function T(m){if(l+m.length>a)return!1;for(let h=0;h<m.length;h++)if(i.charCodeAt(l+h)!==m.charCodeAt(h))return!1;if(l+m.length<a&&Qe(i.charCodeAt(l+m.length)))return!1;return!0}function Re(m){let h=l+m;while(h<a){let d=i.charCodeAt(h);if(d===Oe||d===ke||d===de||d===Se){h++;continue}return d!==gt&&d!==$e}return!1}function V(){if(!D)return!1;let m=l;y();let h=l>=a||pe()||i.charCodeAt(l)===Q;return l=m,h}function pe(){if(l>=a)return!1;switch(i.charCodeAt(l)){case 101:return T("export")||T("enum");case 105:return T("import")||T("interface");case 102:return T("function");case 99:return T("class")||T("const");case 116:return T("type");case 108:return T("let");case 118:return T("var");case 100:return T("declare")||T("default");case 109:return T("module");case 110:return T("namespace");case 97:return T("abstract")||T("async");default:return!1}}function ee(){let m=i.charCodeAt(l);if(m!==de&&m!==Se)return!1;let h=l;if(l++,m===Se&&l<a&&i.charCodeAt(l)===de)l++;while(l<a){let g=i.charCodeAt(l);if(g===Oe||g===ke||g===Se||g===de){l++;continue}if(g===X&&l+1<a){let w=i.charCodeAt(l+1);if(w===X){l=E(l+2);continue}if(w===be){let v=i.indexOf("*/",l+2);l=v===-1?a:v+2;continue}}break}let d=l>=a||pe()||i.charCodeAt(l)===Q;return l=h,d}function ie(m){let h=m-1;while(h>=0){let b=i.charCodeAt(h);if(b===Oe||b===ke||b===Se||b===de){h--;continue}break}if(h<0)return!0;let d=i[h];if("+-*/%=<>&|^!~?:,.([{".includes(d))return!0;let g=h;while(g>0&&i.charCodeAt(g-1)!==de)g--;let w=i.slice(g,h+1),v=w.lastIndexOf("<");if(v!==-1&&/^<[A-Za-z]/.test(w.slice(v))&&!w.slice(v).includes(">"))return!0;let R=h;while(R>=0&&/[a-z]/i.test(i[R]))R--;let P=i.slice(R+1,h+1);return["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(P)}function ne(){let m=i.charCodeAt(l);if(m!==de&&m!==Se)return!1;if(ie(l))return!1;let h=l;l++;while(l<a){let v=i.charCodeAt(l);if(v===Oe||v===ke||v===Se||v===de){l++;continue}if(v===X&&l+1<a){let R=i.charCodeAt(l+1);if(R===X){l=E(l+2);continue}if(R===be){let P=i.indexOf("*/",l+2);l=P===-1?a:P+2;continue}}break}let d=l<a?i[l]:"",g=i.slice(l,l+2),w=d==="."||d==="?"||d===":"||d===")"||d==="]"||d==="}"||d===","||d==="+"||d==="-"||d==="*"||d==="/"||d==="%"||d==="<"||d===">"||d==="="||d==="&"||d==="|"||d==="^"||d==="`"||g==="=>"||T("as")||T("satisfies")||T("instanceof")||T("in");return l=h,!w}function ce(){let m=i.charCodeAt(l);if(m!==de&&m!==Se)return!1;if(ie(l))return!1;let h=l;l++;while(l<a){let w=i.charCodeAt(l);if(w===Oe||w===ke||w===Se||w===de){l++;continue}if(w===X&&l+1<a){let v=i.charCodeAt(l+1);if(v===X){l=E(l+2);continue}if(v===be){let R=i.indexOf("*/",l+2);l=R===-1?a:R+2;continue}}break}let d=l<a?i[l]:"",g=d==="|"||d==="&"||d==="["||d==="."||d==="?"||d===":"||d===">"||d===")"||d===","||T("extends");return l=h,!g}function N(){let m=i.charCodeAt(l);if(m!==de&&m!==Se)return!1;let h=l;if(l++,m===Se&&l<a&&i.charCodeAt(l)===de)l++;while(l<a){let g=i.charCodeAt(l);if(g===Oe||g===ke||g===Se||g===de){l++;continue}if(g===X&&l+1<a&&i.charCodeAt(l+1)===X){l=E(l+2);continue}break}if(l>=a)return l=h,!0;let d=i.charCodeAt(l);if(d===124||d===38||d===gt||d===Li||d===ft)return l=h,!1;if(T("extends")||T("keyof")||T("typeof")||T("infer")||T("is")||T("as")||T("in"))return l=h,!1;return l=h,!0}let z=/[{}'"`\/]/g,J=/[()'"`\/]/g,te=/[[\]'"`\/]/g,Z=/[<>'"`\/]/g;function Y(m,h){let d=1;l++;let g=m===U?z:m===se?J:m===Ee?te:Z;g.lastIndex=l;let w;while((w=g.exec(i))!==null){let v=w.index,R=i.charCodeAt(v);if(R===le||R===he){l=v,S(R),g.lastIndex=l;continue}if(R===Ie){l=v,M(),g.lastIndex=l;continue}if(R===X){if(l=v,O()){g.lastIndex=l;continue}g.lastIndex=v+1;continue}if(R===m)d++;else if(R===h){if(h===ue&&v>0&&i.charCodeAt(v-1)===$e){g.lastIndex=v+1;continue}if(d--,d===0)return l=v+1,l}g.lastIndex=v+1}return l=a,l}function oe(){return l>0&&i.charCodeAt(l-1)===$e}function Fe(){return l+1<a&&i.charCodeAt(l+1)===ue}let Ve=/[<{};'"`\/\n\r()[\]]/g;function Me(m=!1){let h=0,d=0,g=0,w=0,v=i.charCodeAt(l)===U;Ve.lastIndex=l;let R;while((R=Ve.exec(i))!==null){let P=R.index,b=i.charCodeAt(P);if(b===le||b===he){l=P,S(b),Ve.lastIndex=l;continue}if(b===Ie){l=P,M(),Ve.lastIndex=l;continue}if(b===X){if(P>0&&i.charCodeAt(P-1)===ve){Ve.lastIndex=P+1;continue}if(l=P,O()){if(h===0&&d===0&&g===0&&w===0&&V())return;Ve.lastIndex=l;continue}Ve.lastIndex=P+1;continue}if(b===ve){let A=
|
|
139
|
-
`,l),h=m===-1?a:m,d=i.indexOf(";",l);if(d!==-1&&d<h){let g=d-1;while(g>=l&&(i.charCodeAt(g)===Oe||i.charCodeAt(g)===ke))g--;let w=i.charCodeAt(l),v=i.charCodeAt(g);if(w===U&&v===Q||w===Ee&&v===Pe||w===le&&v===le||w===he&&v===he||w===Ie&&v===Ie){l=d+1;return}}Me()}function
|
|
140
|
-
`));continue}break}if(d.length===0)return;return d.reverse(),d}function
|
|
141
|
-
`),g=[],w=[],v=[],R=!1,P=1/0;for(let k=0;k<d.length;k++){let L=d[k];if(h){if(R){if(L.includes("*/"))R=!1;continue}let G=L.trim();if(G.length===0)continue;let W=G.charCodeAt(0);if(W===X){let He=G.charCodeAt(1);if(He===X)continue;if(He===be){if(!G.includes("*/"))R=!0;continue}}if(W===be)continue;let F=x(L);if(F.charCodeAt(F.length-1)===re)F=F.slice(0,-1);F=
|
|
132
|
+
}`:"{}";if(s.length===0)return f;let u=s[0];for(let l=1;l<s.length;l++)u=`Omit<${u}, keyof ${s[l]}> & ${s[l]}`;return o.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function Fi(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(!$t(e.charCodeAt(r)))return!1;return!0}function cr(e){let t=e.split(".");return t.length>0&&t.every(Fi)}function sd(e){let t=!1,r="";for(let n=0;n<e.length;n++){let i=e[n];if(t){if(i==="\\")n++;else if(i===r)t=!1;continue}if(i==='"'||i==="'"||i==="`"){t=!0,r=i;continue}if(i==="(")return n;if(i==="<"){let o=nt(e,n,"<",">");if(o!==-1)n=o}}return-1}function ll(e){if(e.length<3||!e.endsWith(")"))return null;let t=sd(e);if(t===-1||nt(e,t,"(",")")!==e.length-1)return null;let r=e.slice(0,t).trim(),n=!1;if(r.endsWith("?."))n=!0,r=r.slice(0,-2).trim();let i=r,o=!1,s=r.indexOf("<");if(s!==-1){if(nt(r,s,"<",">")!==r.length-1)return null;i=r.slice(0,s).trim(),o=!0}if(!cr(i))return null;let a=e.slice(t+1,-1).trim(),c=Di(a)!==-1||a.startsWith("function")||a.startsWith("async function"),f=cr(a),u=!c&&a.endsWith(")")&&ll(a)!==null;if(!o&&!n&&!c&&!f&&!u)return null;let l=`ReturnType<typeof ${r}>`;return n?`${l} | undefined`:l}function Qa(e){let t=e.split(`
|
|
133
|
+
`).map((f)=>cl(f)).join(`
|
|
134
|
+
`),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(!$t(f)&&!$t(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let n=t.indexOf("(");if(n!==-1){let f=nt(t,n,"(",")");if(f!==-1){let u=t.slice(n,f+1),l=Bt(u);t=t.slice(0,n)+l+t.slice(f+1)}}let i=t.length,o="",s=[],a=!1,c=!1;for(let f=0;f<i;f++){let u=t.charCodeAt(f);if(u===123||u===40)s.push(u);else if(u===125||u===41)s.pop();if(u<=32){if(a=!0,u===10||u===13)c=!0;continue}if(a&&o.length>0){let l=(s.length>0?s[s.length-1]:0)===123;if(c&&l){let p=o.charCodeAt(o.length-1),C=p===59||p===44||p===123||u===125,E=o.length>=2&&o.charCodeAt(o.length-1)===47&&o.charCodeAt(o.length-2)===42;if(!C&&!E)o+="; ";else o+=" "}else o+=" "}a=!1,c=!1,o+=t[f]}return o.trim()}function $t(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Bt(e){let t=e.trim(),r,n=!1;if(t.startsWith("(")&&t.endsWith(")"))r=t.slice(1,-1),n=!0;else r=t;let i=r.trim();if(!i)return n?"()":"";let o=!1;{let E=0;for(let y=0;y<i.length;y++){let x=i.charCodeAt(y);if(x===40||x===60||x===91||x===123)E++;else if(x===41||x===93||x===125||x===62&&i.charCodeAt(y-1)!==61)E--;else if(E===0&&x===61){let S=y>0?i.charCodeAt(y-1):0,M=y+1<i.length?i.charCodeAt(y+1):0;if(S!==61&&S!==33&&S!==60&&S!==62&&M!==61&&M!==62){o=!0;break}}}}if(!o)return t;let s=[],a=[],c=0,f=0,u=!1,l=0;for(let E=0;E<=i.length;E++){if(E===i.length){s.push(i.slice(c));break}let y=i.charCodeAt(E);if(u){if(y===92){E++;continue}if(y===l)u=!1;continue}if(y===47&&E+1<i.length){let x=i.charCodeAt(E+1);if(x===42){E+=2;while(E+1<i.length&&!(i.charCodeAt(E)===42&&i.charCodeAt(E+1)===47))E++;E++;continue}if(x===47){while(E<i.length&&i.charCodeAt(E)!==10)E++;continue}}if(y===39||y===34||y===96){u=!0,l=y;continue}if(y===40||y===60||y===91||y===123)f++;else if(y===41||y===93||y===125||y===62&&i.charCodeAt(E-1)!==61)f--;else if(y===44&&f===0){s.push(i.slice(c,E));let x=",",S=E+1;while(S<i.length&&i.charCodeAt(S)<=32)x+=i[S],S++;a.push(x),c=S}}let p=[];for(let E of s){let y=E.trim();if(!y){p.push(E);continue}if(y.startsWith("//"))continue;let x=cl(y),S=E.slice(0,E.length-E.trimStart().length);p.push(S+ad(x))}let C=p[0]||"";for(let E=1;E<p.length;E++)C+=(a[E-1]||", ")+p[E];return n?`(${C})`:C}function cl(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 ad(e){if(e.startsWith("..."))return e;let t=-1,r=-1,n=0,i=!1,o=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(i){if(c===92){a++;continue}if(c===o)i=!1;continue}if(c===47&&a+1<e.length){let f=e.charCodeAt(a+1);if(f===42){a+=2;while(a+1<e.length&&!(e.charCodeAt(a)===42&&e.charCodeAt(a+1)===47))a++;a++;continue}if(f===47){while(a<e.length&&e.charCodeAt(a)!==10)a++;continue}}if(c===39||c===34||c===96){i=!0,o=c;continue}if(c===40||c===60||c===91||c===123)n++;else if(c===41||c===93||c===125||c===62&&e.charCodeAt(a-1)!==61)n--;else if(n===0){if(c===58&&t===-1)t=a;else if(c===61&&r===-1&&(a===0||e.charCodeAt(a-1)!==61)&&(a+1>=e.length||e.charCodeAt(a+1)!==61&&e.charCodeAt(a+1)!==62))r=a}}let s=r!==-1;if(t!==-1&&(r===-1||t<r)){let a=e.slice(0,t).trim(),c=r!==-1?e.slice(t+1,r).trim():e.slice(t+1).trim(),f=s&&!a.endsWith("?")?"?":"";return`${a}${f}: ${c}`}else if(r!==-1){let a=e.slice(0,r).trim(),c=!a.endsWith("?")?"?":"",f=e.slice(r+1).trim(),u="unknown";if(f==="true"||f==="false")u="boolean";else if(/^-?\d+(\.\d+)?$/.test(f))u="number";else if(f.startsWith("'")&&f.endsWith("'")||f.startsWith('"')&&f.endsWith('"'))u="string";else if(f.startsWith("["))u="unknown[]";else if(f.startsWith("{"))u="Record<string, unknown>";return`${a}${c}: ${u}`}return e}function ld(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 fl(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(`
|
|
135
|
+
`),key:e.slice(r).trim()}}function cd(e){let t=[],r="",n="",i=0,o=!1,s="",a=!0,c=!1,f=0,u=!1,l=!1,p=0,C=!1,E=!1;for(let y=0;y<e.length;y++){let x=e.charCodeAt(y),S=y>0?e.charCodeAt(y-1):0,M=y<e.length-1?e.charCodeAt(y+1):0;if(!o&&!c&&x===47&&M===47){r=r.replace(/[ \t]+$/,""),y+=2;while(y<e.length&&e.charCodeAt(y)!==10)y++;y--;continue}if(!o&&!c&&x===47&&M===42){c=!0,f=1,r+="/*",y++;continue}else if(c&&x===42&&M===47){if(f--,r+="*/",y++,f===0)c=!1;continue}else if(c&&x===47&&M===42){f++,r+="/*",y++;continue}let D=e[y];if(!o&&!c&&(x===34||x===39||x===96))o=!0,s=D,r+=D;else if(o&&D===s&&S!==92)o=!1,r+=D;else if(!o&&!c)if(x===40&&i===0&&a&&p===0){n=r.trim();let O=ld(n),H=O>0?n.slice(0,O):"",K=n.slice(O),me="";if(K.startsWith("async ")||K.startsWith("async\t")||K.startsWith(`async
|
|
136
|
+
`))K=K.slice(6).trimStart(),me="async ";if(K.startsWith("*"))K=K.slice(1).trimStart(),me+="*";n=H+K,r=me+D,a=!1,C=!0,E=!1,i=1}else if(x===123||x===91||x===40){if(i++,r+=D,E&&x===123)E=!1}else if(x===125||x===93||x===41){if(i--,r+=D,x===41&&i===0&&!a&&!C)u=!0;if(C){if(x===41&&i===0&&!E)E=!0;else if(x===125&&i===0)C=!1,E=!1}}else if(x===58&&i===0&&a&&p===0)n=r.trim(),r="",a=!1;else if(x===58&&i===0&&u)l=!0,r+=D;else if(x===60&&l)p++,r+=D;else if(x===60&&a&&i===0)p++,r+=D;else if(x===62&&p>0&&S!==61)p--,r+=D;else if(x===61&&M===62&&l&&p===0)l=!1,u=!1,r+=D;else if(x===44&&i===0&&p===0&&!E){if(n&&r.trim()){let O=r.trim();t.push([n,O])}else if(a&&r.trim())el(t,r.trim());r="",n="",a=!0,u=!1,l=!1,p=0}else r+=D;else r+=D}if(n&&r.trim()){let y=r.trim();t.push([n,y])}else if(a&&r.trim())el(t,r.trim());return t}function el(e,t){let{comments:r,key:n}=fl(t);if(Fi(n))e.push([r?`${r}
|
|
137
|
+
${n}`:n,n]);else if(n.startsWith("...")&&n.length>3)e.push(["...",n.slice(3).trim()])}function fd(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 ud(e,t,r){let n=r.trim();if(n.charCodeAt(0)!==40)return null;let i=nt(n,0,"(",")");if(i===-1)return null;let o=n.slice(1,i).trim(),s=n.slice(i+1).trimStart();if(!s.startsWith("=>"))return null;let a=s.slice(2).trim();if(e==="get")return`get ${t}(): ${a||"unknown"}`;return`set ${t}(${o})`}function hd(e){let t=e;if(t.startsWith("async ")||t.startsWith("async\t"))t=t.slice(5).trimStart();if(t.startsWith("*"))t=t.slice(1).trimStart();if(!t.startsWith("("))return!1;let r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);if(i===40)r++;else if(i===41){if(r--,r===0){let o=t.slice(n+1).trimStart();if(o.startsWith("{"))return!0;if(o.startsWith(":")){let s=vo(o,1);if(s?.kind==="arrow")return!1;if(s?.kind==="body")return!0}return!1}}}return!1}function dd(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let r=0,n=-1;for(let o=t.length-1;o>=0;o--){let s=t.charCodeAt(o);if(s===62){if(o>0&&t.charCodeAt(o-1)===61)continue;r++}else if(s===60){if(r--,r===0){n=o;break}}}if(n===-1)return null;let i=t.slice(0,n).trimEnd();if(!i)return null;return{name:i,typeParams:t.slice(n)}}function tl(e,t){let r=t.trimStart(),n=!1,i=!1;if(r.startsWith("async ")||r.startsWith("async\t"))n=!0,r=r.slice(5).trimStart();if(r.startsWith("*"))i=!0,r=r.slice(1).trimStart();let o="";if(r.charCodeAt(0)===60){let p=0,C=-1;for(let E=0;E<r.length;E++)if(r.charCodeAt(E)===60)p++;else if(r.charCodeAt(E)===62&&!(E>0&&r.charCodeAt(E-1)===61)){if(p--,p===0){C=E;break}}if(C!==-1)o=r.slice(0,C+1),r=r.slice(C+1).trimStart()}let s=r.indexOf("("),a=nt(r,s,"(",")");if(s===-1||a===-1)return"() => unknown";let c=r.slice(s,a+1),f="unknown",u=r.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let p=u.slice(1),C=vo(p,0);if(C)f=p.slice(0,C.index).trim();else f=p.trim()}if(f==="unknown"&&!i&&u.charCodeAt(0)===123){let p=nt(u,0,"{","}");if(p!==-1){let C=fr(u.slice(1,p),n,c);if(C!=="unknown"&&C!=="Promise<unknown>")f=n&&C.startsWith("Promise<")?C.slice(8,-1):C;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 l=Bt(c);return`${o}${l} => ${f}`}function vo(e,t){let r=0,n=0,i=0,o=0,s=!1,a=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(s){if(f===92)c++;else if(f===a)s=!1;continue}if(f===34||f===39||f===96){s=!0,a=f;continue}if(f===40)r++;else if(f===41&&r>0)r--;else if(f===91)n++;else if(f===93&&n>0)n--;else if(f===60)i++;else if(f===62&&i>0&&e.charCodeAt(c-1)!==61)i--;else if(f===125&&o>0)o--;else if(f===123){let u=r>0||n>0||i>0||o>0,l=e.slice(t,c).trimEnd(),p=l.charCodeAt(l.length-1),C=l.length===0||p===38||p===124||p===40||p===44||p===58||p===61||p===91;if(u||C)o++;else return{index:c,kind:"body"}}else if(f===61&&c+1<e.length&&e.charCodeAt(c+1)===62&&r===0&&n===0&&i===0&&o===0)return{index:c,kind:"arrow"}}return null}function nt(e,t,r,n){let i=0;for(let o=t;o<e.length;o++)if(e[o]===r)i++;else if(e[o]===n){if(n===">"&&o>0&&e[o-1]==="=")continue;if(i--,i===0)return o}return-1}function Di(e){let t=0,r=0,n=!1,i="";for(let o=0;o<e.length-1;o++){let s=e[o],a=e[o+1],c=o>0?e[o-1]:"";if(!n&&(s==='"'||s==="'"||s==="`"))n=!0,i=s;else if(n&&s===i&&c!=="\\")n=!1;if(!n){if(s==="<"){let f=nt(e,o,"<",">");if(f!==-1){o=f;continue}}if(s==="(")t++;else if(s===")")t--;else if(s==="[")r++;else if(s==="]")r--;if(s==="="&&a===">"&&t===0&&r===0)return o}}return-1}function ul(e,t=!1,r=0,n=!0){let i=e.trim();if(i.length>200&&lo(i,"=>")>2&&lo(i,"<")>5&&!i.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(i.startsWith("async ")&&i.includes("=>")){let s=i.slice(5).trim(),a=Di(s);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=s.substring(0,a).trim(),f=s.substring(a+2).trim(),u=rl(c),{params:l,returnType:p}=u;if(l=Bt(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let C=p;if(C);else if(f.startsWith("{"))C=fr(f.slice(1,f.endsWith("}")?-1:void 0),!0,l);else C=Ne(f,n,!1,r+1);let E=`${l} => ${p||C.startsWith("Promise<")?C:`Promise<${C}>`}`;return t?`(${E})`:E}if(i.includes("=>")){let s="",a=i;if(i.startsWith("<")){let x=nt(i,0,"<",">");if(x!==-1)s=i.substring(0,x+1),a=i.substring(x+1).trim()}let c=Di(a);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,c).trim(),u=a.substring(c+2).trim(),l=rl(f),{params:p,returnType:C}=l;if(p=Bt(p),p==="()"||p==="")p="()";else if(!p.startsWith("("))p=`(${p})`;let E="unknown";if(C)E=C;else if(u.startsWith("{"))E=fr(u.slice(1,u.endsWith("}")?-1:void 0),!1,p);else if(Oi(u)||sl(u)&&Oi(u.slice(1,-1).trim()))E="JSX.Element";else if(u.includes("=>")){let x=u.trimStart(),S=x.indexOf("("),M=S!==-1?nt(x,S,"(",")"):-1,D=M!==-1?x.indexOf("=>",M):-1;if(S===0&&M!==-1&&D!==-1){let O=x.substring(S+1,M).trim(),H=Bt(O);if(s.includes("T")&&H.includes("T"))E=`(${H}) => T`;else E=`(${H}) => any`}else E="any"}else if(t)E="unknown";else E=Wt(u,ol(p));let y=`${s}${p} => ${E}`;return t?`(${y})`:y}if(i.startsWith("function")){let s=8,a=i.length;while(s<a&&i.charCodeAt(s)<=32)s++;let c=!1;if(s<a&&i.charCodeAt(s)===42){c=!0,s++;while(s<a&&i.charCodeAt(s)<=32)s++}let f="";if(s<a&&i.charCodeAt(s)===60){let p=s,C=1;s++;while(s<a&&C>0){let E=i.charCodeAt(s);if(E===60)C++;else if(E===62&&i.charCodeAt(s-1)!==61)C--;s++}f=i.substring(p,s);while(s<a&&i.charCodeAt(s)<=32)s++}let u=i.indexOf("(",s);if(u!==-1){let p=1,C=u+1;while(C<a&&p>0){let D=i.charCodeAt(C);if(D===40)p++;else if(D===41)p--;C++}let E=i.substring(u+1,C-1).trim(),y=E?Bt(`(${E})`):"()";if(c){let D=i.substring(C).trim(),O=D.indexOf("Generator<");if(O!==-1){let K=O+10,me=D.indexOf(">",K);if(me!==-1){let I=D.substring(K,me),j=`${f}${y} => Generator<${I}>`;return t?`(${j})`:j}}let H=`${f}${y} => Generator<any, any, any>`;return t?`(${H})`:H}let x="unknown",S=i.substring(C).trimStart();if(S.charCodeAt(0)===58){let D=S.slice(1),O=vo(D,0),H=(O?D.slice(0,O.index):D).trim();if(H)x=H}let M=`${f}${y} => ${x}`;return t?`(${M})`:M}let l="(...args: any[]) => unknown";return t?`(${l})`:l}if(i.includes("=>")&&i.includes("(")&&i.includes(")")){if(i.length>100||lo(i,"=>")>2){let s="";if(i.charCodeAt(0)===60){let l=nt(i,0,"<",">");if(l!==-1)s=i.substring(0,l+1)}let a=i.indexOf("("),c=a!==-1?nt(i,a,"(",")"):-1,f=a!==-1&&c!==-1?i.substring(a,c+1):"(...args: any[])";f=Bt(f);let u=`${s}${f} => any`;return t?`(${u})`:u}return t?`(${i})`:i}let o="() => unknown";return t?`(${o})`:o}function rl(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=nt(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 hl(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 Ni(e){let t=-1,r=0;for(let i=0;i<e.length;i++){let o=e.charCodeAt(i);if(o===34||o===39||o===96){i=Mt(e,i,o)-1;continue}if(o===47&&e.charCodeAt(i+1)===47){while(i<e.length&&e.charCodeAt(i)!==10)i++;continue}if(o===47&&e.charCodeAt(i+1)===42){let s=e.indexOf("*/",i+2);i=s===-1?e.length:s+1;continue}if(o===47){let s=i-1;while(s>=0&&e.charCodeAt(s)<=32)s--;if(s<0||"([{:;,=!?&|+*-~>".includes(e[s])){let a=!1;for(i++;i<e.length;i++){let c=e.charCodeAt(i);if(c===92)i++;else if(c===91)a=!0;else if(c===93)a=!1;else if(c===47&&!a)break}continue}}if(o===40||o===91||o===123)r++;else if(o===41||o===93||o===125)r--;else if(r===0&&e.startsWith("satisfies",i)&&fo(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 yo=20,Ii=!1,Ze=null;var bo=()=>{};function Ge(e){return e===Oe||e===ke||e===de||e===Se}function Gt(e){return e>=65&&e<=90||e>=97&&e<=122||e===pd||e===pl||e>127}function Qe(e){return Gt(e)||e>=48&&e<=57}function gd(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(!Gt(n))return!1;t=!1}else if(!Qe(n))return!1}return e.length>0&&!t}function Bi(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===Xe){n+=2;continue}if(n++,i===r)break}return n}function yd(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===U&&e.includes("[")&&e.includes("]:")}function gl(e,t,r=!0){return Cl(e,t,r,!0)}function yl(e,t,r=!0){return Cl(e,t,r,!1)}function Cl(e,t,r,n){let i=e,o=r,s=n,a=i.length,c=[],f=new Map,u=new Set,l=0;if(l<a&&i.charCodeAt(l)===65279)l++;function p(m,h){if(m<h){let d=i.charCodeAt(m),g=i.charCodeAt(h-1);if(d!==Oe&&d!==ke&&d!==de&&d!==Se&&g!==Oe&&g!==ke&&g!==de&&g!==Se)return i.slice(m,h)}while(m<h&&Ge(i.charCodeAt(m)))m++;while(h>m&&Ge(i.charCodeAt(h-1)))h--;return i.slice(m,h)}let C=/[\r\n]/g;function E(m){return C.lastIndex=m,C.exec(i)?.index??a}function y(){if(l>=a)return;let m=i.charCodeAt(l);if(m!==Oe&&m!==ke&&m!==de&&m!==Se&&m!==X)return;while(l<a){let h=i.charCodeAt(l);if(h===Oe||h===ke||h===de||h===Se){l++;continue}if(h===X&&l+1<a){let d=i.charCodeAt(l+1);if(d===X){l=E(l+2);continue}if(d===be){let g=i.indexOf("*/",l+2);l=g===-1?a:g+2;continue}}break}}function x(m){let h=m.length,d=0,g=h;for(let w=0;w<h;w++){let v=m.charCodeAt(w);if(d){if(v===Xe){w++;continue}if(v===d)d=0;continue}if(v===le||v===he||v===Ie){d=v;continue}if(v===X&&w+1<h){let R=m.charCodeAt(w+1);if(R===X){g=w;while(g>0&&(m.charCodeAt(g-1)===Oe||m.charCodeAt(g-1)===ke))g--;return m.slice(0,g)}if(R===be){let P=m.indexOf("*/",w+2);if(P!==-1){m=`${m.slice(0,w)} ${m.slice(P+2)}`,w--;continue}}}}g=h;while(g>0&&(m.charCodeAt(g-1)===Oe||m.charCodeAt(g-1)===ke||m.charCodeAt(g-1)===Se))g--;return g<h?m.slice(0,g):m}function S(m){l++;let h=m===le?"'":'"';while(l<a){let d=i.indexOf(h,l);if(d===-1){l=a;return}let g=0,w=d-1;while(w>=0&&i.charCodeAt(w)===Xe)g++,w--;if(g%2===0){l=d+1;return}l=d+1}}function M(){l++;let m=[];while(l<a){let h=i.charCodeAt(l);if(m.length===0){if(h===Xe){l+=2;continue}if(h===Ie){l++;return}if(h===pl&&l+1<a&&i.charCodeAt(l+1)===U){l+=2,m.push(0);continue}l++;continue}if(h===le||h===he){S(h);continue}if(h===Ie){M();continue}if(h===X&&l+1<a){let d=i.charCodeAt(l+1);if(d===X){l=E(l+2);continue}if(d===be){let g=i.indexOf("*/",l+2);l=g===-1?a:g+2;continue}if(me()){I();continue}l++;continue}if(h===U){m[m.length-1]++,l++;continue}if(h===Q){let d=m[m.length-1];if(d===0){m.pop(),l++;continue}m[m.length-1]=d-1,l++;continue}l++}}let D=!1;function O(){D=!1;let m=i.charCodeAt(l);if(m===le||m===he)return S(m),!0;if(m===Ie)return M(),!0;if(m===X&&l+1<a){let h=i.charCodeAt(l+1);if(h===X)return l=E(l+2),!0;if(h===be){let d=i.indexOf("*/",l+2);return D=E(l+2)<(d===-1?a:d),l=d===-1?a:d+2,!0}if(me())return I(),!0}return!1}function H(m){let h=m;for(;;){while(h>=0&&(i.charCodeAt(h)===Oe||i.charCodeAt(h)===ke||i.charCodeAt(h)===de||i.charCodeAt(h)===Se))h--;if(h<0)return-1;if(i.charCodeAt(h)===X&&h>0&&i.charCodeAt(h-1)===be){let w=i.lastIndexOf("/*",h-2);if(w===-1)return-1;h=w-1;continue}let d=i.lastIndexOf(`
|
|
138
|
+
`,h)+1,g=K(d,h);if(g!==-1){h=g-1;continue}return h}}function K(m,h){let d=0;for(let g=m;g<=h;g++){let w=i.charCodeAt(g);if(d){if(w===Xe){g++;continue}if(w===d)d=0;continue}if(w===le||w===he||w===Ie){d=w;continue}if(w===X&&g+1<=h&&i.charCodeAt(g+1)===X)return g}return-1}function me(){let m=H(l-1);if(m<0)return!0;let h=i.charCodeAt(m);if(h===$e||h===se||h===Ee||h===33||h===38||h===124||h===Li||h===ft||h===ut||h===re||h===U||h===Q||h===94||h===126||h===43||h===45||h===be||h===37||h===ve||h===ue)return!0;if(Qe(h)){let d=m;while(d>=0&&Qe(i.charCodeAt(d)))d--;let g=i.slice(d+1,m+1);if(g==="return"||g==="typeof"||g==="void"||g==="delete"||g==="throw"||g==="new"||g==="in"||g==="of"||g==="case"||g==="instanceof"||g==="yield"||g==="await")return!0}return!1}function I(){l++;let m=!1;while(l<a){let h=i.charCodeAt(l);if(h===Xe){l+=2;continue}if(m){if(h===Pe)m=!1;l++;continue}if(h===Ee){m=!0,l++;continue}if(h===X){l++;break}if(h===de||h===Se)break;l++}while(l<a&&Qe(i.charCodeAt(l)))l++}function j(){let m=l;while(l<a&&Qe(i.charCodeAt(l)))l++;return i.slice(m,l)}function T(m){if(l+m.length>a)return!1;for(let h=0;h<m.length;h++)if(i.charCodeAt(l+h)!==m.charCodeAt(h))return!1;if(l+m.length<a&&Qe(i.charCodeAt(l+m.length)))return!1;return!0}function Re(m){let h=l+m;while(h<a){let d=i.charCodeAt(h);if(d===Oe||d===ke||d===de||d===Se){h++;continue}return d!==gt&&d!==$e}return!1}function V(){if(!D)return!1;let m=l;y();let h=l>=a||pe()||i.charCodeAt(l)===Q;return l=m,h}function pe(){if(l>=a)return!1;switch(i.charCodeAt(l)){case 101:return T("export")||T("enum");case 105:return T("import")||T("interface");case 102:return T("function");case 99:return T("class")||T("const");case 116:return T("type");case 108:return T("let");case 118:return T("var");case 100:return T("declare")||T("default");case 109:return T("module");case 110:return T("namespace");case 97:return T("abstract")||T("async");default:return!1}}function ee(){let m=i.charCodeAt(l);if(m!==de&&m!==Se)return!1;let h=l;if(l++,m===Se&&l<a&&i.charCodeAt(l)===de)l++;while(l<a){let g=i.charCodeAt(l);if(g===Oe||g===ke||g===Se||g===de){l++;continue}if(g===X&&l+1<a){let w=i.charCodeAt(l+1);if(w===X){l=E(l+2);continue}if(w===be){let v=i.indexOf("*/",l+2);l=v===-1?a:v+2;continue}}break}let d=l>=a||pe()||i.charCodeAt(l)===Q;return l=h,d}function ie(m){let h=m-1;while(h>=0){let b=i.charCodeAt(h);if(b===Oe||b===ke||b===Se||b===de){h--;continue}break}if(h<0)return!0;let d=i[h];if("+-*/%=<>&|^!~?:,.([{".includes(d))return!0;let g=h;while(g>0&&i.charCodeAt(g-1)!==de)g--;let w=i.slice(g,h+1),v=w.lastIndexOf("<");if(v!==-1&&/^<[A-Za-z]/.test(w.slice(v))&&!w.slice(v).includes(">"))return!0;let R=h;while(R>=0&&/[a-z]/i.test(i[R]))R--;let P=i.slice(R+1,h+1);return["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(P)}function ne(){let m=i.charCodeAt(l);if(m!==de&&m!==Se)return!1;if(ie(l))return!1;let h=l;l++;while(l<a){let v=i.charCodeAt(l);if(v===Oe||v===ke||v===Se||v===de){l++;continue}if(v===X&&l+1<a){let R=i.charCodeAt(l+1);if(R===X){l=E(l+2);continue}if(R===be){let P=i.indexOf("*/",l+2);l=P===-1?a:P+2;continue}}break}let d=l<a?i[l]:"",g=i.slice(l,l+2),w=d==="."||d==="?"||d===":"||d===")"||d==="]"||d==="}"||d===","||d==="+"||d==="-"||d==="*"||d==="/"||d==="%"||d==="<"||d===">"||d==="="||d==="&"||d==="|"||d==="^"||d==="`"||g==="=>"||T("as")||T("satisfies")||T("instanceof")||T("in");return l=h,!w}function ce(){let m=i.charCodeAt(l);if(m!==de&&m!==Se)return!1;if(ie(l))return!1;let h=l;l++;while(l<a){let w=i.charCodeAt(l);if(w===Oe||w===ke||w===Se||w===de){l++;continue}if(w===X&&l+1<a){let v=i.charCodeAt(l+1);if(v===X){l=E(l+2);continue}if(v===be){let R=i.indexOf("*/",l+2);l=R===-1?a:R+2;continue}}break}let d=l<a?i[l]:"",g=d==="|"||d==="&"||d==="["||d==="."||d==="?"||d===":"||d===">"||d===")"||d===","||T("extends");return l=h,!g}function N(){let m=i.charCodeAt(l);if(m!==de&&m!==Se)return!1;let h=l;if(l++,m===Se&&l<a&&i.charCodeAt(l)===de)l++;while(l<a){let g=i.charCodeAt(l);if(g===Oe||g===ke||g===Se||g===de){l++;continue}if(g===X&&l+1<a&&i.charCodeAt(l+1)===X){l=E(l+2);continue}break}if(l>=a)return l=h,!0;let d=i.charCodeAt(l);if(d===124||d===38||d===gt||d===Li||d===ft)return l=h,!1;if(T("extends")||T("keyof")||T("typeof")||T("infer")||T("is")||T("as")||T("in"))return l=h,!1;return l=h,!0}let z=/[{}'"`\/]/g,J=/[()'"`\/]/g,te=/[[\]'"`\/]/g,Z=/[<>'"`\/]/g;function Y(m,h){let d=1;l++;let g=m===U?z:m===se?J:m===Ee?te:Z;g.lastIndex=l;let w;while((w=g.exec(i))!==null){let v=w.index,R=i.charCodeAt(v);if(R===le||R===he){l=v,S(R),g.lastIndex=l;continue}if(R===Ie){l=v,M(),g.lastIndex=l;continue}if(R===X){if(l=v,O()){g.lastIndex=l;continue}g.lastIndex=v+1;continue}if(R===m)d++;else if(R===h){if(h===ue&&v>0&&i.charCodeAt(v-1)===$e){g.lastIndex=v+1;continue}if(d--,d===0)return l=v+1,l}g.lastIndex=v+1}return l=a,l}function oe(){return l>0&&i.charCodeAt(l-1)===$e}function Fe(){return l+1<a&&i.charCodeAt(l+1)===ue}let Ve=/[<{};'"`\/\n\r()[\]]/g;function Me(m=!1){let h=0,d=0,g=0,w=0,v=i.charCodeAt(l)===U;Ve.lastIndex=l;let R;while((R=Ve.exec(i))!==null){let P=R.index,b=i.charCodeAt(P);if(b===le||b===he){l=P,S(b),Ve.lastIndex=l;continue}if(b===Ie){l=P,M(),Ve.lastIndex=l;continue}if(b===X){if(P>0&&i.charCodeAt(P-1)===ve){Ve.lastIndex=P+1;continue}if(l=P,O()){if(h===0&&d===0&&g===0&&w===0&&V())return;Ve.lastIndex=l;continue}Ve.lastIndex=P+1;continue}if(b===ve){let A=Bo(P);if(A!==null)w=Math.max(0,w+A);Ve.lastIndex=P+1;continue}if(b===se){d++,Ve.lastIndex=P+1;continue}if(b===xe){d--,Ve.lastIndex=P+1;continue}if(b===Ee){g++,Ve.lastIndex=P+1;continue}if(b===Pe){g--,Ve.lastIndex=P+1;continue}if(b===U){h++,Ve.lastIndex=P+1;continue}if(b===Q){let A=h>0;if(!A&&m&&d===0&&g===0&&w===0){l=P;return}if(A)h--;if((!A||v)&&h===0&&d===0&&g===0&&w===0){l=P+1;return}Ve.lastIndex=P+1;continue}if(b===re&&h===0&&d===0&&g===0&&w===0){l=P+1;return}if((b===de||b===Se)&&h===0&&d===0&&g===0&&w===0){if(l=P,ee())return}Ve.lastIndex=P+1}l=a}function Ac(){l++;while(l<a&&(i.charCodeAt(l)===Oe||i.charCodeAt(l)===ke))l++;let m=i.indexOf(`
|
|
139
|
+
`,l),h=m===-1?a:m,d=i.indexOf(";",l);if(d!==-1&&d<h){let g=d-1;while(g>=l&&(i.charCodeAt(g)===Oe||i.charCodeAt(g)===ke))g--;let w=i.charCodeAt(l),v=i.charCodeAt(g);if(w===U&&v===Q||w===Ee&&v===Pe||w===le&&v===le||w===he&&v===he||w===Ie&&v===Ie){l=d+1;return}}Me()}function Do(){Y(U,Q);while(l<a&&Ge(i.charCodeAt(l)))l++;if(T("from")){l+=4;while(l<a&&Ge(i.charCodeAt(l)))l++;if(l<a){let m=i.charCodeAt(l);if(m===le||m===he)S(m)}}while(l<a&&(i.charCodeAt(l)===Oe||i.charCodeAt(l)===ke))l++;if(l<a&&i.charCodeAt(l)===re)l++}function Io(){l++;while(l<a&&Ge(i.charCodeAt(l)))l++;if(T("as")){l+=2;while(l<a&&Ge(i.charCodeAt(l)))l++;j();while(l<a&&Ge(i.charCodeAt(l)))l++}if(T("from")){l+=4;while(l<a&&Ge(i.charCodeAt(l)))l++;if(l<a){let m=i.charCodeAt(l);if(m===le||m===he)S(m)}}while(l<a&&(i.charCodeAt(l)===Oe||i.charCodeAt(l)===ke))l++;if(l<a&&i.charCodeAt(l)===re)l++}function Dr(m){let h=m.indexOf("from ");if(h===-1)return;let d=h+5;while(d<m.length&&(m.charCodeAt(d)===32||m.charCodeAt(d)===9))d++;if(d>=m.length)return;let g=m.charCodeAt(d);if(g!==39&&g!==34)return;let w=m.indexOf(m[d],d+1);if(w===-1)return;return m.slice(d+1,w)}function tt(m){if(!o)return;let h=m-1;while(h>=0&&Ge(i.charCodeAt(h)))h--;if(h<0)return;let d=[],g=!1;while(h>=0){if(h>=1&&i.charCodeAt(h)===X&&i.charCodeAt(h-1)===be){let R=i.lastIndexOf("/*",h-2);if(R>=0){d.push(i.slice(R,h+1)),g=!0,h=R-1;while(h>=0&&Ge(i.charCodeAt(h)))h--;continue}break}let w=h;while(w>0&&i.charCodeAt(w-1)!==de)w--;let v=p(w,h+1);if(v.startsWith("//")){if(g)break;let R=[v];h=w-1;while(h>=0&&(i.charCodeAt(h)===de||i.charCodeAt(h)===Se))h--;while(h>=0){let P=h;while(P>0&&i.charCodeAt(P-1)!==de)P--;let b=p(P,h+1);if(b.startsWith("//")){R.push(b),h=P-1;while(h>=0&&(i.charCodeAt(h)===de||i.charCodeAt(h)===Se))h--}else if(b===""){h=P-1;while(h>=0&&(i.charCodeAt(h)===de||i.charCodeAt(h)===Se))h--}else break}R.reverse(),d.push(R.join(`
|
|
140
|
+
`));continue}break}if(d.length===0)return;return d.reverse(),d}function xc(m){let h=m,d=!1;while(l<a){let b=i.charCodeAt(l);if(b===re){l++;break}if(b===le||b===he){S(b),d=!0;while(l<a&&(i.charCodeAt(l)===Oe||i.charCodeAt(l)===ke))l++;if(l<a&&i.charCodeAt(l)===re)l++;break}if(b===de&&d)break;l++}let g=p(h,l),w=g.charCodeAt(7)===116&&(g.startsWith("import type ")||g.startsWith("import type{")),v=!1;{let b=6;while(b<g.length&&(g.charCodeAt(b)===Oe||g.charCodeAt(b)===ke))b++;if(b<g.length&&g.charCodeAt(b)===116&&g.startsWith("type",b)){b+=4;while(b<g.length&&(g.charCodeAt(b)===Oe||g.charCodeAt(b)===ke))b++}if(b<g.length){let A=g.charCodeAt(b);v=A===le||A===he}}let R="";{let b=g.indexOf("from ");if(b!==-1){let A=b+5;while(A<g.length&&(g.charCodeAt(A)===Oe||g.charCodeAt(A)===ke))A++;if(A<g.length){let k=g.charCodeAt(A);if(k===le||k===he){let L=g.indexOf(String.fromCharCode(k),A+1);if(L!==-1)R=g.slice(A+1,L)}}}else if(v){let A=6;while(A<g.length&&g.charCodeAt(A)!==le&&g.charCodeAt(A)!==he)A++;if(A<g.length){let k=g.charCodeAt(A),L=g.indexOf(String.fromCharCode(k),A+1);if(L!==-1)R=g.slice(A+1,L)}}}let P=tt(h);return{kind:"import",name:"",text:g,isExported:!1,isTypeOnly:w,isSideEffect:v,source:R,leadingComments:P,start:h,end:l}}function Ui(){let m=l;return Y(U,Q),i.slice(m,l)}function Fo(m){let h=m.indexOf("(");if(h===-1)return m;let d=m.slice(h);if(d.indexOf("=")===-1)return m;let g=!1;for(let b=0;b<d.length;b++)if(d.charCodeAt(b)===61){let A=b>0?d.charCodeAt(b-1):0,k=b+1<d.length?d.charCodeAt(b+1):0;if(A!==61&&A!==33&&A!==60&&A!==62&&k!==61&&k!==62){g=!0;break}}if(!g)return m;let w=0,v=-1;for(let b=h;b<m.length;b++){let A=m.charCodeAt(b);if(A===40)w++;else if(A===41){if(w--,w===0){v=b;break}}}if(v===-1)return m;let R=m.slice(h,v+1),P=_t(R);return m.slice(0,h)+P+m.slice(v+1)}function No(m){let h=m.indexOf("//")!==-1||m.indexOf("/*")!==-1,d=m.split(`
|
|
141
|
+
`),g=[],w=[],v=[],R=!1,P=1/0;for(let k=0;k<d.length;k++){let L=d[k];if(h){if(R){if(L.includes("*/"))R=!1;continue}let G=L.trim();if(G.length===0)continue;let W=G.charCodeAt(0);if(W===X){let He=G.charCodeAt(1);if(He===X)continue;if(He===be){if(!G.includes("*/"))R=!0;continue}}if(W===be)continue;let F=x(L);if(F.charCodeAt(F.length-1)===re)F=F.slice(0,-1);F=Fo(F);let B=F.trim();if(!B)continue;g.push(F),w.push(B);let _=0;while(_<F.length&&Ge(F.charCodeAt(_)))_++;if(B!=="{"&&B!=="}"){if(_<P)P=_}v.push(_)}else{let G=L.length;while(G>0&&(L.charCodeAt(G-1)===Oe||L.charCodeAt(G-1)===ke||L.charCodeAt(G-1)===Se))G--;if(G===0)continue;let W=G<L.length?L.slice(0,G):L;if(W.charCodeAt(W.length-1)===re)W=W.slice(0,-1);W=Fo(W);let F=W.trim();if(!F)continue;g.push(W),w.push(F);let B=0;while(B<W.length&&Ge(W.charCodeAt(B)))B++;if(F!=="{"&&F!=="}"){if(B<P)P=B}v.push(B)}}if(g.length===0)return"{}";if(P===1/0||P<=2)return g.join(`
|
|
142
142
|
`);let b=P-2,A=Array(g.length);for(let k=0;k<g.length;k++){let L=w[k];if(L==="{"){A[k]=L;continue}let G=v[k];if(G>P)A[k]=g[k];else if(G===P&&(L.charCodeAt(0)===Q||L.charCodeAt(0)===Pe||L.charCodeAt(0)===xe))A[k]=g[k];else{let W=Math.max(0,G-b);A[k]=" ".repeat(W)+L}}return A.join(`
|
|
143
143
|
`)}function mt(){if(l>=a||i.charCodeAt(l)!==ve)return"";let m=l;Y(ve,ue);let h=i.slice(m,l);if(h.includes(`
|
|
144
144
|
`)){let d="",g=!1;for(let w=0;w<h.length;w++){let v=h.charCodeAt(w);if(v===32||v===9||v===10||v===13){if(!g&&d.length>0)d+=" ",g=!0}else d+=h[w],g=!1}if(d.charCodeAt(1)===32)d=`<${d.slice(2)}`;if(d.charCodeAt(d.length-2)===32)d=`${d.slice(0,-2)}>`;return d}return h}function xt(){if(l>=a||i.charCodeAt(l)!==se)return"()";let m=l;return Y(se,xe),i.slice(m,l)}function Ir(m){if(m.indexOf("/")===-1)return m;let h="",d=!1,g=0;for(let w=0;w<m.length;w++){let v=m.charCodeAt(w);if(d){if(h+=m[w],v===Xe&&w+1<m.length){h+=m[++w];continue}if(v===g)d=!1;continue}if(v===le||v===he||v===Ie){d=!0,g=v,h+=m[w];continue}if(v===X&&w+1<m.length){let R=m.charCodeAt(w+1);if(R===be){let P=m.indexOf("*/",w+2);w=P===-1?m.length:P+1,h+=" ";continue}if(R===X){let P=m.indexOf(`
|
|
145
145
|
`,w+2);w=P===-1?m.length:P-1;continue}}h+=m[w]}return h.trim()}function _t(m){let h=m.slice(1,-1).trim();if(!h)return"()";if(m.indexOf(`
|
|
146
|
-
`)===-1&&h.indexOf(":")!==-1&&h.indexOf("{")===-1&&h.indexOf("[")===-1&&h.indexOf("=")===-1&&h.indexOf("@")===-1&&h.indexOf("...")===-1){let b=0,A=0,k=0;for(let L=0;L<h.length;L++){let G=h.charCodeAt(L);if(G===se||G===ve||G===U)k++;else if(G===xe||G===ue||G===Q)k--;else if(k===0){if(G===ft)b++;else if(G===ut)A++}}if(b>=A+1){let L=!1;for(let G=0;G<
|
|
147
|
-
`,B);if(He===-1){k=k.slice(0,F).trimEnd();break}let Je=k.slice(0,F),Kt=k.slice(He+1);k=`${Je}${Kt}`,B=F-1}}}if(!k.trim())continue;P.push(
|
|
148
|
-
`))h=h.slice(0,-1);d++;let P=0;while(d<m.length){let b=m.charCodeAt(d);if(b===le||b===he||b===Ie){let A=b;d++;while(d<m.length){if(m.charCodeAt(d)===Xe){d+=2;continue}if(m.charCodeAt(d)===A){d++;break}d++}continue}if(b===U||b===Ee||b===se)P++;else if(b===Q||b===Pe||b===xe){if(P===0)break;P--}else if(b===ut&&P===0)break;d++}continue}if(g===1&&R===gt&&d+2<m.length&&m.charCodeAt(d+1)===gt&&m.charCodeAt(d+2)===gt){d+=3;continue}h+=m[d],d++}return h}function
|
|
146
|
+
`)===-1&&h.indexOf(":")!==-1&&h.indexOf("{")===-1&&h.indexOf("[")===-1&&h.indexOf("=")===-1&&h.indexOf("@")===-1&&h.indexOf("...")===-1){let b=0,A=0,k=0;for(let L=0;L<h.length;L++){let G=h.charCodeAt(L);if(G===se||G===ve||G===U)k++;else if(G===xe||G===ue||G===Q)k--;else if(k===0){if(G===ft)b++;else if(G===ut)A++}}if(b>=A+1){let L=!1;for(let G=0;G<So.length;G++){let W=So[G],F=h.indexOf(W);if(F!==-1){let B=F+W.length;if((F===0||!Qe(h.charCodeAt(F-1)))&&(B>=h.length||!Qe(h.charCodeAt(B)))){L=!0;break}}}if(!L)return m}}let d=[],g=0,w=0,v=!1,R=0;for(let b=0;b<=h.length;b++){if(b===h.length){d.push(Ir(h.slice(g).trim()));break}let A=h.charCodeAt(b);if(v){if(A===Xe){b++;continue}if(A===R)v=!1;continue}if(A===X&&b+1<h.length){let k=h.charCodeAt(b+1);if(k===be){b+=2;while(b+1<h.length&&!(h.charCodeAt(b)===be&&h.charCodeAt(b+1)===X))b++;b++;continue}if(k===X){while(b<h.length&&h.charCodeAt(b)!==10)b++;continue}}if(A===le||A===he||A===Ie){v=!0,R=A;continue}if(A===se||A===U||A===Ee||A===ve)w++;else if(A===xe||A===Q||A===Pe||A===ue&&!(b>0&&h.charCodeAt(b-1)===$e))w--;else if(A===ut&&w===0)d.push(Ir(h.slice(g,b).trim())),g=b+1}let P=[];for(let b of d){if(!b)continue;let A=b.trim();if(A.startsWith("//")||A.startsWith("/*"))continue;let k=b;{let L=!1,G=0,W=0,F=0;for(let B=0;B<k.length-1;B++){let _=k.charCodeAt(B);if(_===de){F=B+1;continue}if(L){if(_===Xe){B++;continue}if(_===G)L=!1;continue}if(_===le||_===he||_===Ie){L=!0,G=_;continue}if(_===U||_===Ee||_===se||_===ve){W++;continue}if(_===Q||_===Pe||_===xe||_===ue){if(W>0)W--;continue}if(_===X&&k.charCodeAt(B+1)===X){if(W===0){k=k.slice(0,B).trimEnd();break}let He=k.indexOf(`
|
|
147
|
+
`,B);if(He===-1){k=k.slice(0,F).trimEnd();break}let Je=k.slice(0,F),Kt=k.slice(He+1);k=`${Je}${Kt}`,B=F-1}}}if(!k.trim())continue;P.push(Lo(k))}return`(${P.join(", ")})`}function Tc(m){if(!m.startsWith("{")&&!m.startsWith("["))return m;let h="",d=0,g=0,w=!1,v=0;while(d<m.length){let R=m.charCodeAt(d);if(w){if(R===Xe&&d+1<m.length){h+=m[d]+m[d+1],d+=2;continue}if(R===v)w=!1;h+=m[d],d++;continue}if(R===X&&d+1<m.length){let P=m.charCodeAt(d+1);if(P===be){let b=d;d+=2;while(d+1<m.length&&!(m.charCodeAt(d)===be&&m.charCodeAt(d+1)===X))d++;d=Math.min(d+2,m.length),h+=m.slice(b,d);continue}if(P===X){let b=d;while(d<m.length&&m.charCodeAt(d)!==10)d++;h+=m.slice(b,d);continue}}if(R===le||R===he||R===Ie){w=!0,v=R,h+=m[d],d++;continue}if(R===U||R===Ee||R===se)g++;else if(R===Q||R===Pe||R===xe)g--;if(g>=1&&R===$e&&(d+1>=m.length||m.charCodeAt(d+1)!==$e&&m.charCodeAt(d+1)!==ue)){while(h.length>0&&(h[h.length-1]===" "||h[h.length-1]==="\t"||h[h.length-1]===`
|
|
148
|
+
`))h=h.slice(0,-1);d++;let P=0;while(d<m.length){let b=m.charCodeAt(d);if(b===le||b===he||b===Ie){let A=b;d++;while(d<m.length){if(m.charCodeAt(d)===Xe){d+=2;continue}if(m.charCodeAt(d)===A){d++;break}d++}continue}if(b===U||b===Ee||b===se)P++;else if(b===Q||b===Pe||b===xe){if(P===0)break;P--}else if(b===ut&&P===0)break;d++}continue}if(g===1&&R===gt&&d+2<m.length&&m.charCodeAt(d+1)===gt&&m.charCodeAt(d+2)===gt){d+=3;continue}h+=m[d],d++}return h}function Lo(m){let h=m.trim(),d=h.startsWith("...");if(d)h=h.slice(3).trim();while(h.startsWith("@")){let F=1;while(F<h.length&&Qe(h.charCodeAt(F)))F++;if(F<h.length&&h.charCodeAt(F)===se){let B=1;F++;while(F<h.length&&B>0){if(h.charCodeAt(F)===se)B++;else if(h.charCodeAt(F)===xe)B--;F++}}h=h.slice(F).trim()}let g=!0;while(g){g=!1;for(let F of So)if(h.startsWith(F)&&h.length>F.length&&!Qe(h.charCodeAt(F.length))){let B=h.slice(F.length).trim();if(B.charCodeAt(0)===ft||B.charCodeAt(0)===Li&&B.length>1&&B.charCodeAt(1)===ft)break;h=B,g=!0;break}}let w=-1,v=-1,R=0,P=!1,b=0;for(let F=0;F<h.length;F++){let B=h.charCodeAt(F);if(P){if(B===Xe){F++;continue}if(B===b)P=!1;continue}if(B===X&&F+1<h.length){let _=h.charCodeAt(F+1);if(_===be){F+=2;while(F+1<h.length&&!(h.charCodeAt(F)===be&&h.charCodeAt(F+1)===X))F++;F++;continue}if(_===X){while(F<h.length&&h.charCodeAt(F)!==10)F++;continue}}if(B===le||B===he||B===Ie){P=!0,b=B;continue}if(B===se||B===U||B===Ee||B===ve)R++;else if(B===xe||B===Q||B===Pe||B===ue&&!(F>0&&h.charCodeAt(F-1)===$e))R--;else if(R===0){if(B===ft&&w===-1)w=F;else if(B===$e&&v===-1&&(F===0||h.charCodeAt(F-1)!==$e)&&(F+1>=h.length||h.charCodeAt(F+1)!==$e&&h.charCodeAt(F+1)!==ue))v=F}}let A,k,L=v!==-1;if(w!==-1&&(v===-1||w<v))if(A=h.slice(0,w).trim(),v!==-1)k=h.slice(w+1,v).trim();else k=h.slice(w+1).trim();else if(v!==-1)A=h.slice(0,v).trim(),k=Ki(h.slice(v+1).trim());else A=h,k="unknown";if(A=Tc(A),(A.startsWith("{")||A.startsWith("["))&&A.includes(`
|
|
149
149
|
`)){let F=A.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(F.length<=40)A=F;else A=A.split(`
|
|
150
150
|
`).map((B)=>{let _=B.trim();if(!_)return"";if(_==="{"||_==="}"||_==="["||_==="]"||_.startsWith("}")||_.startsWith("]"))return _;return` ${_}`}).join(`
|
|
151
|
-
`)}let G=A.endsWith("?")||L;if(A.endsWith("?"))A=A.slice(0,-1).trim();let W=G&&!d?"?":"";if(d)return`...${A}: ${k}`;return`${A}${W}: ${k}`}function
|
|
152
|
-
`,v+2),k=A===-1?m.length:A;w+=m.slice(v,k),v=k;continue}let P=m.indexOf("*/",v+2),b=P===-1?m.length:P+2;w+=m.slice(v,b),v=b;continue}if(R===se||R===Ee||R===U)g++;else if(R===xe||R===Pe||R===Q)g--;if(m[v]===h&&g===0){d.push(w),w="",v++;continue}w+=m[v],v++}return d.push(w),d}function
|
|
153
|
-
`;if(d==="t")return"\t";if(d==="r")return"\r";if(d==="0")return"\x00";return d})}function
|
|
151
|
+
`)}let G=A.endsWith("?")||L;if(A.endsWith("?"))A=A.slice(0,-1).trim();let W=G&&!d?"?":"";if(d)return`...${A}: ${k}`;return`${A}${W}: ${k}`}function Wo(m){let h=0;if(h<m.length&&m.charCodeAt(h)===45)h++;if(h>=m.length)return!1;let d=m.charCodeAt(h);if(d<48||d>57)return!1;while(h<m.length&&m.charCodeAt(h)>=48&&m.charCodeAt(h)<=57)h++;if(h<m.length&&m.charCodeAt(h)===46){if(h++,h>=m.length||m.charCodeAt(h)<48||m.charCodeAt(h)>57)return!1;while(h<m.length&&m.charCodeAt(h)>=48&&m.charCodeAt(h)<=57)h++}return h===m.length}function Ki(m){let h=m.trim();if(h==="true"||h==="false")return"boolean";if(Wo(h))return"number";if(h.startsWith("'")&&h.endsWith("'")||h.startsWith('"')&&h.endsWith('"'))return"string";if(h.startsWith("["))return"unknown[]";if(h.startsWith("{"))return"Record<string, unknown>";return"unknown"}function zi(m){let h=m.trim();if(h.endsWith("as const"))h=h.slice(0,-8).trim();if(h==="true"||h==="false")return h;if(Wo(h))return h;let d=Rc(h);if(d!==null)return d;return"unknown"}function Rc(m){if(m==="")return null;if(m.charCodeAt(0)===le||m.charCodeAt(0)===he){if(Bi(m,0,m.charCodeAt(0))===m.length)return m}let h=Pc(m,"+");if(h.length>1){let d=!1,g=!0,w=[];for(let v of h){let R=v.trim(),P=R.charCodeAt(0);if((P===le||P===he)&&Bi(R,0,P)===R.length)d=!0,w.push(Oc(R));else g=!1}if(g)return kc(w.join(""));if(d)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(m)&&/\d/.test(m)&&/[+*/%\-\s]/.test(m))return"number";return null}function Pc(m,h){let d=[],g=0,w="",v=0;while(v<m.length){let R=m.charCodeAt(v);if(R===le||R===he||R===Ie){let P=Bi(m,v,R);w+=m.slice(v,P),v=P;continue}if(R===X&&(m.charCodeAt(v+1)===X||m.charCodeAt(v+1)===42)){if(m.charCodeAt(v+1)===X){let A=m.indexOf(`
|
|
152
|
+
`,v+2),k=A===-1?m.length:A;w+=m.slice(v,k),v=k;continue}let P=m.indexOf("*/",v+2),b=P===-1?m.length:P+2;w+=m.slice(v,b),v=b;continue}if(R===se||R===Ee||R===U)g++;else if(R===xe||R===Pe||R===Q)g--;if(m[v]===h&&g===0){d.push(w),w="",v++;continue}w+=m[v],v++}return d.push(w),d}function Oc(m){return m.slice(1,-1).replace(/\\(.)/g,(h,d)=>{if(d==="n")return`
|
|
153
|
+
`;if(d==="t")return"\t";if(d==="r")return"\r";if(d==="0")return"\x00";return d})}function kc(m){return`'${m.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Fr(m){if(m.endsWith("as const"))return null;let h=0,d=-1;for(let g=0;g<m.length;g++){let w=m.charCodeAt(g);if(w===le||w===he||w===Ie)g=Bi(m,g,w)-1;else if(w===123||w===91||w===40)h++;else if(w===125||w===93||w===41)h--;else if(h===0&&w===32&&g+4<=m.length&&m.substring(g,g+4)===" as ")d=g}if(d===-1)return null;return m.slice(d+4).trim()||null}function hr(){if(y(),l<a&&i.charCodeAt(l)===ft){l++,y();let m=l,h=0;while(l<a){if(O())continue;let d=i.charCodeAt(l);if(d===se||d===Ee||d===ve)h++;else if(d===xe||d===Pe||d===ue&&!oe())h--;else if(d===U)if(h>0)h++;else{let g=p(m,l),w=(v)=>{let R=g.length-v.length;return R>=0&&g.endsWith(v)&&(R===0||!Qe(g.charCodeAt(R-1)))};if(g.length===0||g.endsWith("|")||g.endsWith("&")||w("is")||w("extends"))h++;else break}else if(d===Q){if(h===0)break;h--}else if(h===0&&d===re)break;if(h===0&&N())break;l++}return p(m,l)}return""}function Tt(m,h,d,g){l+=8,y();let w=l<a&&i.charCodeAt(l)===be;if(w)l++,y();let v=j();if(!v&&!g)return null;y();let R=mt();y();let P=xt();y();let b=hr(),A=b.length>0;if(!b)if(d&&w)b="AsyncGenerator<unknown, void, unknown>";else if(w)b="Generator<unknown, void, unknown>";else if(d)b="Promise<void>";else b="void";y();let k=!1;if(l<a&&i.charCodeAt(l)===U){k=!0;let F=l+1;if(Y(U,Q),!A&&!w)b=fr(i.slice(F,l-1),d,P)}else if(l<a&&i.charCodeAt(l)===re)l++;let L=_t(P),G=`${h?g?"export default function ":"export declare function ":"declare function "}${v||(g?"":"default")}${R}${L}: ${b};`,W=tt(m);if(k)u.add(c.length);return{kind:"function",name:v||"default",text:G,isExported:h,isDefault:g,isAsync:d,isGenerator:w,returnType:b,generics:R||void 0,leadingComments:W,start:m,end:l}}function Ft(m,h,d){l+=h.length,y();let g=[];do{if(y(),l>=a)break;let w=i.charCodeAt(l);if(w===U||w===Ee)return Me(),g;let v=j();if(!v)return Me(),g;y();let R,P,b=!1;if(l<a&&i.charCodeAt(l)===ft){l++,y();let L=l,G=0;while(l<a){if(O()){if(G===0&&V())break;continue}let W=i.charCodeAt(l);if(W===se||W===U||W===Ee||W===ve)G++;else if(W===xe||W===Q||W===Pe||W===ue&&!oe())G--;else if(G===0&&(W===re||W===ut))break;else if(G===0&&W===$e&&!Fe())break;if(G===0&&(ee()||ce()))break;l++}R=p(L,l)}if(l<a&&i.charCodeAt(l)===$e)if(s&&R&&(!o||!yd(R)))Ac();else{l++,y();let L=l,G=0,W=0,F=0,B=!0;for(;;){l=L,G=0,W=0,F=0;while(l<a){if(O()){if(G===0&&W===0&&F===0&&V())break;continue}let _=i.charCodeAt(l);if(_===se||_===U||_===Ee)G++;else if(_===xe||_===Q||_===Pe)G--;else if(_===ve&&G===0){let He=Bo(l);if(He!==null)F=Math.max(0,F+He);else if(B&&(l+1>=a||i.charCodeAt(l+1)!==$e))W++}else if(_===ue&&G===0&&F===0&&!oe()){if(W>0&&(l+1>=a||i.charCodeAt(l+1)!==$e))W--}else if(G===0&&W===0&&F===0&&(_===re||_===ut))break;if(G===0&&W===0&&F===0&&(ee()||ne()))break;l++}if(W>0&&B){B=!1;continue}break}if(P=p(L,l),P.endsWith(" as const")||P==="const"){if(b=!0,!R){let _=P.endsWith(" as const")?P.slice(0,-9).trim():P,He=zi(_);R=He!=="unknown"?He:void 0}}else if(!R){let _=Ni(P)??Fr(P);if(_)R=_}}if(l<a){let L=i.charCodeAt(l);if(L===ut){l++;continue}if(L===re)l++}let A=tt(m),k=`${d?"export ":""}declare ${h} ${v}: ${R||"unknown"};`;g.push({kind:"variable",name:v,text:k,isExported:d,typeAnnotation:R,value:P,modifiers:b?[h,"const assertion"]:[h],leadingComments:A,start:m,end:l});break}while(l<a);return g}function Bo(m){if(i.charCodeAt(m)!==ve||m+1>=a)return null;let h=i.charCodeAt(m+1);if(h===ue)return 1;if(h===X)return-1;if(!Gt(h))return null;let d=m+2;while(d<a){let A=i.charCodeAt(d);if(!Qe(A)&&A!==gt&&A!==58&&A!==45)break;d++}let g=i.slice(m+1,d),w=i.charCodeAt(d);if(w>32&&w!==ue&&w!==X)return null;let v=0,R=0,P=d;for(;P<a;P++){let A=i.charCodeAt(P);if(R!==0){if(A===Xe)P++;else if(A===R)R=0;continue}if(A===le||A===he||A===Ie)R=A;else if(A===U)v++;else if(A===Q&&v>0)v--;else if(A===ue&&v===0)break}if(P>=a)return null;let b=P-1;while(b>m&&i.charCodeAt(b)<=32)b--;if(i.charCodeAt(b)===X)return 0;return i.indexOf(`</${g}`,P+1)===-1?null:1}function Hi(m,h){l+=9,y();let d=j();y();let g=mt();y();let w="";if(T("extends")){l+=7,y();let A=l,k=0;while(l<a){if(O())continue;let L=i.charCodeAt(l);if(L===ve)k++;else if(L===ue&&!oe())k--;else if(L===U&&k===0)break;l++}w=p(A,l)}y();let v=l<a&&i.charCodeAt(l)===U?Ui():"{}",R=No(v),P=`${h?"export ":""}declare interface ${d}${g}${w?` extends ${w}`:""} ${R}`,b=tt(m);return{kind:"interface",name:d,text:P,isExported:h,extends:w||void 0,generics:g||void 0,leadingComments:b,start:m,end:l}}function Ji(m,h){l+=4,y();let d=j();y();let g=mt();if(y(),l<a&&i.charCodeAt(l)===$e)l++;y();let w=l,v=0;while(l<a){if(O())continue;let A=i.charCodeAt(l);if(A===se||A===U||A===Ee||A===ve)v++;else if(A===xe||A===Q||A===Pe||A===ue&&!oe())v--;else if(v===0&&A===re)break;if(v===0&&(ee()||ce()))break;l++}let R=p(w,l);if(l<a&&i.charCodeAt(l)===re)l++;let P=`${h?"export ":""}type ${d}${g} = ${R}`,b=tt(m);return{kind:"type",name:d,text:P,isExported:h,generics:g||void 0,leadingComments:b,start:m,end:l}}function Vt(m,h,d){l+=4,y();let g=j();y();let w=l;if(l<a&&i.charCodeAt(l)===U)Y(U,Q);let v=p(m,l),R=tt(m);return{kind:"enum",name:g,text:v,isExported:h,modifiers:d?["const"]:void 0,leadingComments:R,start:m,end:l}}function Rt(m,h,d,g=!1){l+=5,y();let w=j()||"AnonymousClass";y();let v=mt();y();let R="";if(T("extends")){l+=7,y();let L=l,G=0;while(l<a){if(O())continue;let W=i.charCodeAt(l);if(W===ve)G++;else if(W===ue&&!oe())G--;else if(G===0&&(W===U||T("implements")))break;l++}R=p(L,l)}let P;if(T("implements")){l+=10,y();let L=l,G=0;while(l<a){if(O())continue;let F=i.charCodeAt(l);if(F===ve)G++;else if(F===ue&&!oe())G--;else if(G===0&&F===U)break;l++}let W=p(L,l);if(W)P=W.split(",").map((F)=>F.trim())}y();let b=qi(),A=`${h?g?"export default ":"export declare ":"declare "}${d?"abstract ":""}class ${w}${v}${R?` extends ${R}`:""}${P&&P.length>0?` implements ${P.join(", ")}`:""} ${b}`,k=tt(m);return{kind:"class",name:w,text:A,isExported:h,isDefault:g,extends:R||void 0,implements:P,generics:v||void 0,modifiers:d?["abstract"]:void 0,leadingComments:k,start:m,end:l}}function qi(){if(l>=a||i.charCodeAt(l)!==U)return"{}";l++;let m=[];while(l<a){if(y(),l>=a)break;if(i.charCodeAt(l)===Q){l++;break}if(i.charCodeAt(l)===re){l++;continue}if(T("static")&&Go("static")===U){l+=6,y(),Y(U,Q);continue}let h=!1,d=!1,g=!1,w=!1,v=!1,R=!1,P=!1,b=!1,A=!0;while(A){if(y(),T("private")){h=!0,l+=7;continue}if(T("protected")){d=!0,l+=9;continue}if(T("public")){l+=6;continue}if(T("static")){g=!0,l+=6;continue}if(T("abstract")){w=!0,l+=8;continue}if(T("readonly")){v=!0,l+=8;continue}if(T("override")){R=!0,l+=8;continue}if(T("accessor")){P=!0,l+=8;continue}if(T("async")){b=!0,l+=5;continue}if(T("declare")){l+=7;continue}break}if(y(),l>=a||i.charCodeAt(l)===Q)break;if(i.charCodeAt(l)===Wi)h=!0;if(h){Zi();continue}let k=" ";if(d)k+="protected ";if(g)k+="static ";if(w)k+="abstract ";if(v)k+="readonly ";if(T("constructor")){l+=11,y();let L=xt();if(y(),Dc(L,m),l<a&&i.charCodeAt(l)===U)Y(U,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let G=_t(L);m.push(` constructor${G};`)}else if(T("get"))if(l+=3,y(),l<a&&(Gt(i.charCodeAt(l))||i.charCodeAt(l)===Ee||i.charCodeAt(l)===Wi)){let L=Yi();if(L.startsWith("#")){if(y(),l<a&&i.charCodeAt(l)===se)xt();if(y(),hr(),y(),l<a&&i.charCodeAt(l)===U)Y(U,Q);else if(l<a&&i.charCodeAt(l)===re)l++;continue}y(),xt(),y();let G=hr()||"unknown";if(y(),l<a&&i.charCodeAt(l)===U)Y(U,Q);else if(l<a&&i.charCodeAt(l)===re)l++;m.push(`${k}get ${L}(): ${G};`)}else jo("get",k,g,v,b,m);else if(T("set"))if(l+=3,y(),l<a&&(Gt(i.charCodeAt(l))||i.charCodeAt(l)===Ee||i.charCodeAt(l)===Wi)){let L=Yi();if(L.startsWith("#")){if(y(),l<a&&i.charCodeAt(l)===se)xt();if(y(),l<a&&i.charCodeAt(l)===U)Y(U,Q);else if(l<a&&i.charCodeAt(l)===re)l++;continue}y();let G=xt();if(y(),l<a&&i.charCodeAt(l)===U)Y(U,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let W=_t(G);m.push(`${k}set ${L}${W};`)}else jo("set",k,g,v,b,m);else{let L=i.charCodeAt(l)===be;if(L)l++,y();let G=Yi();if(!G){Zi();continue}_o(G,k,g,v,L,w,b,m)}}return`{
|
|
154
154
|
${m.join(`
|
|
155
155
|
`)}
|
|
156
|
-
}`}function Yi(){if(l>=a)return"";let m=i.charCodeAt(l);if(m===Ee){let h=l;return Y(Ee,Pe),i.slice(h,l)}if(m===Wi)return l++,`#${j()}`;return j()}function
|
|
156
|
+
}`}function Yi(){if(l>=a)return"";let m=i.charCodeAt(l);if(m===Ee){let h=l;return Y(Ee,Pe),i.slice(h,l)}if(m===Wi)return l++,`#${j()}`;return j()}function Go(m){let h=l+m.length;while(h<a&&Ge(i.charCodeAt(h)))h++;return h<a?i.charCodeAt(h):0}function Zi(){let m=0;while(l<a){if(O())continue;let h=i.charCodeAt(l);if(h===U||h===se)m++;else if(h===Q||h===xe){if(m===0)return;m--}else if(h===re&&m===0){l++;return}if(m===0&&N())return;l++}}function jo(m,h,d,g,w,v){_o(m,h,d,g,!1,!1,w,v)}function _o(m,h,d,g,w,v,R,P){if(y(),l>=a)return;let b=i.charCodeAt(l),A=!1;if(b===Li)A=!0,l++,y();if(l<a&&i.charCodeAt(l)===33)l++,y();let k=l<a?i.charCodeAt(l):0;if(k===se||k===ve){let L=k===ve?mt():"";y();let G=xt();y();let W=hr(),F=W.length>0;if(!W)if(R&&w)W="AsyncGenerator<unknown, void, unknown>";else if(w)W="Generator<unknown, void, unknown>";else if(R)W="Promise<void>";else W="void";if(y(),l<a&&i.charCodeAt(l)===U){let He=l+1;if(Y(U,Q),!F&&!w)W=fr(i.slice(He,l-1),R,G)}else if(l<a&&i.charCodeAt(l)===re)l++;let B=_t(G),_=A?"?":"";P.push(`${h}${m}${_}${L}${B}: ${W};`)}else if(k===ft||k===$e||k===re||k===Q||k===de||k===Se){let L="";if(k===ft){l++,y();let F=l,B=0;while(l<a){if(O())continue;let _=i.charCodeAt(l);if(_===se||_===U||_===Ee||_===ve)B++;else if(_===xe||_===Q||_===Pe||_===ue&&!oe()){if(B===0)break;B--}else if(B===0&&(_===re||_===ut))break;else if(B===0&&_===$e&&!Fe())break;if(B===0&&N())break;l++}L=p(F,l)}let G="";if(l<a&&i.charCodeAt(l)===$e)if(s&&L){l++;let F=0;while(l<a){if(O())continue;let B=i.charCodeAt(l);if(B===se||B===U||B===Ee)F++;else if(B===xe||B===Q||B===Pe){if(F===0&&B===Q)break;F--}else if(F===0&&B===re)break;if(F===0&&N())break;l++}}else{l++,y();let F=l,B=0;while(l<a){if(O())continue;let _=i.charCodeAt(l);if(_===se||_===U||_===Ee)B++;else if(_===xe||_===Q||_===Pe){if(B===0&&_===Q)break;B--}else if(B===0&&_===re)break;if(B===0&&N())break;l++}G=p(F,l)}if(l<a&&i.charCodeAt(l)===re)l++;if(!L)if(G){let F=Fr(G);if(F)L=F;else L=G.endsWith("as const")||d&&g?zi(G):Ki(G)}else L="unknown";let W=A?"?":"";P.push(`${h}${m}${W}: ${L};`)}else Zi()}function Mc(m){let h=0;for(let d=0;d<m.length;d++){let g=m.charCodeAt(d);if(g===se||g===U||g===Ee||g===ve)h++;else if(g===xe||g===Q||g===Pe||g===ue&&m.charCodeAt(d-1)!==$e)h--;else if(g===$e&&h===0&&m.charCodeAt(d+1)!==ue&&m.charCodeAt(d+1)!==$e)return!0}return!1}function Dc(m,h){let d=m.slice(1,-1).trim();if(!d)return;let g=[],w=0,v=0,R=!1,P=0;for(let b=0;b<=d.length;b++){if(b===d.length){g.push(Ir(d.slice(w).trim()));break}let A=d.charCodeAt(b);if(R){if(A===Xe){b++;continue}if(A===P)R=!1;continue}if(A===X&&b+1<d.length){let k=d.charCodeAt(b+1);if(k===be){b+=2;while(b+1<d.length&&!(d.charCodeAt(b)===be&&d.charCodeAt(b+1)===X))b++;b++;continue}if(k===X){while(b<d.length&&d.charCodeAt(b)!==10)b++;continue}}if(A===le||A===he||A===Ie){R=!0,P=A;continue}if(A===se||A===U||A===Ee||A===ve)v++;else if(A===xe||A===Q||A===Pe||A===ue&&!(b>0&&d.charCodeAt(b-1)===$e))v--;else if(A===ut&&v===0)g.push(Ir(d.slice(w,b).trim())),w=b+1}for(let b of g){let A=b.startsWith("public ")||b.startsWith("public\t"),k=b.startsWith("protected ")||b.startsWith("protected\t"),L=b.startsWith("private ")||b.startsWith("private\t"),G=b.includes("readonly ");if(!A&&!k&&!L&&!G)continue;if(L)continue;let W=b,F=[];if(A){let Je=6;while(Je<W.length&&Ge(W.charCodeAt(Je)))Je++;W=W.slice(Je),F.push("public")}if(k){let Je=9;while(Je<W.length&&Ge(W.charCodeAt(Je)))Je++;W=W.slice(Je),F.push("protected")}if(G){let Je=W.indexOf("readonly ");if(Je!==-1){let Kt=Je+8;while(Kt<W.length&&Ge(W.charCodeAt(Kt)))Kt++;W=W.slice(0,Je)+W.slice(Kt)}F.push("readonly")}let B=F.length>0?`${F.join(" ")} `:"",_=Lo(W),He=W.search(/[?:=]/);if(He!==-1&&W.charCodeAt(He)!==63&&Mc(W))_=_.replace(/^([\w$]+)\?:/,"$1:");h.push(` ${B}${_};`)}}function Xi(m=" "){if(l>=a||i.charCodeAt(l)!==U)return"{}";l++;let h=[];while(l<a){if(y(),l>=a)break;if(i.charCodeAt(l)===Q){l++;break}if(i.charCodeAt(l)===re){l++;continue}let d=!1;if(T("export"))d=!0,l+=6,y();if(T("declare"))l+=7,y();let g=d?"export ":"";if(T("function")||T("async")&&Ic("async","function")){let w=!1;if(T("async"))w=!0,l+=5,y();if(l+=8,y(),l<a&&i.charCodeAt(l)===be)l++,y();let v=j();y();let R=mt();y();let P=xt();y();let b=hr();if(!b)b=w?"Promise<void>":"void";if(y(),l<a&&i.charCodeAt(l)===U)Y(U,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let A=_t(P);h.push(`${m}${g}function ${v}${R}${A}: ${b};`)}else if(T("const")||T("let")||T("var")){let w=T("const")?"const":T("let")?"let":"var";l+=w.length,y();let v=j();if(!v){Me(!0);continue}y();let R="";if(l<a&&i.charCodeAt(l)===ft){l++,y();let b=l,A=0;while(l<a){if(O())continue;let k=i.charCodeAt(l);if(k===se||k===U||k===Ee||k===ve)A++;else if(k===Q&&A===0)break;else if(k===xe||k===Q||k===Pe||k===ue&&!oe())A--;else if(A===0&&(k===re||k===ut))break;else if(A===0&&k===$e&&!Fe())break;if(A===0&&ee())break;l++}R=p(b,l)}let P="";if(l<a&&i.charCodeAt(l)===$e){l++,y();let b=l,A=0;while(l<a){if(O())continue;let k=i.charCodeAt(l);if(k===se||k===U||k===Ee||k===ve)A++;else if(k===Q&&A===0)break;else if(k===xe||k===Q||k===Pe||k===ue&&!oe())A--;else if(A===0&&(k===re||k===ut))break;if(A===0&&ee())break;l++}P=p(b,l)}if(l<a&&i.charCodeAt(l)===re)l++;if(!R&&P){let b=Fr(P);if(b)R=b;else if(w==="const")R=zi(P);else R=Ki(P)}if(!R)R="unknown";h.push(`${m}${g}${w} ${v}: ${R};`)}else if(T("interface")){l+=9,y();let w=j();y();let v=mt();y();let R="";if(T("extends")){l+=7,y();let b=l,A=0;while(l<a){if(O())continue;let k=i.charCodeAt(l);if(k===ve)A++;else if(k===ue&&!oe())A--;else if(k===U&&A===0)break;l++}R=p(b,l)}let P=No(Ui());h.push(`${m}${g}interface ${w}${v}${R?` extends ${R}`:""} ${P}`)}else if(T("type")){l+=4,y();let w=j();y();let v=mt();if(y(),l<a&&i.charCodeAt(l)===$e){l++,y();let R=l,P=0;while(l<a){if(O())continue;let A=i.charCodeAt(l);if(A===se||A===U||A===Ee||A===ve)P++;else if(A===Q&&P===0)break;else if(A===xe||A===Q||A===Pe||A===ue&&!oe())P--;else if(P===0&&A===re)break;if(P===0&&ee())break;l++}let b=p(R,l);if(l<a&&i.charCodeAt(l)===re)l++;h.push(`${m}${g}type ${w}${v} = ${b}`)}}else if(T("class")){l+=5,y();let w=j();y();let v=mt();y();let R=l,P=0;while(l<a){if(O())continue;let L=i.charCodeAt(l);if(L===ve)P++;else if(L===ue&&!oe())P--;else if(L===U&&P===0)break;l++}let b=p(R,l),A=b?` ${b}`:"",k=qi();h.push(`${m}${g}class ${w}${v}${A} ${k}`)}else if(T("enum")){l+=4,y();let w=j();y();let v=Ui();h.push(`${m}${g}enum ${w} ${v}`)}else if(T("namespace")||T("module")){let w=T("namespace")?"namespace":"module";l+=w.length,y();let v=j();y();let R=Xi(m);h.push(`${m}${g}${w} ${v} ${R}`)}else if(T("abstract"))if(l+=8,y(),T("class")){l+=5,y();let w=j();y();let v=mt();y();let R=l,P=0;while(l<a){if(O())continue;let L=i.charCodeAt(l);if(L===ve)P++;else if(L===ue&&!oe())P--;else if(L===U&&P===0)break;l++}let b=p(R,l),A=b?` ${b}`:"",k=qi();h.push(`${m}${g}abstract class ${w}${v}${A} ${k}`)}else Me(!0);else if(d&&T("default")){l+=7,y();let w=l;Me(!0);let v=p(w,l);if(v.charCodeAt(v.length-1)===re)v=v.slice(0,-1);if(v)h.push(`${m}export default ${v};`)}else if(!d&&(i.charCodeAt(l)===le||i.charCodeAt(l)===he||i.charCodeAt(l)===Ie))Me(!0);else Me(!0)}if(h.length===0)return"{}";return`{
|
|
157
157
|
${h.join(`
|
|
158
158
|
`)}
|
|
159
|
-
}`}function
|
|
159
|
+
}`}function Ic(m,h){let d=l+m.length;while(d<a&&Ge(i.charCodeAt(d)))d++;for(let g=0;g<h.length;g++)if(d+g>=a||i.charCodeAt(d+g)!==h.charCodeAt(g))return!1;return d+h.length>=a||!Qe(i.charCodeAt(d+h.length))}function Ut(m,h,d){l+=d.length,y();let g="",w=i.charCodeAt(l);if(w===le||w===he){let A=l;S(w),g=i.slice(A,l)}else{g=j();while(l<a&&i.charCodeAt(l)===gt)l++,g+=`.${j()}`}y();let v=l<a&&i.charCodeAt(l)===U?Xi():"{}",R=`${h?"export ":""}declare ${d} ${g} ${v}`,P=tt(m),b=g.startsWith("'")||g.startsWith('"');return{kind:"module",name:g,text:R,isExported:h,source:b?g.slice(1,-1):void 0,leadingComments:P,start:m,end:l}}function Vo(m,h){Me();let d=p(h,l);if(d.charCodeAt(d.length-1)===re)d=d.slice(0,-1).trimEnd();if(!d)return;let g=Gt(d.charCodeAt(0));for(let A=1;g&&A<d.length;A++)g=Qe(d.charCodeAt(A));let w=tt(m);if(g){c.push({kind:"export",name:"default",text:`export default ${d};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:m,end:l});return}let v="__dtsx_default_export__",R=1;while(i.includes(v))v=`__dtsx_default_export_${R++}__`;let P=Fr(d)||Ne(d,!1),b=P==="unknown"&&gd(d)?`typeof ${d}`:P;c.push({kind:"variable",name:v,text:`declare const ${v}: ${b};`,isExported:!1,typeAnnotation:b,modifiers:["const"],start:m,end:l}),c.push({kind:"export",name:"default",text:`export default ${v};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:m,end:l})}while(l<a){if(y(),l>=a)break;let m=l,h=i.charCodeAt(l);if(h===105&&T("import"))c.push(xc(m));else if(h===101&&T("export")){l+=6,y();let d=i.charCodeAt(l);if(d===100&&T("default")){l+=7,y();let g=l,w=i.charCodeAt(l);if(w===102&&T("function")){let v=Tt(m,!0,!1,!0);if(v)c.push(v)}else if(w===97&&T("async")&&Go("async")!==re)if(l+=5,y(),T("function")){let v=Tt(m,!0,!0,!0);if(v)c.push(v)}else Vo(m,g);else if(w===99&&T("class")){let v=Rt(m,!0,!1,!0);c.push(v)}else if(w===97&&T("abstract")){if(l+=8,y(),T("class")){let v=Rt(m,!0,!0,!0);c.push(v)}}else Vo(m,g)}else if(d===116&&T("type")){let g=l;if(l+=4,y(),l<a&&i.charCodeAt(l)===U){Do();let w=p(m,l),v=tt(m);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Dr(w),leadingComments:v,start:m,end:l})}else if(l<a&&i.charCodeAt(l)===be){Io();let w=p(m,l);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Dr(w),start:m,end:l})}else{l=g;let w=Ji(m,!0);c.push(w)}}else if(d===105&&T("interface")){let g=Hi(m,!0);c.push(g)}else if(d===102&&T("function")){let g=Tt(m,!0,!1,!1);if(g)c.push(g)}else if(d===97&&T("async"))if(l+=5,y(),T("function")){let g=Tt(m,!0,!0,!1);if(g)c.push(g)}else Me();else if(d===99)if(T("class")){let g=Rt(m,!0,!1);c.push(g)}else if(T("const")){let g=l;if(l+=5,y(),T("enum")){l=g+5,y();let w=Vt(m,!0,!0);c.push(w)}else{l=g;let w=Ft(m,"const",!0);for(let v=0;v<w.length;v++)c.push(w[v])}}else Me();else if(d===97&&T("abstract")){if(l+=8,y(),T("class")){let g=Rt(m,!0,!0);c.push(g)}}else if(d===108&&T("let")){let g=Ft(m,"let",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else if(d===118&&T("var")){let g=Ft(m,"var",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else if(d===101&&T("enum")){let g=Vt(m,!0,!1);c.push(g)}else if(d===100&&T("declare"))l+=7,y(),Uo(m,!0);else if(d===110&&T("namespace")&&Re(9)){let g=Ut(m,!0,"namespace");c.push(g)}else if(d===109&&T("module")&&Re(6)){let g=Ut(m,!0,"module");c.push(g)}else if(d===U){Do();let g=p(m,l),w=g.includes("export type"),v=tt(m);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:w,source:Dr(g),leadingComments:v,start:m,end:l})}else if(d===be){Io();let g=p(m,l),w=tt(m);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:!1,source:Dr(g),leadingComments:w,start:m,end:l})}else{Me();let g=p(m,l);if(g)c.push({kind:"export",name:"",text:g,isExported:!0,start:m,end:l})}}else if(h===100&&T("declare"))l+=7,y(),Uo(m,!1);else if(h===105&&T("interface")){let d=Hi(m,!1);f.set(d.name,d)}else if(h===116&&T("type")){let d=Ji(m,!1);f.set(d.name,d),c.push(d)}else if(h===102&&T("function")){let d=Tt(m,!1,!1,!1);if(d)f.set(d.name,d);else Me()}else if(h===97)if(T("async")){let d=l;if(l+=5,y(),T("function")){let g=Tt(m,!1,!0,!1);if(g)f.set(g.name,g);else l=d,Me()}else l=d,Me()}else if(T("abstract"))if(l+=8,y(),T("class")){let d=Rt(m,!1,!1);f.set(d.name,d),c.push(d)}else Me();else l++,Me();else if(h===99)if(T("class")){let d=Rt(m,!1,!1);f.set(d.name,d),c.push(d)}else if(T("const")){let d=l;if(l+=5,y(),T("enum")){l=d+5,y();let g=Vt(m,!1,!0);f.set(g.name,g),c.push(g)}else{l=d;let g=Ft(m,"const",!1);for(let w=0;w<g.length;w++)f.set(g[w].name,g[w])}}else l++,Me();else if(h===101&&T("enum")){let d=Vt(m,!1,!1);f.set(d.name,d),c.push(d)}else if(h===108&&T("let")||h===118&&T("var")){let d=T("let")?"let":"var",g=Ft(m,d,!1);for(let w=0;w<g.length;w++)f.set(g[w].name,g[w])}else if(h===109&&T("module")&&Re(6)){let d=Ut(m,!1,"module");c.push(d)}else if(h===110&&T("namespace")&&Re(9)){let d=Ut(m,!1,"namespace");c.push(d)}else{let d=i.charCodeAt(l);if(d===re)l++;else if(d===le||d===he){if(S(d),l<a&&i.charCodeAt(l)===re)l++}else if(d===Ie){if(M(),l<a&&i.charCodeAt(l)===re)l++}else if(d===md){if(l++,j(),y(),l<a&&i.charCodeAt(l)===gt)l++,j(),y();if(l<a&&i.charCodeAt(l)===se)Y(se,xe)}else l++,Me()}}if(f.size>0)Cd(c,f);if(u.size>0){let m=new Map;for(let d of c)if(d.kind==="function")m.set(d.name,(m.get(d.name)||0)+1);let h=new Set;for(let[d,g]of m)if(g>1)h.add(d);if(h.size>0){let d=new Set;for(let g of h)for(let w=c.length-1;w>=0;w--)if(c[w].kind==="function"&&c[w].name===g&&u.has(w)){d.add(w);break}if(d.size>0){let g=[...d].sort((w,v)=>v-w);for(let w of g)c.splice(w,1)}}}return c;function Uo(m,h){if(T("function")){let d=Tt(m,h,!1,!1);if(d)c.push(d)}else if(T("async")){if(l+=5,y(),T("function")){let d=Tt(m,h,!0,!1);if(d)c.push(d)}}else if(T("class")){let d=Rt(m,h,!1);c.push(d)}else if(T("abstract")){if(l+=8,y(),T("class")){let d=Rt(m,h,!0);c.push(d)}}else if(T("interface")){let d=Hi(m,h);c.push(d)}else if(T("type")){let d=Ji(m,h);c.push(d)}else if(T("enum")){let d=Vt(m,h,!1);c.push(d)}else if(T("const")){let d=l;if(l+=5,y(),T("enum")){l=d+5,y();let g=Vt(m,h,!0);c.push(g)}else if(h){l=d;let g=Ft(m,"const",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else Me()}else if(T("let")||T("var"))if(h){let d=T("let")?"let":"var",g=Ft(m,d,!0);for(let w=0;w<g.length;w++)c.push(g[w])}else Me();else if(T("module")){let d=Ut(m,h,"module");c.push(d)}else if(T("namespace")){let d=Ut(m,h,"namespace");c.push(d)}else if(T("global")){l+=6,y();let d=`declare global ${l<a&&i.charCodeAt(l)===U?Xi():"{}"}`,g=tt(m);c.push({kind:"module",name:"global",text:d,isExported:!1,leadingComments:g,start:m,end:l})}else Me()}}function dl(e,t){let r=0,n=e.length;while(r<n){let i=e.charCodeAt(r);if(i>=65&&i<=90||i>=97&&i<=122||i===95||i===36||i>127){let o=r;r++;while(r<n){let s=e.charCodeAt(r);if(s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===95||s===36||s>127)r++;else break}t.add(e.substring(o,r))}else r++}}function ml(e,t){let r=0;while(r<e.length){let n=e.charCodeAt(r);if(n===le||n===he||n===Ie){let u=n;r++;while(r<e.length)if(e.charCodeAt(r)===Xe)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(n===X&&e.charCodeAt(r+1)===X){r+=2;while(r<e.length&&e.charCodeAt(r)!==de&&e.charCodeAt(r)!==Se)r++;continue}if(n===X&&e.charCodeAt(r+1)===be){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!Gt(n)){r++;continue}let i=r++;while(r<e.length&&Qe(e.charCodeAt(r)))r++;let o=i-1,s=r;while(o>=0&&Ge(e.charCodeAt(o)))o--;while(s<e.length&&Ge(e.charCodeAt(s)))s++;let a=o>=0?e.charCodeAt(o):0,c=s<e.length?e.charCodeAt(s):0,f=i>=3&&e.slice(i-3,i)==="...";if(c===ft||a===gt&&!f)continue;if(c===se&&(a===U||a===ut))continue;t.add(e.slice(i,r))}}function Cd(e,t){let r=new Set,n=new Set;for(let s of e)n.add(s.name);let i=new Set,o=[];for(let s=0;s<e.length;s++){let a=e[s];if(a.kind!=="import"){if(o.push(a.text),dl(a.text,i),typeof a.value==="string")ml(a.value,i)}}for(;;){let s=[];for(let[f,u]of t){if(r.has(f))continue;if(i.has(f)){if(!n.has(f))s.push(u),n.add(f);r.add(f)}}if(s.length===0)break;s.sort((f,u)=>(f.start??1/0)-(u.start??1/0));let a=[],c=0;for(let f=0;f<e.length;f++){let u=e[f].start??1/0;while(c<s.length&&(s[c].start??1/0)<=u)a.push(s[c++]);a.push(e[f])}while(c<s.length)a.push(s[c++]);e.length=0;for(let f=0;f<a.length;f++)e.push(a[f]);for(let f of s)if(f.kind!=="import"){if(o.push(f.text),dl(f.text,i),typeof f.value==="string")ml(f.value,i)}}}var Oe=32,ke=9,de=10,Se=13,X=47,be=42,le=39,he=34,Ie=96,Xe=92,U=123,Q=125,se=40,xe=41,Ee=91,Pe=93,ve=60,ue=62,re=59,ft=58,$e=61,ut=44,gt=46,Li=63,Wi=35,md=64,pl=36,pd=95,So;var wl=ge(()=>{bo();So=["public","protected","private","readonly","override"]});function vl(e,t,r=!0,n=!1){if(Va(t))e=za(e);else if(Ja(t))e=qa(e);let i=dr(e),o=`${t}:${r?1:0}:${n?1:0}`,s=ur.get(o);if(s&&s.contentHash===i)return s.lastAccess=++El,s.declarations;let a=n?gl(e,t,r):yl(e,t,r);if(ur.set(o,{declarations:a,contentHash:i,lastAccess:++El}),ur.size>wd){let c=Math.max(1,Math.ceil(ur.size*0.1)),f=[];for(let[u,l]of ur)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)ur.delete(f[u][0])}return a}var wd=100,El=0,ur;var bl=ge(()=>{ao();Ya();wl();sn();ur=new Map});function Sl(e,t,r=!0,n=!1){return vl(e,t,r,n)}var $l=ge(()=>{bl()});async function Ed(){if(Gi!==null)return Gi;try{return Dt=await import("prettier"),Gi=!0,!0}catch{return Gi=!1,!1}}async function vd(e,t){if(!Dt)return null;try{if(t&&Dt.resolveConfig){let r=await Dt.resolveConfig(t);if(r)return r}if(e&&Dt.resolveConfig){let r=await Dt.resolveConfig(e);if(r)return r}return null}catch{return null}}async function bd(e,t){if(!Dt)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return Dt.format(e,r)}function Sd(e,t={}){let{indentSize:r=2,useTabs:n=!1,maxLineWidth:i=100,trailingNewline:o=!0,normalizeWhitespace:s=!0,sortImports:a=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(r);if(f.indexOf(`\r
|
|
160
160
|
`)!==-1)f=f.replace(/\r\n/g,`
|
|
161
161
|
`);if(s){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
|
|
162
162
|
|
|
163
163
|
|
|
164
164
|
`)!==-1)f=f.replace(/\n{3,}/g,`
|
|
165
165
|
|
|
166
|
-
`);f
|
|
166
|
+
`);f=$d(f,u)}if(a||c)f=Ad(f,{sort:a,group:c});if(i>0)f=Td(f,i,u);if(o&&!f.endsWith(`
|
|
167
167
|
`))f+=`
|
|
168
|
-
`;return f}function
|
|
168
|
+
`;return f}function $d(e,t){let r=e.split(`
|
|
169
169
|
`),n=[];for(let i of r){let o=i.match(/^(\s*)(.*)$/);if(!o){n.push(i);continue}let[,s,a]=o;if(!a){n.push("");continue}let c=s.replace(/\t/g," ").length,f=Math.floor(c/2);n.push(t.repeat(f)+a)}return n.join(`
|
|
170
|
-
`)}function
|
|
171
|
-
`),n=[],i=[],o=!1,s=0;for(let c=0;c<r.length;c++){let f=r[c],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){o=!0,s=c;let l=u[1];n.push({line:f,source:u[2],isType:l.startsWith("import type ")||l.startsWith("import type\t")})}else if(o&&f.trim()==="")continue;else{if(o)o=!1;i.push(f)}}if(n.length===0)return e;if(t.sort)n.sort((c,f)=>{if(c.isType!==f.isType)return c.isType?1:-1;return
|
|
172
|
-
`)}function
|
|
173
|
-
`),i=[];for(let o of n){if(o.length<=t){i.push(o);continue}if(o.trimStart().startsWith("import ")){i.push(o);continue}let s=o.match(/^(\s*)/)?.[1]||"",a=s+r,c=
|
|
174
|
-
`)}function
|
|
170
|
+
`)}function Ad(e,t){let r=e.split(`
|
|
171
|
+
`),n=[],i=[],o=!1,s=0;for(let c=0;c<r.length;c++){let f=r[c],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){o=!0,s=c;let l=u[1];n.push({line:f,source:u[2],isType:l.startsWith("import type ")||l.startsWith("import type\t")})}else if(o&&f.trim()==="")continue;else{if(o)o=!1;i.push(f)}}if(n.length===0)return e;if(t.sort)n.sort((c,f)=>{if(c.isType!==f.isType)return c.isType?1:-1;return xd(c.source,f.source)});let a;if(t.group){let c=[],f=[],u=[],l=[],p=[];for(let C=0;C<n.length;C++){let E=n[C],y=E.source;if(y.charCodeAt(0)===46)p.push(E);else if(y.startsWith("node:"))c.push(E);else if(y.charCodeAt(0)===64)l.push(E);else if(y.includes("/"))u.push(E);else f.push(E)}a=[...c.map((C)=>C.line),...c.length>0&&f.length>0?[""]:[],...f.map((C)=>C.line),...(c.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((C)=>C.line),...l.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...l.map((C)=>C.line),...p.length>0?[""]:[],...p.map((C)=>C.line)]}else a=n.map((c)=>c.line);return[...a,"",...i].join(`
|
|
172
|
+
`)}function xd(e,t){let r=e.startsWith("node:"),n=t.startsWith("node:");if(r!==n)return r?-1:1;let i=e.startsWith("."),o=t.startsWith(".");if(i!==o)return i?1:-1;return e.localeCompare(t)}function Td(e,t,r){let n=e.split(`
|
|
173
|
+
`),i=[];for(let o of n){if(o.length<=t){i.push(o);continue}if(o.trimStart().startsWith("import ")){i.push(o);continue}let s=o.match(/^(\s*)/)?.[1]||"",a=s+r,c=Pd(o,s,a);if(c){i.push(...c);continue}if(o.includes("{")&&o.includes("}")){let f=Od(o,t,s,a);i.push(...f);continue}if(o.includes(" | ")){let f=kd(o,t,s,a);i.push(...f);continue}i.push(o)}return i.join(`
|
|
174
|
+
`)}function Pd(e,t,r){let n=e.match(Rd);if(!n)return null;let[,i,o,s,a]=n,c=s.split(",").map((l)=>l.trim()).filter(Boolean);if(c.length<=1)return[e];let f=`${t}${i}${o??""} {`,u=a?`${t}} ${a};`:`${t}};`;return[f,...c.map((l)=>`${r}${l},`),u]}function Od(e,t,r,n){let i=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!i)return[e];let[,,o,s,a,c]=i,f=a.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${r}${o}${s}`,...f.map((u)=>`${n}${u.trim()};`),`${r}${c.trim()}`]}function kd(e,t,r,n){let i=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!i)return[e];let[,,o,s]=i,a=s.split(/\s*\|\s*/).filter((c)=>c.trim());if(a.length<=2)return[e];return[`${r}${o}`,...a.map((c,f)=>`${n}${f>0?"| ":" "}${c.trim()}`)]}async function Al(e,t={},r){let n=[];if(t.usePrettier!==!1){if(await Ed())try{let i={...await vd(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await bd(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:Sd(e,t.builtIn),usedPrettier:!1,warnings:n.length>0?n:void 0}}var Gi=null,Dt=null,Rd;var xl=ge(()=>{Rd=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/});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)},o=await n.onBeforeFile(i);if(typeof o==="string")r=o}return r}async runOnDeclarations(e,t,r){let n=r;for(let i of this.plugins)if(i.onDeclarations){let o={filePath:e,sourceCode:t,declarations:n,config:this.config,log:this.createLogger(i.name)},s=await i.onDeclarations(o);if(s)n=s}return n}async runOnAfterFile(e,t,r){let n=r;for(let i of this.plugins)if(i.onAfterFile){let o={filePath:e,sourceCode:t,content:n,config:this.config,log:this.createLogger(i.name)},s=await i.onAfterFile(o);if(typeof s==="string")n=s}return n}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,r){for(let n of this.plugins)if(n.onError){let i={filePath:t,sourceCode:r,config:this.config,log:this.createLogger(n.name)};await n.onError(e,i)}}}function Md(e){return e}var Ky,zy;var Tl=ge(()=>{Ky=new ji;zy=Md({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(e)=>e.declarations.filter((t)=>{if(t.leadingComments){if(t.leadingComments.some((r)=>r.includes("@internal")))return e.log.debug(`Stripping internal declaration: ${t.name}`),!1}return!0})})});function Ol(e,t={}){let{lineEnding:r="lf",trailingNewline:n=!0,maxBlankLines:i=1,trimTrailingWhitespace:o=!0,normalizeIndentation:s=!0,indent:a={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:l=!0}=t,p=e;if(p=Fd(p,r),f?.enabled!==!1)p=Gd(p,f||{});if(c)p=jd(p,c);if(o)p=Nd(p);if(p=Ld(p,i),s)p=Bd(p,a);if(n||l)p=Wd(p);return p}function Fd(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
|
|
175
175
|
`)!==-1)r=r.replace(/\r\n/g,`
|
|
176
176
|
`);if(r.indexOf("\r")!==-1)r=r.replace(/\r/g,`
|
|
177
177
|
`)}if(t==="crlf")r=r.replace(/\n/g,`\r
|
|
178
|
-
`);return r}function
|
|
178
|
+
`);return r}function Nd(e){return e.split(`
|
|
179
179
|
`).map((t)=>t.replace(/[\t ]+$/,"")).join(`
|
|
180
|
-
`)}function
|
|
181
|
-
`.repeat(t+1))}function
|
|
182
|
-
`}function
|
|
180
|
+
`)}function Ld(e,t){let r=new RegExp(`\\n{${t+2},}`,"g");return e.replace(r,`
|
|
181
|
+
`.repeat(t+1))}function Wd(e){return`${e.replace(/\s+$/,"")}
|
|
182
|
+
`}function Bd(e,t){let{style:r="spaces",size:n=2}=t,i=r==="tabs"?"\t":" ".repeat(n),o=e.split(`
|
|
183
183
|
`),s=[];for(let a of o){let c=a.match(/^([\t ]*)(.*)$/);if(!c){s.push(a);continue}let[,f,u]=c;if(!u){s.push("");continue}let l=f.replace(/\t/g," "),p=Math.floor(l.length/2);s.push(i.repeat(p)+u)}return s.join(`
|
|
184
|
-
`)}function
|
|
185
|
-
`),s=[],a=[],c=-1;for(let E=0;E<o.length;E++){let y=o[E],x=
|
|
186
|
-
`)}function
|
|
187
|
-
`),s=[],a=[],c=[],f=null,u=0,l=!0,p=!1,C=[];for(let x=0;x<o.length;x++){let S=o[x],M=S.trim(),D=u,O=M.startsWith("///"),H=D===0&&!O&&(M.startsWith("//")||M.startsWith("/*"));if(p||H){if(C.push(S),!p&&M.startsWith("/*")&&!M.includes("*/"))p=!0;else if(p&&M.includes("*/"))p=!1;continue}if(D===0&&C.length>0&&M===""){C.push(S);continue}u+=(S.match(/\{/g)||[]).length,u-=(S.match(/\}/g)||[]).length;let K=
|
|
188
|
-
`)}function
|
|
189
|
-
`;r++}r=Math.min(r+2,e.length);continue}if(i===44){let o=r+1;while(o<e.length){while(o<e.length&&e.charCodeAt(o)<=32)o++;if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===47){o+=2;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===42){o+=2;while(o+1<e.length&&!(e.charCodeAt(o)===42&&e.charCodeAt(o+1)===47))o++;o=Math.min(o+2,e.length);continue}break}let s=e.charCodeAt(o);if(s===93||s===125){r++;continue}}t+=e[r++]}return t}var Il=()=>{};var Fl;var Nl=ge(()=>{Fl=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 Ll(e,t={strings:!0}){let r="",n=0;while(n<e.length){let i=e.slice(n,n+2);if(i==="//"){let s=e.indexOf(`
|
|
184
|
+
`)}function Gd(e,t){let{groups:r=Id,separateGroups:n=!0,alphabetize:i=!0}=t,o=e.split(`
|
|
185
|
+
`),s=[],a=[],c=-1;for(let E=0;E<o.length;E++){let y=o[E],x=Rl(y);if(x)s.push({line:y,source:x.source,group:x.group,isType:x.isType}),c=E;else if(s.length>0&&y.trim()==="")continue;else if(s.length>0||y.trim()!==""){if(s.length===0||E>c+1)a.push(y)}}if(s.length===0)return e;let f=new Map;for(let E of r)f.set(E,[]);for(let E of s)(f.get(E.group)||f.get("external")||[]).push(E);if(i)for(let[,E]of f)E.sort((y,x)=>{if(y.isType!==x.isType)return y.isType?1:-1;return y.source.localeCompare(x.source)});let u=[],l=null;for(let E of r){let y=f.get(E)||[];if(y.length===0)continue;if(n&&l!==null)u.push("");for(let x of y)u.push(x.line);l=E}let p=o.slice(0,o.findIndex((E)=>Rl(E)!==null)),C=a;while(C.length>0&&C[0].trim()==="")C.shift();return[...p,...u,"",...C].join(`
|
|
186
|
+
`)}function Rl(e){let t=e.trim(),r=t.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!r){let o=t.match(/^import\s+['"]([^'"]+)['"]/);if(o)return{source:o[1],group:Pl(o[1]),isType:!1};return null}let n=!!r[1],i=r[2];return{source:i,group:n?"type":Pl(i),isType:n}}function Pl(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 jd(e,t){let{kinds:r=Dd,alphabetize:n=!1,groupExports:i=!0}=t,o=e.split(`
|
|
187
|
+
`),s=[],a=[],c=[],f=null,u=0,l=!0,p=!1,C=[];for(let x=0;x<o.length;x++){let S=o[x],M=S.trim(),D=u,O=M.startsWith("///"),H=D===0&&!O&&(M.startsWith("//")||M.startsWith("/*"));if(p||H){if(C.push(S),!p&&M.startsWith("/*")&&!M.includes("*/"))p=!0;else if(p&&M.includes("*/"))p=!1;continue}if(D===0&&C.length>0&&M===""){C.push(S);continue}u+=(S.match(/\{/g)||[]).length,u-=(S.match(/\}/g)||[]).length;let K=_d(M);if(l&&K&&K.kind!=="import"&&!M.startsWith("//")&&!M.startsWith("/*"))l=!1;if(l){if(C.length>0){if(K?.kind==="import"||!K)a.push(...C),C.length=0}a.push(S);continue}if(K&&u<=1){if(f)s.push(f);f={lines:C.length>0?[...C,S]:[S],kind:K.kind,name:K.name,isExport:K.isExport},C.length=0}else if(f)f.lines.push(S);else{if(M==="")continue;c.push(S)}}if(f)s.push(f);if(C.length>0)c.push(...C);s.sort((x,S)=>{if(i&&x.isExport!==S.isExport)return x.isExport?-1:1;let M=r.indexOf(x.kind),D=r.indexOf(S.kind),O=M>=0?M:r.length,H=D>=0?D:r.length;if(O!==H)return O-H;if(n)return x.name.localeCompare(S.name);return 0});let E=[...a],y=null;for(let x of s){if(y!==null&&x.kind!==y)E.push("");E.push(...x.lines),y=x.kind}if(c.length>0)E.push(""),E.push(...c);return E.join(`
|
|
188
|
+
`)}function _d(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 Dd,Id;var kl=ge(()=>{Dd=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],Id=["builtin","external","scoped","internal","parent","sibling","index","type"]});function Hd(e){switch(e){case"strict":return Ud;case"readonly":return Kd;case"simplified":return zd;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 Dl{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...Vd);if(e.presets)for(let t of e.presets)this.rules.push(...Hd(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(Jd,"\\$&"),r.global?"g":""):r.pattern;e[t]={rule:r,regex:n}}this.compiled=e}map(e,t={}){let r=!t.declarationName&&!t.declarationKind&&!t.filePath&&!t.isReturnType&&!t.isParameterType&&!t.isPropertyType?e:`${e}\x00${t.declarationName??""}\x00${t.declarationKind??""}\x00${t.filePath??""}\x00${t.isReturnType?"r":""}${t.isParameterType?"p":""}${t.isPropertyType?"P":""}`,n=this.cache.get(r);if(n!==void 0)return n;let i=e,o=null;for(let s=0;s<this.compiled.length;s++){let{rule:a,regex:c}=this.compiled[s];if(a.condition){if(!o)o={type:e,...t};if(!a.condition(o))continue}if(c.lastIndex=0,c.test(i)){if(c.lastIndex=0,i=i.replace(c,a.replacement),c.lastIndex=0,!a.global)break}}if(this.cache.size>=Ml){let s=Math.ceil(Ml*0.1),a=0;for(let c of this.cache.keys()){if(a++>=s)break;this.cache.delete(c)}}return this.cache.set(r,i),i}mapAll(e,t={}){return e.map((r)=>this.map(r,{...t,type:r}))}addRule(e){this.rules.push(e),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let t=this.rules.length;return this.rules=this.rules.filter((r)=>{let n=typeof r.pattern==="string"?r.pattern:r.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?n!==e:!e.test(n)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function _i(e={rules:[]}){return new Dl(e)}function Il(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>`: ${t.map(i.trim(),r)}`)}var Vd,Ud,Kd,zd,Jd,Ml=2048,qy,Yy;var Fl=ge(()=>{Vd=[{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}],Ud=[{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}],Kd=[{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}],zd=[{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}];Jd=/[.*+?^${}()|[\]\\]/g;qy=_i({rules:[]}),Yy=_i({rules:[],presets:["strict"]})});function Nl(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+=`
|
|
189
|
+
`;r++}r=Math.min(r+2,e.length);continue}if(i===44){let o=r+1;while(o<e.length){while(o<e.length&&e.charCodeAt(o)<=32)o++;if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===47){o+=2;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===42){o+=2;while(o+1<e.length&&!(e.charCodeAt(o)===42&&e.charCodeAt(o+1)===47))o++;o=Math.min(o+2,e.length);continue}break}let s=e.charCodeAt(o);if(s===93||s===125){r++;continue}}t+=e[r++]}return t}var Ll=()=>{};var Wl;var Bl=ge(()=>{Wl=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 s=e.indexOf(`
|
|
190
190
|
`,n),a=s===-1?e.length:s;r+=" ".repeat(a-n),n=a;continue}if(i==="/*"){let s=e.indexOf("*/",n+2),a=s===-1?e.length:s+2;for(let c=n;c<a;c++)r+=e[c]===`
|
|
191
191
|
`?`
|
|
192
192
|
`:" ";n=a;continue}let o=e[n];if(t.strings&&(o==='"'||o==="'"||o==="`")){let s=o;r+=" ",n++;while(n<e.length){if(e[n]==="\\"){r+=" ",n+=2;continue}if(e[n]===s){r+=" ",n++;break}r+=e[n]===`
|
|
193
193
|
`?`
|
|
194
|
-
`:" ",n++}continue}r+=o,n++}return r}function
|
|
194
|
+
`:" ",n++}continue}r+=o,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 Zd(e){let t=new Set;for(let r of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let n=r[1],i=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(n);if(i)t.add(i[1]);let o=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let a of o.split(",")){let c=a.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let s=/\{([\s\S]*?)\}/.exec(n);if(s)for(let a of s[1].split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let f=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(c);t.add(f?f[1]:c.split(/\s+/)[0])}}for(let r of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(r[1]);return t}function Xd(e){let t=new Set,r=(i)=>{for(let o of i.split(",")){let s=o.trim().split(/\s+|=/)[0]?.trim();if(s&&/^[A-Za-z_$][\w$]*$/.test(s))t.add(s)}},n=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let i of e.matchAll(n))r(i[1]);for(let i of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))r(i[1]);for(let i of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))t.add(i[1]);for(let i of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))t.add(i[1]);return t}function Qd(e){let t=new Map,r=(i)=>{let o=1;for(let s=0;s<i&&s<e.length;s++)if(e.charCodeAt(s)===10)o++;return o},n=(i,o,s)=>{for(let a of i.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=a[1];if(t.has(c))continue;let f=i.slice(a.index+c.length);if(/^\s*\??:/.test(f))continue;t.set(c,{line:r(o),context:s.trim().slice(0,120)})}};for(let i of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))n(i[1],i.index+i[0].indexOf("="),i[0]);for(let i of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/:\s*([^;,){}\n=]+)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/<([^<>()]*)>/g))n(i[1],i.index,i[0]);return t}function jl(e){let t=Gl(e),r=Gl(e,{strings:!1}),n=new Set([...Yd(t),...Zd(r),...Xd(t),...Wl,...qd]),i=[];for(let[o,s]of Qd(t)){if(n.has(o))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${o}\\b`).test(t))continue;i.push({name:o,line:s.line,context:s.context})}return i.sort((o,s)=>o.line-s.line||o.name.localeCompare(s.name))}var qd;var _l=ge(()=>{Bl();qd=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function It(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 Ul(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},o=0,s=0,a=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),l=e.charCodeAt(f+1);if(a!==-1){if(u===42&&l===47)r.push({start:a,end:f+2}),a=-1,f++;continue}if(o){if(u===92)f++;else if(u===o)r.push({start:s,end:f+1}),o=0;continue}if(u===47&&l===42){a=f,f++;continue}if(u===47&&l===47){let C=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:C,end:f});continue}if(u===39||u===34||u===96){o=u,s=f;continue}let p=e[f];if(p==="("||p==="["||p==="{")n.push({char:p,offset:f});else if(i[p]){let C=n.pop();if(!C||C.char!==i[p])t.push({...It(e,f),message:`Unexpected closing delimiter ${p}`,code:"DTSX1004"})}}if(o)t.push({...It(e,s),message:"Unterminated string literal",code:"DTSX1002"});if(a!==-1)t.push({...It(e,a),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...It(e,f.offset),message:`Unclosed delimiter ${f.char}`,code:"DTSX1001"});let c=[[/\b(?:interface|class|enum)\s*(?=[{=])/g,"Declaration name expected"],[/\bfunction\s*(?=\()/g,"Function name expected"],[/\(\s*:/g,"Parameter name expected"]];for(let[f,u]of c)for(let l of e.matchAll(f)){if(r.some((p)=>l.index>=p.start&&l.index<p.end))continue;t.push({...It(e,l.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((l)=>f.index>=l.start&&f.index<l.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...It(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...tm(e,r)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function tm(e,t){let r=[],n=(i)=>t.some((o)=>i>=o.start&&i<o.end);for(let i of e.matchAll(/\b(import|export)\s+(?:type\s+)?\{/g)){let o=i.index;if(n(o))continue;let s=o+i[0].length-1,a=-1;for(let u=s+1;u<e.length;u++){if(n(u))continue;let l=e[u];if(l==="{"){a=-2;break}if(l==="}"){a=u;break}}if(a<0)continue;let c=e.slice(s+1,a);if(!c.trim())continue;let f=s+1;for(let u of c.split(",")){let l=u.trim();if(l){let p=f+u.indexOf(l);if(l.includes(";"))r.push({...It(e,p),message:`Unexpected ';' in ${i[1]} clause \u2014 specifiers are separated by ','`,code:"DTSX1006"});else if(!em.test(l))r.push({...It(e,p),message:`Invalid ${i[1]} specifier '${l}'`,code:"DTSX1006"})}f+=u.length+1}}return r}var Vl,em;var Kl=ge(()=>{Vl=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,em=new RegExp(`^(?:type\\s+)?${Vl}(?:\\s+as\\s+${Vl})?$`,"u")});import{statSync as rm}from"fs";import{readFile as im,readdir as c0}from"fs/promises";import{createRequire as nm}from"module";import{dirname as om,isAbsolute as zl,join as sm,resolve as Hl}from"path";import am from"process";function Ao(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function Ar(e,t,r="lf"){let n=t.replace(/\r\n/g,`
|
|
195
195
|
`);if(!n.endsWith(`
|
|
196
196
|
`))n+=`
|
|
197
197
|
`;if(r==="crlf")n=n.replace(/\n/g,`\r
|
|
198
|
-
`);await
|
|
198
|
+
`);await zo(e,n)}function $o(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(sm(e,"tsconfig.json"));for(let r of t)try{if(rm(r).isFile())return r}catch{}return null}function lm(e,t){if(zl(e)||e.startsWith("."))return $o(Hl(om(t),e));let r=nm(t);for(let n of[e,`${e}/tsconfig.json`])try{let i=$o(r.resolve(n));if(i)return i}catch{}return null}async function Jl(e,t){let r=$o(e);if(!r||t.has(r))return;t.add(r);let n=await im(r,"utf8"),i=JSON.parse(Nl(n)),o=typeof i.extends==="string"?[i.extends]:i.extends??[],s;for(let a of o){let c=lm(a,r);if(!c)continue;let f=await Jl(c,t);if(f!==void 0)s=f}return i.compilerOptions?.isolatedDeclarations??s}async function ql(e){try{let t=e?.cwd||am.cwd(),r=e?.tsconfigPath||"tsconfig.json",n=zl(r)?r:Hl(t,r);return await Jl(n,new Set)??!1}catch{return!1}}function Yl(e,t){let r={isValid:!0,errors:[]};for(let n of Ul(e))r.errors.push({line:n.line,column:n.column,message:n.message,code:n.code});for(let n of jl(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 Zl(e,t,r){if(e===t)return"";let n=e.split(`
|
|
199
199
|
`),i=t.split(`
|
|
200
200
|
`),o=new Map,s=new Map;for(let u=0;u<n.length;u++)o.set(n[u],(o.get(n[u])??0)+1);for(let u=0;u<i.length;u++)s.set(i[u],(s.get(i[u])??0)+1);let a=[],c=[];for(let[u,l]of o){let p=l-(s.get(u)??0);for(let C=0;C<p;C++)a.push(u)}for(let[u,l]of s){let p=l-(o.get(u)??0);for(let C=0;C<p;C++)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(`
|
|
201
|
-
`)}function
|
|
201
|
+
`)}function Xl(e,t,r,n){let i=e.split(`
|
|
202
202
|
`),o=[];function s(l){let p="",C=l<0?-l<<1|1:l<<1;do{let E=C&31;if(C>>>=5,C>0)E|=32;p+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[E]}while(C>0);return p}let a=0,c=0,f=0,u=n.split(`
|
|
203
|
-
`).length;for(let l=0;l<i.length;l++){if(i[l].trim()===""){o.push("");continue}a=0;let p=Math.min(l,u-1),C=[],E=0-a,y=0,x=p-c,S=0-f;C.push(s(E)+s(y)+s(x)+s(S)),a=0,c=p,f=0,o.push(C.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[n],mappings:o.join(";")}}function
|
|
204
|
-
${
|
|
205
|
-
`}var
|
|
206
|
-
`){let i=r,o=n;while(i<o&&(e[i]===" "||e[i]==="\t"||e[i]==="\r"))i++;while(o>i&&(e[o-1]===" "||e[o-1]==="\t"||e[o-1]==="\r"))o--;let s=e.slice(i,o);if(r=n+1,s.startsWith("///")){if(s.indexOf("<")===-1)continue;if(
|
|
203
|
+
`).length;for(let l=0;l<i.length;l++){if(i[l].trim()===""){o.push("");continue}a=0;let p=Math.min(l,u-1),C=[],E=0-a,y=0,x=p-c,S=0-f;C.push(s(E)+s(y)+s(x)+s(S)),a=0,c=p,f=0,o.push(C.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[n],mappings:o.join(";")}}function Ql(e,t){return`${e}
|
|
204
|
+
${Ao()}${t}
|
|
205
|
+
`}var ec=ge(()=>{Ll();Lr();_l();Kl()});function hm(e){let t=[],r=0;for(let n=0;n<=e.length;n++)if(n===e.length||e[n]===`
|
|
206
|
+
`){let i=r,o=n;while(i<o&&(e[i]===" "||e[i]==="\t"||e[i]==="\r"))i++;while(o>i&&(e[o-1]===" "||e[o-1]==="\t"||e[o-1]==="\r"))o--;let s=e.slice(i,o);if(r=n+1,s.startsWith("///")){if(s.indexOf("<")===-1)continue;if(cm.test(s)||fm.test(s)||um.test(s))t.push(s)}else if(s===""||s.startsWith("//"))continue;else break}return t}function dm(e){if(e.includes(`
|
|
207
207
|
`))return`/**
|
|
208
208
|
* ${e}
|
|
209
209
|
*/
|
|
210
210
|
`;return`/** ${e} */
|
|
211
|
-
`}function
|
|
211
|
+
`}function mm(e){let t=e.indexOf("{");if(t===-1)return-1;let r=e.indexOf("<");if(r===-1||r>t)return t;let n=0,i=!1,o="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";if(!i&&(a==='"'||a==="'"||a==="`"))i=!0,o=a;else if(i&&a===o&&c!=="\\")i=!1;if(!i){if(a==="<")n++;else if(a===">")n--;else if(a==="{"&&n===0)return s}}return-1}function pm(e,t=!0){return At(e.leadingComments,t)+e.text}function tc(e,t=!0){let r=At(e.leadingComments,t);if(e.typeAnnotation&&!e.value)return r+e.text;let n="";if(e.isExported)n+="export ";n+="declare ";let i=e.modifiers?.[0]||"const";n+=`${i} `,n+=e.name;let{typeAnnotation:o,value:s}=e,a=!o&&s?Ni(s):null;if(a)o=a;else if(!o&&s&&s.trim().endsWith("as const"))o=Ne(s,!0);else if(!o&&s&&i==="const"){let f=s.trim(),u=f.startsWith("{")||f.startsWith("[");if(u)Co();o=Ne(s,!u)}else if(!o&&s)o=Ne(s,i==="const");if(!o)o="unknown";let c="";if(t&&s&&!e.typeAnnotation&&!s.trim().endsWith("as const")){let f=s.trim();if(i!=="const"){if((o==="string"||o==="number"||o==="boolean")&&f.length>0)c=`@defaultValue ${f}`}else if(f.startsWith("{")||f.startsWith("[")){let u=wo();if(u)if(u.includes(`
|
|
212
212
|
`))c=`@defaultValue
|
|
213
213
|
* \`\`\`ts
|
|
214
214
|
${u.split(`
|
|
215
215
|
`).map((l)=>` * ${l}`).join(`
|
|
216
216
|
`)}
|
|
217
|
-
* \`\`\``;else c=`@defaultValue \`${u}\``}}else if(t&&s&&e.typeAnnotation&&
|
|
217
|
+
* \`\`\``;else c=`@defaultValue \`${u}\``}}else if(t&&s&&e.typeAnnotation&&hl(e.typeAnnotation)){Co();let f=s.trim(),u=f.endsWith("as const")?f.slice(0,-8).trim():f;Ne(u,!1);let l=wo();if(l)if(l.includes(`
|
|
218
218
|
`))c=`@defaultValue
|
|
219
219
|
* \`\`\`ts
|
|
220
220
|
${l.split(`
|
|
221
221
|
`).map((p)=>` * ${p}`).join(`
|
|
222
222
|
`)}
|
|
223
|
-
* \`\`\``;else c=`@defaultValue \`${l}\``}if(c=
|
|
223
|
+
* \`\`\``;else c=`@defaultValue \`${l}\``}if(c=go(c),n+=`: ${o};`,c&&r&&r.includes("@defaultValue"))c="";if(c&&r){let f=r.trimEnd(),u=f.lastIndexOf("*/");if(u!==-1){let l=f.slice(0,u).trimEnd();if(l.startsWith("/** ")&&!l.includes(`
|
|
224
224
|
`))l=`/**
|
|
225
225
|
* ${l.slice(4)}`;return`${l}
|
|
226
226
|
* ${c}
|
|
@@ -229,28 +229,28 @@ ${l.split(`
|
|
|
229
229
|
* ${f.replace(/^\/\/\s*/,"")}
|
|
230
230
|
* ${c}
|
|
231
231
|
*/
|
|
232
|
-
${n}`}if(c)return`${
|
|
233
|
-
`;i+=j[T]}}}let s=[],a=[],c=[],f=[],u=[],l=[],p=[],C=[],E=[];for(let I of e){let j=I.kind;switch(j){case"import":s.push(I);break;case"function":a.push(I);break;case"variable":c.push(I);break;case"interface":f.push(I);break;case"type":u.push(I);break;case"class":l.push(I);break;case"enum":p.push(I);break;case"module":C.push(I);break;case"export":E.push(I);break;case"namespace":C.push(I);break;case"unknown":break;default:
|
|
234
|
-
`));for(let T of f)if(j.has(T.name))H.add(T.name)}}let K=[];if(s.length>0){let I=new Set,j=[];for(let V of a)if(V.isExported)j.push(V.text);for(let V of c)if(j.push(V.text),V.typeAnnotation)j.push(V.typeAnnotation);else if(V.isExported&&V.value)j.push(
|
|
235
|
-
`);if(T&&O.size>0){let V=
|
|
232
|
+
${n}`}if(c)return`${dm(c)}${n}`;return r+n}function gm(e,t=!0){let r=At(e.leadingComments,t),n=e.text;if(n.startsWith("export declare interface")||n.startsWith("declare interface"))return r+n;let i="";if(e.isExported)i+="export ";if(i+="declare interface ",i+=e.name,e.generics)i+=e.generics;if(e.extends)i+=` extends ${e.extends}`;let o=mm(e.text);if(o!==-1)i+=` ${e.text.slice(o)}`;else i+=" {}";return r+i}function ym(e,t=!0){let r=At(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return r+e.text;let n="";if(e.isExported)n+="export ";if(!e.isExported&&!e.text.includes(" from "))n+="declare ";let i=e.text.indexOf("type ");if(i!==-1){let s=e.text.slice(i),a=s.length;while(a>0&&(s.charCodeAt(a-1)===59||s.charCodeAt(a-1)===32||s.charCodeAt(a-1)===10||s.charCodeAt(a-1)===13))a--;if(a<s.length)s=s.slice(0,a);n+=s}else{if(n+=`type ${e.name}`,e.generics)n+=e.generics;n+=" = any"}let o=n.trimEnd();if(!o.endsWith(";")&&!o.endsWith("}"))n+=";";return r+n}function Cm(e,t=!0){return At(e.leadingComments,t)+e.text}function wm(e,t=!0){let r=At(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 Em(e,t=!0){let r=At(e.leadingComments,t);if(e.text.startsWith("declare global"))return r+e.text;if(e.source||(e.name.startsWith('"')||e.name.startsWith("'")||e.name.startsWith("`"))){let o="declare module ";o+=e.name;let s=e.text.indexOf("{");if(s!==-1)o+=` ${e.text.slice(s)}`;else o+=" {}";return r+o}let n="";if(e.isExported)n+="export ";if(!e.modifiers?.includes("declare"))n+="declare ";n+="namespace ",n+=e.name;let i=e.text.indexOf("{");if(i!==-1)n+=` ${e.text.slice(i)}`;else n+=" {}";return r+n}function vm(e){let t=jt.get(e);if(t)return jt.delete(e),jt.set(e,t),t;return null}function rc(e,t){if(jt.set(e,t),jt.size>200){let r=0;for(let n of jt.keys()){if(r++>=20)break;jt.delete(n)}}}function bm(e){let t=e.indexOf(" from ");if(t===-1)return null;let r=e.slice(t+6).trim(),n=r[0];if(n!=='"'&&n!=="'")return null;let i=r.indexOf(n,1);if(i===-1)return null;let o=r.slice(1,i),s=e.slice(0,t).trim(),a=s.startsWith("import type ");if(s.startsWith("import "))s=s.slice(7).trim();if(s.startsWith("type "))s=s.slice(5).trim();let c=null,f=[],u=!1,l=s.indexOf("{"),p=s.lastIndexOf("}");if(l!==-1&&p!==-1){let C=s.slice(0,l).trim();if(C.endsWith(","))c=C.slice(0,-1).trim()||null;let E=s.slice(l+1,p),y=0;for(let x=0;x<=E.length;x++)if(x===E.length||E.charCodeAt(x)===44){let S=y,M=x;while(S<M&&(E.charCodeAt(S)===32||E.charCodeAt(S)===9||E.charCodeAt(S)===10))S++;while(M>S&&(E.charCodeAt(M-1)===32||E.charCodeAt(M-1)===9||E.charCodeAt(M-1)===10))M--;if(S<M)f.push(E.slice(S,M));y=x+1}}else{let C=s.trim();if(C.startsWith("* as "))c=C.slice(5).trim()||null,u=!0;else c=C||null}return{defaultName:c,namedItems:f,source:o,isTypeOnly:a,isNamespace:u}}function Sm(e){let t=vm(e);if(t)return t;let r=[],n=e.indexOf(" from ");if(n===-1)return rc(e,r),r;let i=e.slice(0,n).trim();if(i.startsWith("import "))i=i.slice(7).trim();if(i.startsWith("type "))i=i.slice(5).trim();let o=i.indexOf("{"),s=i.lastIndexOf("}");if(o!==-1&&s!==-1){let a=i.slice(0,o).trim();if(a.endsWith(",")){let f=a.slice(0,-1).trim();if(f)r.push(f)}else if(a&&!a.includes(","))r.push(a);let c=i.slice(o+1,s).split(",");for(let f=0;f<c.length;f++){let u=c[f].trim();if(!u)continue;if(u.startsWith("type "))u=u.slice(5).trim();let l=u.indexOf(" as ");if(l!==-1)u=u.slice(l+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 rc(e,r),r}function ic(e,t){throw Error(t||`Unexpected value: ${e}`)}function $m(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function nc(e){let t=new Set,r=0,n=e.length;while(r<n){let i=e.charCodeAt(r);if(i>=65&&i<=90||i>=97&&i<=122||i===95||i===36||i>127){let o=r;r++;while(r<n&&$m(e.charCodeAt(r)))r++;t.add(e.substring(o,r))}else r++}return t}function lc(e,t,r=!0,n=["bun"]){let i="",o=t.sourceCode;if(o){let I=0;while(I<o.length&&(o.charCodeAt(I)===32||o.charCodeAt(I)===9||o.charCodeAt(I)===10||o.charCodeAt(I)===13))I++;if(I<o.length-2&&o.charCodeAt(I)===47&&o.charCodeAt(I+1)===47&&o.charCodeAt(I+2)===47){let j=hm(o);if(j.length>0)for(let T=0;T<j.length;T++){if(i)i+=`
|
|
233
|
+
`;i+=j[T]}}}let s=[],a=[],c=[],f=[],u=[],l=[],p=[],C=[],E=[];for(let I of e){let j=I.kind;switch(j){case"import":s.push(I);break;case"function":a.push(I);break;case"variable":c.push(I);break;case"interface":f.push(I);break;case"type":u.push(I);break;case"class":l.push(I);break;case"enum":p.push(I);break;case"module":C.push(I);break;case"export":E.push(I);break;case"namespace":C.push(I);break;case"unknown":break;default:ic(j,`Unhandled declaration kind: ${j}`)}}let y=new Set,x=[],S=[],M=[],D=new Set;for(let I of E){let j=At(I.leadingComments,r);if(I.text.startsWith("export default")){let T=I.text.endsWith(";")?I.text:`${I.text};`;M.push(j+T)}else{let T=I.text.trim();if(!T.endsWith(";"))T+=";";let Re=T.match(Am);if(Re){let pe=Re[1],ee=0;for(let ie=0;ie<=pe.length;ie++)if(ie===pe.length||pe.charCodeAt(ie)===44){let ne=ee,ce=ie;while(ne<ce&&pe.charCodeAt(ne)<=32)ne++;while(ce>ne&&pe.charCodeAt(ce-1)<=32)ce--;if(ne<ce)y.add(pe.slice(ne,ce));ee=ie+1}}let V=j+T;if(!D.has(V))if(D.add(V),V.includes("export type"))x.push(V);else S.push(V)}}let O=new Map;if(s.length>0)for(let I of s){let j=Sm(I.text);for(let T of j)O.set(T,I)}let H=new Set;if(f.length>0){let I=[];for(let j of a)if(j.isExported)I.push(j.text);for(let j of l)I.push(j.text);for(let j of u)I.push(j.text);if(I.length>0){let j=nc(I.join(`
|
|
234
|
+
`));for(let T of f)if(j.has(T.name))H.add(T.name)}}let K=[];if(s.length>0){let I=new Set,j=[];for(let V of a)if(V.isExported)j.push(V.text);for(let V of c)if(j.push(V.text),V.typeAnnotation)j.push(V.typeAnnotation);else if(V.isExported&&V.value)j.push(tc(V,!1));for(let V of f)if(V.isExported||H.has(V.name))j.push(V.text);for(let V of u)j.push(V.text);for(let V of l)j.push(V.text);for(let V of p)j.push(V.text);for(let V of C)j.push(V.text);for(let V of E)j.push(V.text);let T=j.join(`
|
|
235
|
+
`);if(T&&O.size>0){let V=nc(T);for(let pe of O.keys())if(V.has(pe))I.add(pe)}for(let V of y)if(O.has(V))I.add(V);for(let V of s){if(V.isSideEffect){let Z=V.text.trim(),Y=Z.endsWith(";")?Z:`${Z};`;K.push(Y);continue}let pe=bm(V.text);if(!pe)continue;let{defaultName:ee,namedItems:ie,source:ne,isTypeOnly:ce,isNamespace:N}=pe,z=ee?I.has(ee):!1,J="",te=0;for(let Z=0;Z<ie.length;Z++){let Y=ie[Z],oe=Y.charCodeAt(0)===116&&Y.startsWith("type ")?Y.slice(5).trim():Y.trim(),Fe=oe.indexOf(" as ");if(Fe!==-1)oe=oe.slice(Fe+4).trim();if(I.has(oe)){if(te>0)J+=", ";J+=Y,te++}}if(z||te>0){let Z=ce?"import type ":"import ";if(z&&ee)if(N)Z+=`* as ${ee}`;else Z+=te>0?`${ee}, { ${J} }`:ee;else if(te>0)Z+=`{ ${J} }`;Z+=` from '${ne}';`,K.push(Z)}}let Re=n.length;if(K.length>1){if(oc!==n)oc=n,sc=n.map((ie)=>`from '${ie}`),ac=n.map((ie)=>`from "${ie}`);let V=sc,pe=ac,ee=new Map;for(let ie of K){let ne=Re;for(let ce=0;ce<n.length;ce++)if(ie.includes(V[ce])||ie.includes(pe[ce])){ne=ce;break}ee.set(ie,ne)}K.sort((ie,ne)=>{let ce=ee.get(ie),N=ee.get(ne);return ce!==N?ce-N:ie.localeCompare(ne)})}}for(let I=0;I<K.length;I++){if(i)i+=`
|
|
236
236
|
`;i+=K[I]}for(let I=0;I<x.length;I++){if(i)i+=`
|
|
237
|
-
`;i+=x[I]}let me=[a,c,f,u,l,p,C];for(let I=0;I<me.length;I++){let j=me[I];for(let T=0;T<j.length;T++){let Re=j[T],V="",pe=Re.kind;switch(pe){case"function":V=
|
|
237
|
+
`;i+=x[I]}let me=[a,c,f,u,l,p,C];for(let I=0;I<me.length;I++){let j=me[I];for(let T=0;T<j.length;T++){let Re=j[T],V="",pe=Re.kind;switch(pe){case"function":V=pm(Re,r);break;case"variable":V=tc(Re,r);break;case"interface":V=gm(Re,r);break;case"type":V=ym(Re,r);break;case"class":V=Cm(Re,r);break;case"enum":V=wm(Re,r);break;case"module":case"namespace":V=Em(Re,r);break;case"import":case"export":case"unknown":break;default:ic(pe,`Unhandled declaration kind in processor: ${pe}`)}if(V){if(i)i+=`
|
|
238
238
|
`;i+=V}}}for(let I=0;I<S.length;I++){if(i)i+=`
|
|
239
239
|
`;i+=S[I]}for(let I=0;I<M.length;I++){if(i)i+=`
|
|
240
|
-
`;i+=M[I]}if(!i&&(s.length>0||E.length>0))return"export {};";return i}var
|
|
241
|
-
${
|
|
242
|
-
${ne}`);else q.debug(`[no changes] ${O}`)}catch{q.info(`[new file] ${je(r.cwd,O)}`)}},K=(ee)=>{if(!r.validate)return 0;let ie=
|
|
243
|
-
...`:"")),q.debug("--- End preview ---")};if(o){let ee=o.getCachedIfValid(S,r.cwd);if(ee){if(r.bundle)l.set(S,ee);await H(ee);let ie=K(ee);if(r.dryRun)me(ee);else{if(await
|
|
244
|
-
`);if(r.failOnUnresolvedReExport)throw Error(D);q.warn(D),q.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(r.bundle&&(s.filesGenerated>0||a>0)&&c.length>0)try{q.debug("Bundling declarations...");let S=c.length===1&&!!r.bundleOutput;for(let M of c){let D=await
|
|
240
|
+
`;i+=M[I]}if(!i&&(s.length>0||E.length>0))return"export {};";return i}var cm,fm,um,jt,Am,oc=null,sc,ac;var cc=ge(()=>{bo();cm=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,fm=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,um=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;jt=new Map;Am=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,sc=[],ac=[]});import{existsSync as fc}from"fs";import{mkdir as xo,readdir as xm,realpath as Tm,rm as Rm}from"fs/promises";import{availableParallelism as Pm}from"os";import{basename as Po,dirname as Tr,extname as Om,isAbsolute as Rr,parse as km,relative as je,resolve as et}from"path";async function uc(e,t,r,n,i){let o=Po(e)||"output.d.ts",s=je(Tr(e),t),a=`${o}.map`,c=r.lastIndexOf(`
|
|
241
|
+
${Ao()}`),f=c===-1?r:r.slice(0,c),u=Xl(f,o,s,n),l=`${e}.map`;return await Ar(l,JSON.stringify(u)),q.debug(` Generated source map: ${je(i,l)}`),a}async function Oo(e){let t=Date.now(),r={...La,...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 S of r.plugins)n.register(S),q.debug(`Registered plugin: ${S.name}`);r=await n.runOnStart(r)}if(await Dm(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await ql(r);let i=r.typeMappings?_i(r.typeMappings):void 0,o=null;if(r.incremental){if(o=new cn(r),r.clearCache){if(q.debug("Clearing build cache..."),!r.dryRun)o.clear()}else if(o.load()){let S=o.getStats();q.debug(`Loaded build cache with ${S.entries} entries`)}else q.debug("No existing build cache found, starting fresh");if(!r.dryRun)ss(r.cwd)}let s={generationMode:r.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},a=0;q.debug("Starting DTS generation..."),q.debug(`Using ${s.generationMode} declaration generation path`),q.debug("Config:",r);let c=await Wm(r);Lm(r,c);let f=c.slice(),u=null;if(r.autoIncludeReExports!==!1&&f.length>0){u=await rn(f,{includeImports:!0});let S=et(r.cwd,r.root),M=r.exclude||[],D=[];for(let O of u.reachable){if(f.includes(O))continue;if(!Ro(O))continue;if(O.endsWith(".d.ts"))continue;if(O.includes("node_modules"))continue;if(!Pr(O,S)){q.warn(`Skipping auto-included source outside root: ${je(r.cwd,O)}`);continue}if(To(O,M,S))continue;D.push(O)}if(D.length>0)f=[...f,...D],q.debug(`Auto-included ${D.length} file(s) reached via relative re-exports`)}if(Bm(f,r),r.clean&&!r.dryRun)await Fm(r);if(o&&!r.dryRun){let S=o.prune(new Set(f),r.cwd);if(S>0)q.debug(`Pruned ${S} deleted files from cache`)}if(q.debug(`Found ${f.length} TypeScript files`),r.progress&&f.length>0){let S=r.parallel?"parallel":"sequential";q.info(`Processing ${f.length} files (${S})...`)}let l=new Map,p=async(S,M)=>{let D;try{let O=Or(S,r),H=async(ee)=>{if(!r.diff)return;try{let ie=await Pt(O),ne=Zl(ie,ee,je(r.cwd,O));if(ne)q.info(`
|
|
242
|
+
${ne}`);else q.debug(`[no changes] ${O}`)}catch{q.info(`[new file] ${je(r.cwd,O)}`)}},K=(ee)=>{if(!r.validate)return 0;let ie=Yl(ee,O);if(ie.isValid)return q.debug(`[validation] ${O} - OK`),0;q.warn(`[validation] ${je(r.cwd,O)} has ${ie.errors.length} error(s):`);for(let ne of ie.errors){let ce=` Line ${ne.line}:${ne.column}`;if(ne.code)ce+=` [${ne.code}]`;if(ce+=` - ${ne.message}`,q.warn(ce),ne.suggestion)q.warn(` Suggestion: ${ne.suggestion}`)}return ie.errors.length},me=(ee)=>{q.info(`[dry-run] Would generate: ${O}`),q.debug("--- Content preview ---"),q.debug(ee.slice(0,500)+(ee.length>500?`
|
|
243
|
+
...`:"")),q.debug("--- End preview ---")};if(o){let ee=o.getCachedIfValid(S,r.cwd);if(ee){if(r.bundle)l.set(S,ee);await H(ee);let ie=K(ee);if(r.dryRun)me(ee);else{if(await xo(Tr(O),{recursive:!0}),r.declarationMap)D=M??await Pt(S),await uc(O,S,ee,D,r.cwd);await Ar(O,ee,r.lineEnding)}return q.debug(`[cached] ${je(r.cwd,O)}`),{success:!0,file:S,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:ie}}}D=M??await Pt(S);let{content:I,declarationCount:j,importCount:T,exportCount:Re}=await _m(S,D,r,n,i);if(r.bundle)l.set(S,I);let V=I;if(r.prettier||r.indentStyle||r.indentSize){let ee=await Al(V,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},O);V=ee.content;for(let ie of ee.warnings??[])q.warn(`[format] ${ie}`)}if(r.declarationMap){let ee=`${Po(O)||"output.d.ts"}.map`;V=Ql(V,ee)}await H(V);let pe=K(V);if(r.dryRun)me(V);else{if(await xo(Tr(O),{recursive:!0}),r.declarationMap&&D)await uc(O,S,V,D,r.cwd);if(await Ar(O,V,r.lineEnding),o&&D)o.update(S,D,V,r.cwd);q.debug(`Generated: ${O}`)}return{success:!0,file:S,declarationCount:j,importCount:T,exportCount:Re,validationErrorCount:pe}}catch(O){let H=Ba(O,S,D);if(r.plugins&&r.plugins.length>0)await n.runOnError(O instanceof Error?O:Error(String(O)),S,D||"");return{success:!1,file:S,declarationCount:0,importCount:0,exportCount:0,dtsError:H,validationErrorCount:0}}},C=r.parallel||r.parallel!==!1&&f.length>=10,E=ls(r.concurrency,Pm?.()??8),y=new Map;if(C&&f.length>1){let S=f.map(async(M)=>{try{let D=await Pt(M);return{file:M,source:D}}catch{return{file:M,source:null}}});for(let M of await Promise.all(S))if(M.source!==null)y.set(M.file,M.source)}let x=(S)=>{if(s.filesProcessed++,S.success){if(S.cached)a++;else s.filesGenerated++,s.declarationsFound+=S.declarationCount,s.importsProcessed+=S.importCount,s.exportsProcessed+=S.exportCount;if(r.validate){if(s.filesValidated++,S.validationErrorCount)s.validationErrors+=S.validationErrorCount}}else if(s.filesFailed++,S.dtsError){s.errors.push(S.dtsError);let M=Ga(S.dtsError);if(r.continueOnError)q.warn(M);else throw q.error(M),Error(S.dtsError.message)}};if(C)for(let S=0;S<f.length;S+=E){let M=f.slice(S,S+E),D=await Promise.all(M.map((O)=>p(O,y.get(O))));for(let O of D)x(O);if(r.progress){let O=Math.round(s.filesProcessed/f.length*100);q.info(`[${s.filesProcessed}/${f.length}] ${O}%`)}}else for(let S of f){let M=await p(S);if(x(M),r.progress){let D=Math.round(s.filesProcessed/f.length*100),O=M.cached?"[cached]":"";q.info(`[${s.filesProcessed}/${f.length}] ${D}% - ${je(r.cwd,S)} ${O}`)}}if(o&&!r.dryRun)o.save(),q.debug("Saved build cache");if(!r.bundle){let S=[];if(u)for(let M of u.unresolved)S.push({from:M.from,specifier:M.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&f.length>0){let M=new Set(f);for(let D of f){let O;try{O=await Pt(D)}catch{continue}for(let H of tn(O)){if(!H.specifier.startsWith("."))continue;let K=zt(H.specifier,D);if(!K.resolved)S.push({from:D,specifier:H.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(K.resolved)&&!M.has(K.resolved))S.push({from:D,specifier:H.specifier,reason:"not-emitted"})}}}if(S.length>0){let M=[];M.push(`Found ${S.length} re-export(s) pointing at siblings that won't be in the output:`);for(let O of S){let H=je(r.cwd,O.from);if(O.reason==="missing")M.push(` ${H} \u2192 '${O.specifier}' (path not found on disk)`);else M.push(` ${H} \u2192 '${O.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let D=M.join(`
|
|
244
|
+
`);if(r.failOnUnresolvedReExport)throw Error(D);q.warn(D),q.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(r.bundle&&(s.filesGenerated>0||a>0)&&c.length>0)try{q.debug("Bundling declarations...");let S=c.length===1&&!!r.bundleOutput;for(let M of c){let D=await rn([M],{includeImports:!0}),O=new Set;for(let I of D.reachable){if(I.endsWith(".d.ts"))continue;if(I.includes("node_modules"))continue;O.add(I)}let H=f.filter((I)=>O.has(I));if(!H.includes(M))H.push(M);let K=es(M,H,l,{cwd:r.cwd,keepComments:r.keepComments});for(let I of new Set(K.warnings))q.warn(`[bundle] ${I}`);let me=S?et(r.cwd,r.outdir,r.bundleOutput):Or(M,r);if(r.dryRun)q.info(`[dry-run] Would bundle ${K.files.length} files to: ${je(r.cwd,me)}`);else await xo(Tr(me),{recursive:!0}),await Ar(me,K.content,r.lineEnding),q.info(`Bundled ${K.files.length} files to: ${je(r.cwd,me)}`);if(S)break}}catch(S){let M=S instanceof Error?S.message:String(S);q.error(`Bundle failed: ${M}`)}if(s.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(s,null,2));else{if(q.info(`
|
|
245
245
|
--- Generation Statistics ---`),q.info(`Files processed: ${s.filesProcessed}`),q.info(`Files generated: ${s.filesGenerated}`),a>0)q.info(`Files cached: ${a}`);if(s.filesFailed>0)q.info(`Files failed: ${s.filesFailed}`);if(q.info(`Declarations found: ${s.declarationsFound}`),q.info(`Imports processed: ${s.importsProcessed}`),q.info(`Exports processed: ${s.exportsProcessed}`),s.filesValidated>0){if(q.info(`Files validated: ${s.filesValidated}`),s.validationErrors>0)q.info(`Validation errors: ${s.validationErrors}`)}if(q.info(`Duration: ${s.durationMs}ms`),s.errors.length>0){q.info(`
|
|
246
246
|
Errors:`);for(let S of s.errors){let M=` - ${S.file}`;if(S.location)M+=`:${S.location.line}:${S.location.column}`;if(S.code)M+=` [${S.code}]`;if(M+=`: ${S.message}`,q.info(M),S.suggestion)q.info(` Suggestion: ${S.suggestion}`)}}q.info(`-----------------------------
|
|
247
|
-
`)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(s);return q.debug("DTS generation complete!"),s}async function
|
|
247
|
+
`)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(s);return q.debug("DTS generation complete!"),s}async function hc(e){try{return await Tm(e)}catch{return et(e)}}async function Dm(e){let t=et(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(Rr(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=et(t,e.bundleOutput);if(!Pr(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===km(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([hc(t),hc(et(e.cwd,e.root))]);if(Pr(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function Im(e){let t=xr.get(e);if(!t){if(t=new dc(e),xr.set(e,t),xr.size>Mm){let r=xr.keys().next().value;if(r!==void 0)xr.delete(r)}}return t}async function Fm(e){let t=et(e.cwd,e.outdir);async function r(n){let i;try{i=await xm(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(o)=>{let s=et(n,o.name);if(o.isDirectory()){await r(s);return}if(o.name.endsWith(".d.ts")||o.name.endsWith(".d.mts")||o.name.endsWith(".d.cts")||o.name.endsWith(".d.ts.map")||o.name.endsWith(".d.mts.map")||o.name.endsWith(".d.cts.map"))await Rm(s,{force:!0})}))}await r(t)}function To(e,t,r){if(!t||t.length===0)return!1;let n=je(r,e);for(let i of t){let o=Im(i);if(o.match(n)||o.match(e))return!0}return!1}function Lm(e,t){let r=et(e.cwd,e.root),n=` root: ${r}
|
|
248
248
|
entrypoints: ${e.entrypoints.map((o)=>JSON.stringify(o)).join(", ")||"(none)"}
|
|
249
249
|
`+(e.exclude?.length?` exclude: ${e.exclude.map((o)=>JSON.stringify(o)).join(", ")}
|
|
250
|
-
`:"")+"Entrypoints are resolved relative to --root. Pass several by repeating --entrypoints or separating them with commas.";if(t.length===0){if(e.entrypoints.filter((o)=>Rr(o)&&
|
|
251
|
-
${n}`)}let i=e.entrypoints.filter((o)=>{if(
|
|
252
|
-
${n}`)}async function
|
|
250
|
+
`:"")+"Entrypoints are resolved relative to --root. Pass several by repeating --entrypoints or separating them with commas.";if(t.length===0){if(e.entrypoints.filter((o)=>Rr(o)&&fc(o)&&!Pr(o,r)).length===e.entrypoints.length)return;throw Error(`No source files matched. Nothing was generated.
|
|
251
|
+
${n}`)}let i=e.entrypoints.filter((o)=>{if(Nm.test(o))return!1;return!fc(Rr(o)?o:et(r,o))});if(i.length>0)throw Error(`Entrypoint${i.length>1?"s":""} not found: ${i.map((o)=>JSON.stringify(o)).join(", ")}
|
|
252
|
+
${n}`)}async function Wm(e){let t=[],r=et(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let o of i)if(Rr(o)&&Ro(o)){if(!o.includes("node_modules")){if(!Pr(o,r)&&e.outputStructure!=="flat")q.warn(`Skipping entrypoint outside root: ${je(e.cwd,o)}`);else if(!To(o,n,r))t.push(o)}}else{let s=new dc(o);for await(let a of s.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(Ro(a)&&!a.includes("node_modules")){if(!To(a,n,r))t.push(a)}}return[...new Set(t.map((o)=>et(o)))].sort()}function Pr(e,t){let r=je(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Rr(r)}function Bm(e,t){let r=new Map;for(let n of e){let i=Or(n,t),o=r.get(i);if(o&&o!==n)throw Error(`Output path collision: ${je(t.cwd,o)} and ${je(t.cwd,n)} both emit ${je(t.cwd,i)}`);r.set(i,n)}}function Ro(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function Or(e,t){let r=et(t.cwd,t.root),n=je(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=Po(n);return et(t.cwd,t.outdir,i)}}function Gm(e,t,r=""){let n=je(Tr(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}function jm(e,t,r){let n=Or(t,r),i=(o)=>{let s=zt(o,t);if(!s.isRelative||!s.resolved)return o;if(/\.d\.(?:ts|mts|cts)$/.test(s.resolved))return o;let a=o.match(/[?#].*$/)?.[0]??"",c=a?o.slice(0,-a.length):o,f=Om(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return Gm(n,Or(s.resolved,r),u)+a};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(o,s,a,c)=>`${s}${a}${i(c)}${a}`).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(o,s,a,c)=>`${s}${a}${i(c)}${a}`).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(o,s,a,c)=>`${s}${a}${i(c)}${a}`)}async function _m(e,t,r,n,i){let o=t;if(n)o=await n.runOnBeforeFile(e,t);let s=Sl(o,e,r.keepComments,r.isolatedDeclarations??!1);if(n)s=await n.runOnDeclarations(e,o,s);let a=0,c=0;for(let u=0;u<s.length;u++){let l=s[u];if(l.kind==="import")a++;if(l.kind==="export"||l.isExported)c++}let f=lc(s,{filePath:e,sourceCode:o,declarations:s},r.keepComments,r.importOrder);if(f=jm(f,e,r),i)f=Il(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=Ol(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)f=await n.runOnAfterFile(e,o,f);return{content:f,declarationCount:s.length,importCount:a,exportCount:c}}var dc,Mm=50,xr,Nm;var mc=ge(()=>{Lr();nn();ts();as();cs();Wa();ds();ja();$l();xl();Tl();kl();Fl();ec();cc();({Glob:dc}=globalThis.Bun);xr=new Map;Nm=/[*?[\]{}!]/});var pc=ge(()=>{mc()});import{createHash as Um}from"crypto";import{existsSync as Km,readFileSync as zm,writeFileSync as Hm}from"fs";import{dirname as Jm,join as qm,relative as gc,resolve as kr,sep as Vi}from"path";import Cc from"process";class wc{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 Ec{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=qm(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(Km(this.manifestPath)){let t=JSON.parse(zm(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}=Vm("fs");e(this.cacheDir,{recursive:!0}),Hm(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 Ym(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return Um("md5").update(JSON.stringify(t)).digest("hex")}function vc(e={}){let{onSuccess:t,onError:r,failOnError:n=!0,incremental:i=!1,cacheDir:o=".dtsx-cache",on:s,timeout:a=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,l=new wc;if(s){for(let[p,C]of Object.entries(s))if(C)l.on(p,C)}return{name:"bun-plugin-dtsx",async setup(p){let C=Date.now(),E=null,y=0;try{let x=Qm(u,p),S=Ym(x);if(x.clean){let H=kr(x.cwd??Cc.cwd(),x.outdir??"./dist");if(yc.has(H))x.clean=!1;else yc.add(H)}if(i)E=new Ec(kr(o),S);if(await l.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 D=await(async()=>new Promise((H,K)=>{let me=setTimeout(()=>{K(new Mr(`Generation timed out after ${a}ms`,"TIMEOUT_ERROR",{timeout:a}))},a);Oo(x).then((I)=>{clearTimeout(me),H(I)}).catch((I)=>{clearTimeout(me),K(I)})}))(),O=Date.now()-C;if(E)E.save();if(await l.emit("complete",{type:"complete",stats:D,duration:O,fromCache:y}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${O}ms`),y>0)console.log(`[bun-plugin-dtsx] ${y} files served from cache`)}if(t)await t(D)}catch(x){let S=Zm(x);if(await l.emit("error",{type:"error",error:S}),r)await r(S);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${S.code}`),console.error(` Message: ${S.message}`),S.context)console.error(` Context: ${JSON.stringify(S.context)}`);if(f&&S.stack)console.error(` Stack: ${S.stack}`)}if(n&&!c)throw S}}}}function Zm(e){if(e instanceof Mr)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 Mr(e.message,t,{originalError:e.name},e)}return new Mr(String(e),"GENERATION_ERROR")}function Xm(e){let t=e.map((n)=>Jm(n).split(Vi)),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(Vi)||Vi}function Qm(e,t){let r=e.cwd||Cc.cwd(),n=t?.config?.entrypoints,i=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",o=e.root||e.build?.config.root||t?.config.root;if(!o&&n?.length){let a=Xm(n.map((c)=>kr(r,c)));o=gc(r,a)||"."}o=o||"./src";let s=e.entrypoints;if(!s)if(n?.length){let a=kr(r,o),c=[];for(let f of n){let u=kr(r,f);if(u===a||u.startsWith(a+Vi))c.push(gc(a,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${o}": ${f}`)}s=c.length?c:["index.ts"]}else s=["index.ts"];return{...e,cwd:r,root:o,entrypoints:s,outdir:i,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}var Vm,Mr,yc;var bc=ge(()=>{pc();Vm=import.meta.require;Mr=class Mr 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}}};yc=new Set});import{mkdir as ep,stat as tp}from"fs/promises";import{bold as ko,dim as Mo,green as rp,italic as Sc,log as ip}from"@stacksjs/cli";import{path as ot}from"@stacksjs/path";import{glob as $c}from"@stacksjs/storage";function Qi(e){let t=new Map;for(let s of e){if(t.has(s.name))throw Error(`duplicate package name: ${s.name}`);t.set(s.name,s)}let r=new Map,n=new Set,i=(s,a)=>{let c=r.get(s);if(c!==void 0)return c;if(n.has(s))throw Error(`dependency cycle: ${[...a,s].join(" -> ")}`);n.add(s);let f=t.get(s).dependencies.filter((l)=>l!==s&&t.has(l)),u=f.length?1+Math.max(...f.map((l)=>i(l,[...a,s]))):0;return n.delete(s),r.set(s,u),u},o=[];for(let s of[...e].sort((a,c)=>a.name.localeCompare(c.name)))(o[i(s.name,[])]||=[]).push(s);return o.filter(Boolean)}import{existsSync as Nc,readdirSync as Lc,readFileSync as Ko}from"fs";import{join as en}from"path";function Wc(e){return[...Lc(e,{withFileTypes:!0}).filter((r)=>r.isDirectory()).map((r)=>en(e,r.name)),e].filter((r)=>{let n=en(r,"package.json");if(!Nc(n))return!1;let i=JSON.parse(Ko(n,"utf8"));return!i.private&&!!i.scripts?.build})}async function Bc(e){let t=e.map((i)=>{let o=JSON.parse(Ko(en(i,"package.json"),"utf8"));if(!o.name||!o.scripts?.build)throw Error(`Not a buildable workspace package: ${i}`);return{name:o.name,dir:i,dependencies:Object.keys(o.dependencies??{})}}),r=Qi(t),n=[];for(let{name:i,dir:o,dependencies:s}of r.flat()){let a=n.filter((f)=>f.exitCode!==0&&s.includes(f.name)).map((f)=>f.name);if(a.length){console.error(`Cannot build ${o}: dependencies failed: ${a.join(", ")}`),n.push({name:i,dir:o,exitCode:null,blockedBy:a});continue}console.log(`Building ${o}`);let c=Bun.spawn([process.execPath,"run","build"],{cwd:o,stdout:"inherit",stderr:"inherit"});n.push({name:i,dir:o,exitCode:await c.exited,blockedBy:[]})}return n}async function np(e){let t=await $c([ot.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let n of t){let i=await Bun.file(n).text();try{r.transformSync(i)}catch(o){throw Error(`Invalid declaration generated at ${n}: ${o instanceof Error?o.message:String(o)}`)}}}async function op(e){let t=ot.resolve(e,"dist","index.js");if(!await Bun.file(t).exists())return;let r=Bun.spawnSync({cmd:[process.execPath,"-e",`try { await import(${JSON.stringify(t)}) } catch (error) { console.error(error); process.exit(1) }`],stdout:"ignore",stderr:"pipe",env:{...process.env,NODE_ENV:"test"}});if(r.exitCode===0)return;let n=new TextDecoder().decode(r.stderr??new Uint8Array),i=/SyntaxError|needs to refer to a top-level declared variable|does not provide an export named|Export named .* not found/i;if(i.test(n)){let o=n.split(`
|
|
253
253
|
`).find((s)=>i.test(s))??n.trim().split(`
|
|
254
254
|
`)[0];throw Error(`Built package at ${t} cannot be imported: ${o}
|
|
255
|
-
Fix the generated module at its source before publishing.`)}}async function
|
|
256
|
-
`),await
|
|
255
|
+
Fix the generated module at its source before publishing.`)}}async function iC(e){let r=Date.now()-e.startTime,n=e.pkgName??`@stacksjs/${ot.basename(e.dir)}`;if(e.result.errors&&e.result.errors.length>0)throw console.error("Build errors:",e.result.errors),Error(`Build failed with errors: ${JSON.stringify(e.result.errors)}`);else if(e.result.success!==void 0&&!e.result.success){let o=e.result.logs?.[0]||"Unknown build error";throw console.log(o),Error(`Build failed: ${o}`)}await Bun.write(ot.resolve(e.dir,"dist","tsconfig.json"),`${JSON.stringify({compilerOptions:{paths:{}}},null,2)}
|
|
256
|
+
`),await np(e.dir),await op(e.dir);let i=await $c([ot.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let o of i){let s=await tp(o),a;if(s.size<1048576)a=`${(s.size/1024).toFixed(2)}kb`;else a=`${(s.size/1024/1024).toFixed(2)}mb`;let c=ot.relative(e.dir,o).replace("dist/","");console.log(`${ko(Mo(`[${a}]`))} ${Mo("dist/")}${c}`)}console.log(`${ko(Mo(`[${r}ms]`))} Built ${Sc(ko(rp(n)))}`)}async function nC(e){let t=e.pkgName??`@stacksjs/${ot.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else ip.info(`Building ${Sc(t)}...`);return{startTime:Date.now()}}async function oC(e){await Promise.resolve().then(() => bc());let r=ot.resolve(e.dir,"src"),n=ot.resolve(e.dir,"dist"),i=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((s)=>!s.endsWith(".d.ts")).filter((s)=>!s.endsWith(".test.ts")&&!s.endsWith(".spec.ts"));await Bun.build({entrypoints:i.map((s)=>ot.resolve(r,s)),outdir:n,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??ap(),plugins:[vc({root:r,outdir:n})]});let o=new Bun.Transpiler({loader:"ts",target:"bun",minifyWhitespace:!0,define:{"process.env.NODE_ENV":"process.env.NODE_ENV"}});for(let s of i){let a=o.transformSync(await Bun.file(ot.resolve(r,s)).text());a=sp(a);let c=ot.resolve(n,s.replace(/\.ts$/,".js"));await ep(ot.dirname(c),{recursive:!0}),await Bun.write(c,a)}}function sp(e){return e.replace(/(['"])(\.\.?\/[^'"]+?)(?<!\.d)\.tsx?\1/g,"$1$2.js$1")}function ap(e=[]){let t=[];try{let r=Fc("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{Bc as buildWorkspacePackages,Qi as dependencyLayers,ap as frameworkExternal,nC as intro,iC as outro,sp as rewriteRelativeTsSpecifiers,oC as transpilePackage,np as validateDeclarations,op as validateRuntimeExports,Wc as workspaceBuildTargets};
|